본문 바로가기
구글 스터디잼 쿠버네티스 입문

Introduction to Docker

by 치우치지않는 2022. 7. 14.

Overview

Docker is an open platform for developing, shipping, and running applications. With Docker, you can separate your applications from your infrastructure and treat your infrastructure like a managed application. Docker helps you ship code faster, test faster, deploy faster, and shorten the cycle between writing code and running code.

Docker does this by combining kernel containerization features with workflows and tooling that helps you manage and deploy your applications.

Docker containers can be directly used in Kubernetes, which allows them to be run in the Kubernetes Engine with ease. After learning the essentials of Docker, you will have the skillset to start developing Kubernetes and containerized applications.

 

도커를 이용하면, 커널 컨테이너화 기능을 애플리케이션 관리 및 배포에 도움이 되는 워크플로우 및 도구와 결합함으로써 애플리케이션을 인프라에서 분리하고 인프라를 관리되는 애플리케이션처럼 취급할 수 있습니다. (무슨 말인지 잘은 모르겠지만, 도커는 애플리케이션을 관리되게끔 하는 도구인가 보다!)

 

+커널 컨테이너화 기능

더보기

컨테이너라는 격리된 사용자 공간에서 애플리케이션을 실행하는 OS 가상화의 한 형태로, 동일한 공유 운영 체제를 사용합니다. 애플리케이션 컨테이너는 완전히 패키지화되고 이동이 가능한 컴퓨팅 환경입니다.

더 자세한 정보: https://www.veritas.com/ko/kr/information-center/containerization

What you'll learn

In this lab, you will learn how to do the following:

  • How to build, run, and debug Docker containers.
  • How to pull Docker images from Docker Hub and Google Container Registry.
  • How to push Docker images to Google Container Registry.

이 세 가지는 학습 목표이니 꼭 배워가자. 1. 도커 컨테이너를 어떻게 빌드하고 실행하고 디버그하는지, 2.  어떻게 도커 이미지들을 도커 허브와 구글 컨테이너 레지스트리로부터 Pull 하는지, 3. 어떻게 도커 이미지들을 구글 컨테이너 레지스트리에 Push 하는지

 

Hello World

Open up Cloud Shell and enter the following command to run a hello world container to get started:

docker run hello-world

(Command Output)

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
9db2ca6ccae0: Pull complete
Digest: sha256:4b8ff392a12ed9ea17784bd3c9a8b1fa3299cac44aca35a85c90c5e3c7afacdc
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
...

This simple container returns Hello from Docker! to your screen. While the command is simple, notice in the output the number of steps it performed. The docker daemon searched for the hello-world image, didn't find the image locally, pulled the image from a public registry called Docker Hub, created a container from that image, and ran the container for you.

 

hello-world 라는 이름의 이미지를 로컬에서 찾지 못했다! 그래서 대신 Docker Hub 라는 공용 레지스트리에서 이미지를 가져와서 해당 이미지에서 컨테이너를 생성하고 컨테이너를 실행했다.

 

Run the following command to take a look at the container image it pulled from Docker Hub:

docker images

(Command Output)

REPOSITORY     TAG      IMAGE ID       CREATED       SIZE
hello-world    latest   1815c82652c0   6 days ago    1.84 kB

This is the image pulled from the Docker Hub public registry. The Image ID is in SHA256 hash format—this field specifies the Docker image that's been provisioned. When the docker daemon can't find an image locally, it will by default search the public registry for the image. Now run the container again:

 

Docker Hub 에서 가져온 컨테이너 이미지. docker daemon 은 로컬에서 이미지를 찾을 수 없으면 기본적으로 공개 레지스트리에서 이미지를 검색한다!

docker run hello-world
컨테이너 재실행

 

(Command Output)

Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
...

Notice the second time you run this, the docker daemon finds the image in your local registry and runs the container from that image. It doesn't have to pull the image from Docker Hub.

Finally, look at the running containers by running the following command:

 

