Docker & K8S

Docker & K8S - Hangman을 Dockerization

터칭 데이터 2023. 12. 19. 17:36

 

 

Hangman 서비스를 Dockerization하기

앞서 살펴본 Hangman 서비스를 Docker Image로 빌드하고 Docker Container로 실행해보자

 

 

 

 

 

 

 

 

Dockerfile 리뷰

 

 

FROM python:3.8-slim-buster
LABEL Maintainer="keeyong@gmail.com"
WORKDIR /app
COPY app.py ./
COPY requirements.txt ./
RUN pip3 install -r requirements.txt
EXPOSE 4000
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0", "--port=4000"]

 

LABEL은 key와 value 형태로 메타데이터에 정보를 저장합니다. docker insepect 명령으로 찾아볼 수 있습니다. 위의 LABEL은 Maintainer가 누구인지 작성한 예입니다.

 

EXPOSE 4000은 아무런 기능은 없지만 참고사항 역할로 이 포트 번호를 사용하니 포트 맵핑을 할 때 참고하라는 정보를 담는 목적으로 적었습니다.

 

 

 

 

 

 

 

 

 

 

 

전체 과정 데모

 

과정에서 사용해볼 일부 docker 명령

docker inspect 명령
docker run "-d" 옵션
docker stop 명령

 

순서:

docker build --platform=linux/amd64 -t keeyong/hangman .
docker image ls
docker inspect keeyong/hangman
docker run -p 4000:4000 keeyong/hangman
docker run -p 4000:4000 -d keeyong/hangman
docker push keeyong/hangman

 

 

 

 

 

 

 

 

 

 

실습

 

 

먼저 hangman 파일이 있는 https://github.com/learndataeng/hangman_web repo를 저의 적당한 공간에 git clone 하겠습니다. 디렉토리로 이동한 후

 

 

 

 

 

Dockerfile로 이미지 build하기

 

 

git clone https://github.com/learndataeng/hangman_web.git

PS D:\dev_KDT\hangman_homework> git clone https://github.com/learndataeng/hangman_web.git

Cloning into 'hangman_web'...
remote: Enumerating objects: 25, done.
remote: Counting objects: 100% (10/10), done.
remote: Compressing objects: 100% (6/6), done.
remote: Total 25 (delta 7), reused 4 (delta 4), pack-reused 15
Receiving objects: 100% (25/25), 8.52 KiB | 4.26 MiB/s, done.
Resolving deltas: 100% (10/10), done.

 

 

 

그러면 hangman_homework 디렉토리 아래에 hangman_web으로 repo가 하나 생성될 것입니다.

 

 

 

 

 

 

아래와 같이 작성된 Dockerfile을

FROM python:3.8-slim-buster
LABEL Maintainer="keeyong@gmail.com"
WORKDIR /app
COPY app.py ./
COPY requirements.txt ./
RUN pip3 install -r requirements.txt
EXPOSE 4000
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0", "--port=4000"]

 

아무 텍스트 에디터에서 Dockerfile이라는 이름으로 작성한 후 alltype 형식으로 저장해주세요. 확장자로 txt가 붙으면 이미지로 build할 때 에러가 발생합니다.

 

 

 

Dockerfile의 위치는 hangman_web에 위치시킵니다.

 

 

 

 

 

 

 

docker build --platform=linux/amd64 -t (ID)/hangman .

PS D:\Dev_KDT\hangman_homework\hangman_web> docker build --platform=linux/amd64 -t (ID)/hangman .
[+] Building 3.6s (11/11) FINISHED                                                                       docker:default
 => [internal] load build definition from Dockerfile                                                               0.0s
 => => transferring dockerfile: 283B                                                                               0.0s
 => [internal] load .dockerignore                                                                                  0.0s
 => => transferring context: 2B                                                                                    0.0s
 => [internal] load metadata for docker.io/library/python:3.8-slim-buster                                          3.3s
 => [auth] library/python:pull token for registry-1.docker.io                                                      0.0s
 => [1/5] FROM docker.io/library/python:3.8-slim-buster@sha256:8799b0564103a9f36cfb8a8e1c562e11a9a6f2e3bb214e2adc  0.0s
 => [internal] load build context                                                                                  0.0s
 => => transferring context: 4.36kB                                                                                0.0s
 => CACHED [2/5] WORKDIR /app                                                                                      0.0s
 => CACHED [3/5] COPY app.py ./                                                                                    0.0s
 => CACHED [4/5] COPY requirements.txt ./                                                                          0.0s
 => CACHED [5/5] RUN pip3 install -r requirements.txt                                                              0.0s
 => exporting to image                                                                                             0.0s
 => => exporting layers                                                                                            0.0s
 => => writing image sha256:2ae60480f9f13902ba3d8bff872beff270ebcf5fe25e284159215c732cce7dcb                       0.0s
 => => naming to docker.io/(ID)/hangman                                                                           0.0s