어랏 컨테이너 재실행에서 docker daemon 은 더 이상 DockerHub 에서 이미지를 가져오지 않고 로컬 레지스트리에서 이미지를 찾고 해당 이미지에서 컨테이너를 실행한다!

docker ps

실행 중인 컨테이너 확인

(Command Output)

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

There are no running containers. The hello-world containers you ran previously already exited. In order to see all containers, including ones that have finished executing, run docker ps -a:

 

음 hello-world 컨테이너는 이미 종료되었군! 

docker ps -a

실행이 완료된 컨테이너를 포함하여 모든 컨테이너 보기

(Command Output)

CONTAINER ID      IMAGE           COMMAND      ...     NAMES
6027ecba1c39      hello-world     "/hello"     ...     elated_knuth
358d709b8341      hello-world     "/hello"     ...     epic_lewin

This shows you the Container ID, a UUID generated by Docker to identify the container, and more metadata about the run. The container Names are also randomly generated but can be specified with docker run --name [container-name] hello-world.

 

Build

Next, build a Docker image that's based on a simple node application. Execute the following command to create and switch into a folder named test.

mkdir test && cd test

test 디렉토리 하나 만들고 이동!

Create a Dockerfile:

 

test 디렉토리에 도커 파일 만들기! (Dockerfile)

cat > Dockerfile <<EOF
# Use an official Node runtime as the parent image
FROM node:lts
# Set the working directory in the container to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Make the container's port 80 available to the outside world
EXPOSE 80
# Run app.js using node when the container launches
CMD ["node", "app.js"]
EOF

This file instructs the Docker daemon on how to build your image.

  • The initial line specifies the base parent image, which in this case is the official Docker image for node version long term support (lts).
  • In the second, you set the working (current) directory of the container.
  • In the third, you add the current directory's contents (indicated by the "." ) into the container.
  • Then expose the container's port so it can accept connections on that port and finally run the node command to start the application.

cat > Dockerfile << EOF 는 여러 줄을 파일로 생성할 때 쓰는 것. 첫번째 줄 = FROM node: lts. 

첫 번째 줄은 기본 상위 이미지를 지정. 이 경우 노드 버전 장기 지원(lts)을 위한 공식 Docker 이미지
두 번째에서는 컨테이너의 작업(현재) 디렉터리를 설정
세 번째에서는 현재 디렉토리의 내용("."로 표시)을 컨테이너에 추가
그런 다음 컨테이너의 포트를 노출하여 해당 포트에서 연결을 수락하고 마지막으로 node 명령을 실행하여 애플리케이션을 시작.

 

Spend some time reviewing the Dockerfile command references to understand each line of the Dockerfile.

Now you'll write the node application, and after that you'll build the image.

Run the following to create the node application:

cat > app.js <<EOF
const http = require('http');
const hostname = '0.0.0.0';
const port = 80;
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
});
server.listen(port, hostname, () => {
    console.log('Server running at http://%s:%s/', hostname, port);
});
process.on('SIGINT', function() {
    console.log('Caught interrupt signal and will exit');
    process.exit();
});
EOF

노드 애플리케이션 생성하기! (app.js)

This is a simple HTTP server that listens on port 80 and returns "Hello World".

 

포트 80에서 수신 대기하다가 Hello World 를 반환하는 간단한 HTTP 서버를 만들었다! 

 

Now build the image.

Note again the ".", which means current directory so you need to run this command from within the directory that has the Dockerfile:

docker build -t node-app:0.1 .

드디어 이미지 빌드! . 은 현재 디렉터리를 의미하니 Dockerfile 이 있는 디렉터리 내에서 명령을 실행해야 함!! 

It might take a couple of minutes for this command to finish executing. When it does, your output should resemble the following:

Sending build context to Docker daemon 3.072 kB
Step 1 : FROM node:lts
6: Pulling from library/node
...
...
...
Step 5 : CMD node app.js
 ---> Running in b677acd1edd9
 ---> f166cd2a9f10
Removing intermediate container b677acd1edd9
Successfully built f166cd2a9f10

The -t is to name and tag an image with the name:tag syntax. The name of the image is node-app and the tag is 0.1. The tag is highly recommended when building Docker images. If you don't specify a tag, the tag will default to latest and it becomes more difficult to distinguish newer images from older ones. Also notice how each line in the Dockerfile above results in intermediate container layers as the image is built.

Now, run the following command to look at the images you built:

 

-t 는 name:tag 구문으로, 이미지의 이름을 지정하고 태그를 지정하는 것! 따라서 이미지 태그 이름은 node-app 이고 태그는 0.1이다!

태그는 Docker 이미지를 빌드할 때 적극 권장됨. 태그를 지정하지 않으면 태그가 기본적으로 최신으로 지정되며 새 이미지와 이전 이미지를 구별하기가 더 어려워짐! 

 

docker images

빌드한 이미지 확인하기!

Your output should resemble the following:

REPOSITORY     TAG      IMAGE ID        CREATED            SIZE
node-app       0.1      f166cd2a9f10    25 seconds ago     656.2 MB
node           lts      5a767079e3df    15 hours ago       656.2 MB
hello-world    latest   1815c82652c0    6 days ago         1.84 kB

Notice node is the base image and node-app is the image you built. You can't remove node without removing node-app first. The size of the image is relatively small compared to VMs. Other versions of the node image such as node:slim and node:alpine can give you even smaller images for easier portability. The topic of slimming down container sizes is further explored in Advanced Topics. You can view all versions in the official repository here.

 

node는 기본 이미지이고 node-app은 빌드한 이미지! node-app을 먼저 제거하지 않고는 노드를 제거할 수 없다! 이미지의 크기는 VM(가상 머신)에 비해 상대적으로 작음!

Run

In this module, use this code to run containers based on the image you built:

 

docker run -p 4000:80 --name my-app node-app:0.1
빌드한 이미지 기반으로 컨테이너 실행하기! 

(Command Output)

Server running at http://0.0.0.0:80/

The --name flag allows you to name the container if you like. The -p instructs Docker to map the host's port 4000 to the container's port 80. Now you can reach the server at http://localhost:4000. Without port mapping, you would not be able to reach the container at localhost.

 

--name 플래그를 이용해서 컨테이너의 이름을 지정할 수 있음. -P 는 dockere 에 호스트의 포트 4000을 컨테이너의 포트 80에 매핑하도록 지시! 이제 http://localhost:4000 에서 서버에 연결 가능. 

 

Open another terminal (in Cloud Shell, click the + icon), and test the server:

curl http://localhost:4000
 
서버 테스트

(Command Output)

Hello World

The container will run as long as the initial terminal is running. If you want the container to run in the background (not tied to the terminal's session), you need to specify the -d flag.

Close the initial terminal and then run the following command to stop and remove the container:

 

컨테이너는 초기 터미널이 실행되는 동안 실행된다. 컨테이너를 백그라운드에서 실행하려면(터미널 세션에 연결되지 않음) -d 플래그를 지정해야 한다. 따라서 초기 터미널을 닫고 다음 명령을 실행하여 컨테이너를 중지하고 제거해야 한다. (무슨 말인지 잘 모르겠으나 그 전 터미널을 닫고 새로운 터미널에서 실행해야 하는 듯)

 

docker stop my-app && docker rm my-app

컨테이너 중지 및 제거

Now run the following command to start the container in the background:

docker run -p 4000:80 --name my-app -d node-app:0.1
docker ps

백그라운드에서 컨테이너 실행

(Command Output)

CONTAINER ID   IMAGE          COMMAND        CREATED         ...  NAMES
xxxxxxxxxxxx   node-app:0.1   "node app.js"  16 seconds ago  ...  my-app

Notice the container is running in the output of docker ps. You can look at the logs by executing docker logs [container_id].

Tip: You don't have to write the entire container ID, as long as the initial characters uniquely identify the container. For example, you can execute docker logs 17b if the container ID is 17bcaca6f....

docker logs [container_id]

컨테이너 id 로그

(Command Output)

Server running at http://0.0.0.0:80/

Next, modify the application. In your Cloud Shell, open the test directory you created earlier in the lab:

cd test

이전에 만들었던 test 디렉토리로 이동!

Edit app.js with a text editor of your choice (for example nano or vim) and replace "Hello World" with another string:

....
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Welcome to Cloud\n');
});
....