What's Next?
  View a summary of image vulnerabilities and recommendations → docker scout quickview

 

Dockerfile을 이용해 이미지를 build합니다. 만일 M1칩으로 구성된 맥북 작성하시면 linux/arm이외의 플랫폼에서 문제가 발생합니다. 플랫폼은 linux/amd64로 작성하시고

 

-t로 이름은 DockerHub에 바로 업로드할 수 있도록 자신의 Docker Hub ID/hangman으로 주겠습니다.

 

 

 

 

 

 

 

 

PS D:\Dev_KDT\hangman_homework\hangman_web> docker images
REPOSITORY                                       TAG          IMAGE ID       CREATED             SIZE
(ID)/hangman                                    latest       2ae60480f9f1   About an hour ago   155MB

 

docker images로도 조회가 되고 docker inspect 명령으로 우리가 LABEL로 주었던 정보도 key:value 형태로 확인할 수 있습니다.

 

 

 

 

 

 

Docker Image 실행해보기

 

docker run -p 4000:4000 (ID)/hangman

PS D:\Dev_KDT\hangman_homework\hangman_web> docker run -p 4000:4000 (ID)/hangman
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:4000
 * Running on http://172.17.0.2:4000
Press CTRL+C to quit

 

-p 옵션으로 포트매핑하여 컨테이너 외부에서도 내부의 hangman 서비스 4000번 포트에 접근할 수 있도록 해야합니다.

 

 

 

 

 

 

정상적으로 접속됩니다.

 

 

 

docker stop (컨테이너 ID)

Container를 중단시키는 명령입니다. 컨테이너 ID는 ps나 ps -a로 조회가능합니다.

 

시간이 조금 걸리니 기다려야 합니다.

 

 

 

docker run -p 4000:4000 -d (ID)/hangman

PS C:\Users\User> docker run -p 4000:4000 -d (ID)/hangman
bb67a6c63799aad90f55f00c71126a4b8c67d5cd24fada70bb349dbd8973ddab
PS C:\Users\User>

-d 옵션을 주면 컨테이너가 끝날 때까지 기다리지 않고 백그라운드에서 돌게할 수 있습니다.

가장 체감되는 기능은 서버를 실행시키고 별다른 터미널 창을 열 필요가 사라진다는 것입니다.

 

 

 

 

 

 

 

 

 

 

 

만든 Docker Image를 Docker Hub에 Push하기

 

 

현재 저의 Docker Hub에는 어떤 repository도 존재하지 않습니다.

 

이 상태에서 push를 하면 repo를 자동으로 생성한다고 했었습니다.

 

 

 

docker push (ID)/hangman

PS C:\Users\User> docker push (ID)/hangman
Using default tag: latest
The push refers to repository [docker.io/(ID)/hangman]
32351efdfce0: Pushed
01bbc3e3032f: Pushed
90dc44714c60: Pushed
b13d16bfedb9: Pushed
e6c5004ee77f: Mounted from library/python
997b8e79e84f: Mounted from library/python
3054512b6f71: Mounted from library/python
ae2d55769c5e: Mounted from library/python
e2ef8a51359d: Mounted from library/python
latest: digest: sha256:e8cd25d6e2c15a1e23e987fc659e091c253830fe4eec8606fd03b99207cae3cf size: 2203

 

별도의 repo를 만들지 않고 push를 했음에도

 

 

 

 

 

 

 

자동으로 repo가 생성되어 있습니다.

 

굳이 repo를 미리 만들지 않고 터미널에서 push가 가능하다는 것을 확인했습니다.

 

 

 

 

 

 

 

 

 

Docker Hub에 생성한 repo를 다른 곳에서 다운 받아 실행시키기

 

 

https://labs.play-with-docker.com/ 에서 실습해보겠습니다.

 

docker run -p 4000:4000 (ID)/hangman 로 repo를 다운받아 서버를 구동시키니

 

 

 

-p 옵션을 캐치하고 labs가 4000번 포트 링크를 제공합니다. 클릭해보면

 

 

 

Hangman이 정상적으로 서비스 됩니다.