Hello world 말고 다른 것으로 시도!

Build this new image and tag it with 0.2:

docker build -t node-app:0.2 .

태그는 2로 해서 빌드!

(Command Output)

Step 1/5 : FROM node:lts
 ---> 67ed1f028e71
Step 2/5 : WORKDIR /app
 ---> Using cache
 ---> a39c2d73c807
Step 3/5 : ADD . /app
 ---> a7087887091f
Removing intermediate container 99bc0526ebb0
Step 4/5 : EXPOSE 80
 ---> Running in 7882a1e84596
 ---> 80f5220880d9
Removing intermediate container 7882a1e84596
Step 5/5 : CMD node app.js
 ---> Running in f2646b475210
 ---> 5c3edbac6421
Removing intermediate container f2646b475210
Successfully built 5c3edbac6421
Successfully tagged node-app:0.2

Notice in Step 2 that you are using an existing cache layer. From Step 3 and on, the layers are modified because you made a change in app.js.

Run another container with the new image version. Notice how the host's port is mapped to 8080 instead of 80. You can't use host port 4000 because it's already in use.

 

2단계에서 기존 캐시 계층을 사용하고 있음을 알 수 있음. 3단계부터 app.js를 변경했기 때문에 레이어가 수정됨.

새 이미지 버전으로 다른 컨테이너를 실행. 호스트의 포트가 80이 아닌 8080에 어떻게 매핑되는지 확인하기! 호스트 포트 4000은 이미 사용 중이기 때문에 사용할 수 없음.

docker run -p 8080:80 --name my-app-2 -d node-app:0.2
docker ps

(Command Output)

CONTAINER ID     IMAGE             COMMAND            CREATED             
xxxxxxxxxxxx     node-app:0.2      "node app.js"      53 seconds ago      ...
xxxxxxxxxxxx     node-app:0.1      "node app.js"      About an hour ago   ...

Test the containers:

컨테이너 테스트!

curl http://localhost:8080

(Command Output)

Welcome to Cloud

And now test the first container you made:

curl http://localhost:4000

첫번째 컨테이너 테스트!

(Command Output)

Hello World

Debug

Now that you're familiar with building and running containers, go over some debugging practices.

You can look at the logs of a container using docker logs [container_id]. If you want to follow the log's output as the container is running, use the -f option.

docker logs -f [container_id]

컨테이너가 실행 중일 때 로그의 출력 보려면 -f 옵션 사용!

(Command Output)

Server running at http://0.0.0.0:80/

Sometimes you will want to start an interactive Bash session inside the running container. You can use docker exec to do this. Open another terminal (in Cloud Shell, click the + icon) and enter the following command:

 

실행중인 컨테이너 내에서 대화형 Bash 세션을 시작하고 싶을 때는 docker exec 를 사용!

docker exec -it [container_id] bash

The -it flags let you interact with a container by allocating a pseudo-tty and keeping stdin open. Notice bash ran in the WORKDIR directory (/app) specified in the Dockerfile. From here, you have an interactive shell session inside the container to debug.

(Command Output)

 

bash는 Dockerfile에 지정된 WORKDIR 디렉터리(/app)에서 실행되었음. 여기에 컨테이너 내부에 디버그할 대화형 셸 세션이 있음.

root@xxxxxxxxxxxx:/app#

Look at the directory

ls

(Command Output)

Dockerfile  app.js

Exit the Bash session:

exit

You can examine a container's metadata in Docker by using Docker inspect:

docker inspect [container_id]

docker inspect 를 사용하면 컨테이너 내의 메타데이터를 검사할 수 있음.

(Command Output)

[
    {
        "Id": "xxxxxxxxxxxx....",
        "Created": "2017-08-07T22:57:49.261726726Z",
        "Path": "node",
        "Args": [
            "app.js"
        ],
...

Use --format to inspect specific fields from the returned JSON. For example:

docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' [container_id]

--format을 사용하여 반환된 JSON에서 특정 필드를 검사할 수 있음.

(Example Output)

192.168.9.3

Be sure to check out the following resources for more information on debugging:

Publish

Now you're going to push your image to the Google Container Registry (gcr). After that you'll remove all containers and images to simulate a fresh environment, and then pull and run your containers. This will demonstrate the portability of Docker containers.

To push images to your private registry hosted by gcr, you need to tag the images with a registry name. The format is [hostname]/[project-id]/[image]:[tag].

 

이제 이미지를 Google Container Registry(gcr)에 푸시하자! 그런 다음 모든 컨테이너와 이미지를 제거하여 새로운 환경을 시뮬레이션한 다음 컨테이너를 가져와 실행! (Docker 컨테이너의 이식성)

gcr에서 호스팅하는 비공개 레지스트리에 이미지를 푸시하려면 이미지에 레지스트리 이름을 태그해야 합니다. 형식은 [호스트 이름]/[프로젝트 ID]/[이미지]:[태그]!

 

For gcr:

  • [hostname]= gcr.io
  • [project-id]= your project's ID
  • [image]= your image name
  • [tag]= any string tag of your choice. If unspecified, it defaults to "latest".

You can find your project ID by running:

gcloud config list project

Project id 찾기

(Command Output)

[core]
project = [project-id]
Your active configuration is: [default]

Tag node-app:0.2. Replace [project-id] with your configuration..

docker tag node-app:0.2 gcr.io/[project-id]/node-app:0.2
 
docker images
 

(Command Output)

REPOSITORY                      TAG         IMAGE ID          CREATED
node-app                        0.2         76b3beef845e      22 hours ago
gcr.io/[project-id]/node-app    0.2         76b3beef845e      22 hours ago
node-app                        0.1         f166cd2a9f10      26 hours ago
node                            lts         5a767079e3df      7 days ago
hello-world                     latest      1815c82652c0      7 weeks ago

Push this image to gcr. Remember to replace [project-id].

이 이미지를 gcr 에 push 하자!

docker push gcr.io/[project-id]/node-app:0.2

Command output (yours may differ):

The push refers to a repository [gcr.io/[project-id]/node-app]
057029400a4a: Pushed
342f14cb7e2b: Pushed
903087566d45: Pushed
99dac0782a63: Pushed
e6695624484e: Pushed
da59b99bbd3b: Pushed
5616a6292c16: Pushed
f3ed6cb59ab0: Pushed
654f45ecb7e3: Pushed
2c40c66f7667: Pushed
0.2: digest: sha256:25b8ebd7820515609517ec38dbca9086e1abef3750c0d2aff7f341407c743c46 size: 2419

Check that the image exists in gcr by visiting the image registry in your web browser. You can navigate via the console to Navigation menu > Container Registry and click node-app or visit: http://gcr.io/[project-id]/node-app. You should land on a similar page:

Test this image. You could start a new VM, ssh into that VM, and install gcloud. For simplicity, just remove all containers and images to simulate a fresh environment.

Stop and remove all containers:

docker stop $(docker ps -q)
docker rm $(docker ps -aq)

모든 컨테이너 중지 및 제거

You have to remove the child images (of node:lts) before you remove the node image. Replace [project-id].

docker rmi node-app:0.2 gcr.io/[project-id]/node-app node-app:0.1
docker rmi node:lts
docker rmi $(docker images -aq) # remove remaining images
docker images

 
노드 이미지 제거 전 자식 이미지 제거해야 함! 프로젝트 아이디 자식의 것으로 바꿔주기!

(Command Output)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

At this point you should have a pseudo-fresh environment. Pull the image and run it. Remember to replace the [project-id].

docker pull gcr.io/[project-id]/node-app:0.2
docker run -p 4000:80 -d gcr.io/[project-id]/node-app:0.2
curl http://localhost:4000

이미지 pull 해주고 실행하기!

(Command Output)

Welcome to Cloud

 

댓글