Docker 기초개념

2020-07-12

.

Data_Engineering_TIL(20200711)

  • Study Program : Docker 기반의 DevOps 인프라 구축 WORKSHOP

  • 관련 URL : https://www.fastcampus.co.kr/dev_workshop_devops

[학습노트]

1. 도커는 무엇인가

리눅스 컨테이너 기술을 이용하여 어플리케이션 패키징,배포를 지원하는 경량의 가상 플랫폼

** 라이센스로 CE(Apache License 2.0), 엔터프라이즈(상용) 두가지가 있지만 일반회사에서 프로덕션 환경에서의 적용에 있어서는 CE로도 충분하다. 다만 금융회사 같이 라이센스로부터 얻을 수 있는 게런티 같은 것을 원하면 엔트프라이즈용을 사용하는 것도 좋다.

2. 그러면 왜 도커를 사용해야 할까?

1

immutable infrastructure

  • 관리가능하고

  • stateless하고

  • Scalable한

  • 이미지기반의

  • 어플리케이션 배포

–> 도커는 변경불가능한 인프라(immutable infrastructure)를 가능하게 한다

3. 도커는 왜 성공했을까

“도커는 사용하기 쉽다”

4. Docker 구성요소

1) Docker Client : 도커 엔진과 통신하는 프로그램

2) Docker Host OS : 도커 엔진을 설치할 수 있는 환경, 64비트 리눅스 커널버전 3.10이상 환경

3) Docker Engine : 어플리케이션을 컨테이너로 만들고 실행하게 해주는 데몬

4) Docker Machine : 로컬, 리모트서버에서 도커엔진을 실행하고, 설정을 자동으로 해주는 프로비저닝 클라이언트

5) Docker Hub : 도커 이미지를 관리하는 저장소

6) Docker Trusted Registry : 도커 이미지 저장소 구축가능

7) Docker Cloud : 도커 이미지, 컨테이너를 관리할 수 있도록 지원하는 툴

5. 실습 : Docker 설치

DockerCE for linux(centos 기준)

$ sudo yum update -y
$ curl -fsSL https://get.docker.com/ | sh
$ sudo yum install docker-engine
$ sudo systemctl enable docker.service
$ sudo systemctl start docker

우분투 기준

Docker Desktop for Ubuntu를 이용해 도커 환경을 구성한다. Docker Desktop 을 설치하기 위해서는 64비트 아래 버전이어야 한다.

  • Yakkety 16.10

  • Xenial 16.04

  • Trusty 14.04

먼저 Docker CE 를 가져오기 위한 레파지터리 정보를 설정한다.

sudo apt-get update -y
sudo apt-get -y install apt-transport-https ca-certificates curl
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

그 다음에 Docker Desktop을 설치한다.

sudo apt-get -y install docker-ce

설치가 완료되면 docker version과 docker info 명령어를 실행했을때 도커 정보들이 아래와 같이 전시가 되어야 한다.

root@ip-10-1-10-144:/home/ubuntu# docker version
Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a66213fe
 Built:             Mon Jun 22 15:45:36 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a66213fe
  Built:            Mon Jun 22 15:44:07 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
root@ip-10-1-10-144:/home/ubuntu# docker info
Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 19.03.12
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
 Swarm: inactive
 Runtimes: runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.3.0-1023-aws
 Operating System: Ubuntu 18.04.4 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 2
 Total Memory: 953.6MiB
 Name: ip-10-1-10-144
 ID: IZBV:DYLP:GQIQ:Z4IH:6L3Q:RCWD:EU4I:FKQZ:KPIC:TI7R:2BV4:TVCH
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No swap limit support

위와 같이 화면에 전시가 되면 도커 설치가 정상적으로 완료된 것이다.

6. Docker 아키텍처

2

3

7. Docker 이미지

  • 컨테이너를 만들기 위한 템플릿

–> 붕어빵(컨테이너)과 붕어빵틀(이미지)이라고 생각하면 된다.

  • 읽기전용 파일시스템으로 도커로 서비스를 배포하는 최소단위.

  • 동일한 이미지로 다른 유형의 컨테이너를 만들수 있을까?

–> 틀이 정해져있기 때문에 불가능하다.

4

5

  • 도커 이미지 크기를 줄이는 방법

1) 가벼운 베이스 이미지를 사용한다.

2) Dockerfile 명령을 체인으로 사용한다.

3) 빌드도구를 설치하지 않는다.

4) 패키지 관리자를 정리한다.

8. 실습 : Docker 이미지를 활용하는 실습

  • 먼저 docker search whalesay 명령어를 이용해서 도커 허브에서 whalesay 이미지를 찾는것과 같이 콘솔에서 whalesay라는 이미지를 찾아본다.
root@ip-10-1-10-144:/home/ubuntu# docker search whalesay
NAME                           DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
docker/whalesay                An image for use in the Docker demo tutorial    678
caibar/whalesay                Builds automatizados.                           1                                       [OK]
nikovirtala/whalesay           Tiny Go web service to print Moby Dock ASCII   1                                       [OK]
milanfort/whalesay             Modified docker/whalesay image that outputs    1
ojenge/whalesay                from docker/whalesay                            1
swinton/whalesay               whalesay, innit                                 1
sabs1117/whalesay              Whalesay with fortune phrases.                  1
forsingh/whalesay              whalesay                                        0                                       [OK]
firecyberice/whalesay          Docker **Cloud** automated build for **amd64   0
dhalljohnston/whalesay         whalesay                                        0
yang225217/whalesay                                                            0
maghnus/whalesayentrypoint     I need a version of whalesay with entrypoint   0
whalebrew/whalesay                                                             0
getporter/whalesay-installer                                                   0
nikovirtala/whalesay-win       Whalesay running on Microsoft IIS on Nano Se   0                                       [OK]
blaines/whalesay                                                               0
burleyinnersbm07/whalesay      Edit to the WhaleSay                            0
hongxi/whalesay-fortunes       Demo, the whalesay-fortunes                     0
dockeramiller/whalesay         Modified version of the official docker/whal   0                                       [OK]
gapfish/whalesay-ruby          whalesay function test                          0
tpei/whalesay-crystal          crystal faas demo function                      0
ox0spy/whalesay-fortune        like docker/whalesay, just using fortunes pr   0
phyominhtun/whalesay           WhaleSay Container                              0
getporter/whalesay                                                             0
jenniferw/whalesay-tutorial    tutorial for whalesay 2.0                       0
  • 그 다음에 docker pull docker/whalesay 명령어를 실행하여 docker/whalesay라는 이름의 이미지를 pull해보자.
root@ip-10-1-10-144:/home/ubuntu# docker pull docker/whalesay
Using default tag: latest
latest: Pulling from docker/whalesay
Image docker.io/docker/whalesay:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/
e190868d63f8: Pull complete
909cd34c6fd7: Pull complete
0b9bfabab7c1: Pull complete
a3ed95caeb02: Pull complete
00bf65475aba: Pull complete
c57b6bcc83e3: Pull complete
8978f6879e2f: Pull complete
8eed3712d2cf: Pull complete
Digest: sha256:178598e51a26abbc958b8a2e48825c90bc22e641de3d31e18aaf55f3258ba93b
Status: Downloaded newer image for docker/whalesay:latest
docker.io/docker/whalesay:latest
  • docker images 명령어를 실행하면 아래와 같이 방금 pull해온 docker/whalesay 이미지를 확인할 수 있다.
root@ip-10-1-10-144:/home/ubuntu# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
docker/whalesay     latest              6b362a9f73eb        5 years ago         247MB
  • 다운받은 이미지를 docker run docker/whalesay cowsay boo 명령어로 실행해본다.
root@ip-10-1-10-144:/home/ubuntu# docker run docker/whalesay cowsay boo
 _____
< boo >
 -----
    \
     \
      \
                    ##        .
              ## ## ##       ==
           ## ## ## ##      ===
       /""""""""""""""""___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~
       \______ o          __/
        \    \        __/
          \____\______/
  • 해당 이미지는 실행하고 끝나면 종료되는 프로세스이기 때문에 docker ps -a 명령어를 실행하면 해당 컨테이너 내역을 확인할 수 있다.
root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
root@ip-10-1-10-144:/home/ubuntu# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
8179a9cb9d38        docker/whalesay     "cowsay boo"        47 seconds ago      Exited (0) 46 seconds ago                       silly_bhaskara
  • 그러면 docker/whalesay 이미지를 이용해서 docker-whalesay라는 나만의 이미지를 만들어보자.

step 1) sudo vim Dockerfile 명령어로 아래와 같은 내용을 작성하여 Dockerfile을 생성해준다.

FROM docker/whalesay:latest
RUN apt-get -y update && apt-get install -y fortune
CMD /usr/games/fortune -a | cowsay

step 2) docker build -t docker-whale . 명령어를 실행하여 docker-whalesay 이미지를 빌드한다.

root@ip-10-1-10-144:/home/ubuntu# docker build -t docker-whale .
Sending build context to Docker daemon  14.34kB
Step 1/3 : FROM docker/whalesay:latest
 ---> 6b362a9f73eb
Step 2/3 : RUN apt-get -y update && apt-get install -y fortune
 ---> Running in 5bd192f326d9
Ign http://archive.ubuntu.com trusty InRelease
Get:1 http://archive.ubuntu.com trusty-updates InRelease [65.9 kB]
Get:2 http://archive.ubuntu.com trusty-security InRelease [65.9 kB]
Hit http://archive.ubuntu.com trusty Release.gpg
Hit http://archive.ubuntu.com trusty Release
Get:3 http://archive.ubuntu.com trusty-updates/main Sources [532 kB]
Get:4 http://archive.ubuntu.com trusty-updates/restricted Sources [6444 B]
Get:5 http://archive.ubuntu.com trusty-updates/universe Sources [288 kB]
Get:6 http://archive.ubuntu.com trusty-updates/main amd64 Packages [1460 kB]
Get:7 http://archive.ubuntu.com trusty-updates/restricted amd64 Packages [21.4 kB]
Get:8 http://archive.ubuntu.com trusty-updates/universe amd64 Packages [671 kB]
Get:9 http://archive.ubuntu.com trusty-security/main Sources [220 kB]
Get:10 http://archive.ubuntu.com trusty-security/restricted Sources [5050 B]
Get:11 http://archive.ubuntu.com trusty-security/universe Sources [127 kB]
Get:12 http://archive.ubuntu.com trusty-security/main amd64 Packages [1032 kB]
Get:13 http://archive.ubuntu.com trusty-security/restricted amd64 Packages [18.1 kB]
Get:14 http://archive.ubuntu.com trusty-security/universe amd64 Packages [378 kB]
Hit http://archive.ubuntu.com trusty/main Sources
Hit http://archive.ubuntu.com trusty/restricted Sources
Hit http://archive.ubuntu.com trusty/universe Sources
Hit http://archive.ubuntu.com trusty/main amd64 Packages
Hit http://archive.ubuntu.com trusty/restricted amd64 Packages
Hit http://archive.ubuntu.com trusty/universe amd64 Packages
Fetched 4890 kB in 12s (379 kB/s)
Reading package lists...
Reading package lists...
Building dependency tree...
Reading state information...
The following extra packages will be installed:
  fortunes-min librecode0
Suggested packages:
  fortunes x11-utils bsdmainutils
The following NEW packages will be installed:
  fortune-mod fortunes-min librecode0
0 upgraded, 3 newly installed, 0 to remove and 124 not upgraded.
Need to get 872 kB of archives.
After this operation, 2206 kB of additional disk space will be used.
Get:1 http://archive.ubuntu.com/ubuntu/ trusty/main librecode0 amd64 3.6-21 [771 kB]
Get:2 http://archive.ubuntu.com/ubuntu/ trusty/universe fortune-mod amd64 1:1.99.1-7 [39.5 kB]
Get:3 http://archive.ubuntu.com/ubuntu/ trusty/universe fortunes-min all 1:1.99.1-7 [61.8 kB]
debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
debconf: unable to initialize frontend: Readline
debconf: (This frontend requires a controlling tty.)
debconf: falling back to frontend: Teletype
dpkg-preconfigure: unable to re-open stdin:
Fetched 872 kB in 2s (374 kB/s)
Selecting previously unselected package librecode0:amd64.
(Reading database ... 13116 files and directories currently installed.)
Preparing to unpack .../librecode0_3.6-21_amd64.deb ...
Unpacking librecode0:amd64 (3.6-21) ...
Selecting previously unselected package fortune-mod.
Preparing to unpack .../fortune-mod_1%3a1.99.1-7_amd64.deb ...
Unpacking fortune-mod (1:1.99.1-7) ...
Selecting previously unselected package fortunes-min.
Preparing to unpack .../fortunes-min_1%3a1.99.1-7_all.deb ...
Unpacking fortunes-min (1:1.99.1-7) ...
Setting up librecode0:amd64 (3.6-21) ...
Setting up fortune-mod (1:1.99.1-7) ...
Setting up fortunes-min (1:1.99.1-7) ...
Processing triggers for libc-bin (2.19-0ubuntu6.6) ...
Removing intermediate container 5bd192f326d9
 ---> 23dab04f9663
Step 3/3 : CMD /usr/games/fortune -a | cowsay
 ---> Running in 2327b9c876d9
Removing intermediate container 2327b9c876d9
 ---> 0b7f7abd1963
Successfully built 0b7f7abd1963
Successfully tagged docker-whale:latest

step 3) docker run docker-whale 명령어로 docker-whale 이미지를 실행해본다. 매번 실행할때마다 다른 결과가 나올 것이다.

root@ip-10-1-10-144:/home/ubuntu# docker run docker-whale
 _______________________________________
/ You will visit the Dung Pits of Glive \
\ soon.                                 /
 ---------------------------------------
    \
     \
      \
                    ##        .
              ## ## ##       ==
           ## ## ## ##      ===
       /""""""""""""""""___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~
       \______ o          __/
        \    \        __/
          \____\______/
root@ip-10-1-10-144:/home/ubuntu# docker run docker-whale
 _____________________________________
/ Things will be bright in P.M. A cop \
\ will shine a light in your face.    /
 -------------------------------------
    \
     \
      \
                    ##        .
              ## ## ##       ==
           ## ## ## ##      ===
       /""""""""""""""""___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~
       \______ o          __/
        \    \        __/
          \____\______/
root@ip-10-1-10-144:/home/ubuntu# docker run docker-whale
 _______________________________________
/ October 12, the Discovery.            \
|                                       |
| It was wonderful to find America, but |
| it would have been more wonderful to  |
| miss it.                              |
|                                       |
| -- Mark Twain, "Pudd'nhead Wilson's   |
\ Calendar"                             /
 ---------------------------------------
    \
     \
      \
                    ##        .
              ## ## ##       ==
           ## ## ## ##      ===
       /""""""""""""""""___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~ ~ /  ===- ~~~
       \______ o          __/
        \    \        __/
          \____\______/
  • docker history docker-whale:latest 명령어를 실행하여 해당이미지의 레이어를 확인해보자.
root@ip-10-1-10-144:/home/ubuntu# docker history docker-whale:latest
IMAGE               CREATED             CREATED BY                                      SIZE                COMMENT
0b7f7abd1963        5 minutes ago       /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/usr…   0B
23dab04f9663        5 minutes ago       /bin/sh -c apt-get -y update && apt-get inst   28.1MB
6b362a9f73eb        5 years ago         /bin/sh -c #(nop) ENV PATH=/usr/local/bin:/u…   0B
<missing>           5 years ago         /bin/sh -c sh install.sh                        30.4kB
<missing>           5 years ago         /bin/sh -c git reset --hard origin/master       43.3kB
<missing>           5 years ago         /bin/sh -c #(nop) WORKDIR /cowsay               0B
<missing>           5 years ago         /bin/sh -c git clone https://github.com/moxi   89.9kB
<missing>           5 years ago         /bin/sh -c apt-get -y update && apt-get inst   58.6MB
<missing>           5 years ago         /bin/sh -c #(nop) CMD ["/bin/bash"]             0B
<missing>           5 years ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$…   1.9kB
<missing>           5 years ago         /bin/sh -c echo '#!/bin/sh' > /usr/sbin/poli…   195kB
<missing>           5 years ago         /bin/sh -c #(nop) ADD file:f4d7b4b3402b5c53f…   188MB
  • 그러면 docker-whale 이미지를 아래와 같이 삭제해보자.
root@ip-10-1-10-144:/home/ubuntu# docker rmi docker-whale:latest
Error response from daemon: conflict: unable to remove repository reference "docker-whale:latest" (must force) - container d57626183844 is using its referenced image 0b7f7abd1963

## 위와 같이 애러가 나는 이유는 현재 docker-whale 이미지가 어떤 컨테이너에서 참조하고 있기 때문이다.        
        
root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
root@ip-10-1-10-144:/home/ubuntu# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
4c75283c403b        docker-whale        "/bin/sh -c '/usr/ga…"   8 minutes ago       Exited (0) 8 minutes ago                        lucid_banach
7308e9f339d8        docker-whale        "/bin/sh -c '/usr/ga…"   8 minutes ago       Exited (0) 8 minutes ago                        eloquent_varahamihira
d57626183844        docker-whale        "/bin/sh -c '/usr/ga…"   8 minutes ago       Exited (0) 8 minutes ago                        elegant_elgamal
66543e7b704c        hello-world         "/hello"                 15 minutes ago      Exited (0) 15 minutes ago                       priceless_mendeleev
8179a9cb9d38        docker/whalesay     "cowsay boo"             19 minutes ago      Exited (0) 19 minutes ago                       silly_bhaskara

## 그래서 위와 같이 컨테이너를 검색했을때 3개 정도의 컨테이너가 docker-whale 이미지를 물고 있는데 이 세개의 컨테이너를 먼저 삭제해줘야한다.
## 그래서 아래와 같이 docker rm 4c75283c403b 7308e9f339d8 d57626183844 으로 해당 세개의 컨테이너를 삭제해준다.

root@ip-10-1-10-144:/home/ubuntu# docker rm 4c75283c403b 7308e9f339d8 d57626183844
4c75283c403b
7308e9f339d8
d57626183844

## 그런 다음에 다시 rmi를 시도하면 이미지가 삭제되는것을 확인할 수 있다.

root@ip-10-1-10-144:/home/ubuntu# docker rmi docker-whale:latest
Untagged: docker-whale:latest
Deleted: sha256:0b7f7abd1963fa7e9a12616c4c71a72817b0ae27f6df026e920dd8b3e2e0b631
Deleted: sha256:23dab04f966318249a279a8b4db953a7d6411342fdb4016cccdbf0c03c27c5b3
Deleted: sha256:b5bd308fb99184c104cde1014525a71195fc27568e007237e74461200e44935d
        
        
## 나는 위와 같은 과정이 귀찮다 싶으면 -f 옵션을 이용하여 docker rmi -f docker-whale:latest 명령어를 실행해줘도 된다.

## 또는 여러개의 컨테이너 또는 이미지를 삭제하는 방법은 아래와 같다.
## -q와 -a 옵션
## -q : 컨테이너 ID만 출력
## -a : 컨테이너 전체 출력
## $()를 이용한 파이프라이닝 명령어로 여러개를 동시에 삭제 할 수 있다.


root@ip-10-1-10-144:/home/ubuntu# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
66543e7b704c        hello-world         "/hello"            31 minutes ago      Exited (0) 31 minutes ago                       priceless_mendeleev
8179a9cb9d38        docker/whalesay     "cowsay boo"        35 minutes ago      Exited (0) 35 minutes ago                       silly_bhaskara

root@ip-10-1-10-144:/home/ubuntu# docker rm $(docker ps -aq)
66543e7b704c
8179a9cb9d38

root@ip-10-1-10-144:/home/ubuntu# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
hello-world         latest              bf756fb1ae65        6 months ago        13.3kB
docker/whalesay     latest              6b362a9f73eb        5 years ago         247MB

root@ip-10-1-10-144:/home/ubuntu# docker rmi $(docker images -aq)
Untagged: hello-world:latest
Untagged: hello-world@sha256:d58e752213a51785838f9eed2b7a498ffa1cb3aa7f946dda11af39286c3db9a9
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b
Deleted: sha256:9c27e219663c25e0f28493790cc0b88bc973ba3b1686355f221c38a36978ac63
Untagged: docker/whalesay:latest
Untagged: docker/whalesay@sha256:178598e51a26abbc958b8a2e48825c90bc22e641de3d31e18aaf55f3258ba93b
Deleted: sha256:6b362a9f73eb8c33b48c95f4fcce1b6637fc25646728cf7fb0679b2da273c3f4
Deleted: sha256:34dd66b3cb4467517d0c5c7dbe320b84539fbb58bc21702d2f749a5c932b3a38
Deleted: sha256:52f57e48814ed1bb08a651ef7f91f191db3680212a96b7f318bff0904fed2e65
Deleted: sha256:72915b616c0db6345e52a2c536de38e29208d945889eecef01d0fef0ed207ce8
Deleted: sha256:4ee0c1e90444c9b56880381aff6455f149c92c9a29c3774919632ded4f728d6b
Deleted: sha256:86ac1c0970bf5ea1bf482edb0ba83dbc88fefb1ac431d3020f134691d749d9a6
Deleted: sha256:5c4ac45a28f91f851b66af332a452cba25bd74a811f7e3884ed8723570ad6bc8
Deleted: sha256:088f9eb16f16713e449903f7edb4016084de8234d73a45b1882cf29b1f753a5a
Deleted: sha256:799115b9fdd1511e8af8a8a3c8b450d81aa842bbf3c9f88e9126d264b232c598
Deleted: sha256:3549adbf614379d5c33ef0c5c6486a0d3f577ba3341f573be91b4ba1d8c60ce4
Deleted: sha256:1154ba695078d29ea6c4e1adb55c463959cd77509adf09710e2315827d66271a

9. 실습 : DB 컨테이너 실행하기

  • docker run -d mysql 명령어로 -d(뒤에 백그라운드 데몬으로 돌게하라는 옵션)를 주고 mysql을 실행해본다.
root@ip-10-1-10-144:/home/ubuntu# docker run -d mysql
Unable to find image 'mysql:latest' locally
latest: Pulling from library/mysql
8559a31e96f4: Pull complete
d51ce1c2e575: Pull complete
c2344adc4858: Pull complete
fcf3ceff18fc: Pull complete
16da0c38dc5b: Pull complete
b905d1797e97: Pull complete
4b50d1c6b05c: Pull complete
c75914a65ca2: Pull complete
1ae8042bdd09: Pull complete
453ac13c00a3: Pull complete
9e680cd72f08: Pull complete
a6b5dc864b6c: Pull complete
Digest: sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6
Status: Downloaded newer image for mysql:latest
a4d39314fd94ecb95746b6601098a51d3123537e83e0898d6ce84242b55d6bb1
  • 그런데 어찌된 일인지 docker ps를 때려보니까 돌고 있는 컨테이너가 없다. 그래서 docker ps -a를 때려보니까 mysql이 확인이 되었다. 그러면 이게 process가 종료된 것인데 왜 이런 문제가 발생한것인지 의문이다.
root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

root@ip-10-1-10-144:/home/ubuntu# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
a4d39314fd94        mysql               "docker-entrypoint.s…"   12 seconds ago      Exited (1) 11 seconds ago                       trusting_haslett
  • 그래서 docker logs 컨테이너이름 을 아래와 같이 때려서 로그를 확인해보니 패스워드를 안줬기 때문에 애러가 발생해서 프로세스가 강제 종료된 것이었다.
root@ip-10-1-10-144:/home/ubuntu# docker logs trusting_haslett
2020-07-12 08:23:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.20-1debian10 started.
2020-07-12 08:23:47+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
2020-07-12 08:23:47+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.20-1debian10 started.
2020-07-12 08:23:47+00:00 [ERROR] [Entrypoint]: Database is uninitialized and password option is not specified
        You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD
  • docker run -d -e MYSQL_ROOT_PASSWORD='password123' --name dbcontainer mysql 명령어로 다시 실행하니까 정상적으로 mysql이 데몬으로 돌고 있는 것을 확인할 수 있다.

-d 옵션 : 컨테이너를 데몬으로 실행해라, -e 옵션 : 환경변수 설정

root@ip-10-1-10-144:/home/ubuntu# docker run -d -e MYSQL_ROOT_PASSWORD='password123' --name dbcontainer mysql
afedf8596baab4cdf0f50752cc19a9708122e21639ed9595344046885d2686a7

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
afedf8596baa        mysql               "docker-entrypoint.s…"   9 seconds ago       Up 9 seconds        3306/tcp, 33060/tcp   dbcontainer
  • mysql 컨테이너와 이미지를 아래와 같이 삭제해보자.
## step 1) 먼저 데몬으로 돌고 있는 mysql을 stop하고 컨테이너를 삭제해준다.

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
afedf8596baa        mysql               "docker-entrypoint.s…"   9 seconds ago       Up 9 seconds        3306/tcp, 33060/tcp   dbcontainer

root@ip-10-1-10-144:/home/ubuntu# docker stop afedf8596baa
afedf8596baa

root@ip-10-1-10-144:/home/ubuntu# docker rm afedf8596baa
afedf8596baa

## step 2) docker ps -a 로 전체 컨테이너를 출력해서 혹시 mysql 컨테이너가 있으면 그것도 삭제해준다.

root@ip-10-1-10-144:/home/ubuntu# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
a4d39314fd94        mysql               "docker-entrypoint.s…"   11 minutes ago      Exited (1) 11 minutes ago                       trusting_haslett

root@ip-10-1-10-144:/home/ubuntu# docker rm a4d39314fd94
a4d39314fd94


## step 3) mysql 이미지를 삭제해준다.

root@ip-10-1-10-144:/home/ubuntu# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               latest              be0dbf01a0f3        4 weeks ago         541MB

root@ip-10-1-10-144:/home/ubuntu# docker rmi mysql
Untagged: mysql:latest
Untagged: mysql@sha256:8b7b328a7ff6de46ef96bcf83af048cb00a1c86282bfca0cb119c84568b4caf6
Deleted: sha256:be0dbf01a0f3f46fc8c88b67696e74e7005c3e16d9071032fa0cd89773771576
Deleted: sha256:086d66e8d1cb0d52e9337eabb11fb9b95960e2e1628d90100c62ea5e8bf72306
Deleted: sha256:f37c61ee1973b18c285d0d5fcf02da4bcdb1f3920981499d2a20b2858500a110
Deleted: sha256:e40b8bca7dc63fc8d188a412328e56caf179022f5e5d5b323aae57d233fb1069
Deleted: sha256:339f6b96b27eb035cbedc510adad2560132925a835f0afddbcc1d311c961c14b
Deleted: sha256:d38b06cdb26a5c98857ddbc6ef531d3f57b00e325c0c314600b712efc7ff6ab0
Deleted: sha256:09687cd9cdf4c704fde969fdba370c2d848bc614689712bef1a31d0d581f2007
Deleted: sha256:b704a4a65bf536f82e5d8b86e633d19185e26313de8380162e778feb2852011a
Deleted: sha256:c37206160543786228aa0cce738e85343173851faa44bb4dc07dc9b7dc4ff1c1
Deleted: sha256:12912c9ec523f648130e663d9d4f0a47c1841a0064d4152bcf7b2a97f96326eb
Deleted: sha256:57d29ad88aa49f0f439592755722e70710501b366e2be6125c95accc43464844
Deleted: sha256:b17c024283d0302615c6f0c825137da9db607d49a83d2215a79733afbbaeb7c3
Deleted: sha256:13cb14c2acd34e45446a50af25cb05095a17624678dbafbcc9e26086547c1d74

10. 실습 : nginx 컨테이너를 띄워서 간단한 웹서버 만들어보자.

docker run -d –name myweb -p 80:80 nginx 명령어를 실행해보자.

-p 옵션 : 포트를 외부에 오픈한다.

root@ip-10-1-10-144:/home/ubuntu# docker run -d --name myweb -p 80:80 nginx
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
8559a31e96f4: Pull complete
1cf27aa8120b: Pull complete
67d252a8c1e1: Pull complete
9c2b660fcff6: Pull complete
4584011f2cd1: Pull complete
Digest: sha256:a93c8a0b0974c967aebe868a186e5c205f4d3bcb5423a56559f2f9599074bbcd
Status: Downloaded newer image for nginx:latest
25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
25559b6435e1        nginx               "/docker-entrypoint.…"   45 minutes ago      Up 45 minutes       0.0.0.0:80->80/tcp   myweb

위와 같이 명령어를 실행하면 아래 그림과 같이 도커 호스트 80과 컨테이너 80 포트를 바인딩하여 엔진엑스를 실행하는 것이다. 참고로 실습환경이 AWS ubuntu 환경의 EC2를 띄워서 했기 때문에 위의 명령어 실행이 완료되면 해당 호스트 아이피:80 을 통해 접근하면 엔진엑스에 접근할 수 있을것이다.

6

  • docker logs myweb 명령어로 로그를 체크해본다.

docker logs myweb -f 명령어로 로그를 연속해서 볼 수도 있다.

-f 옵션 : 로그를 연속해서 보여달라는 옵션

root@ip-10-1-10-144:/home/ubuntu# docker logs myweb
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
xxx.xxx.xxx.xxx - - [12/Jul/2020:08:43:52 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" "-"
2020/07/12 08:43:52 [error] 28#28: *2 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 175.121.250.226, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "13.124.248.31", referrer: "http://13.124.248.31/"
xxx.xxx.xxx.xxx - - [12/Jul/2020:08:43:52 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://13.124.248.31/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" "-"
xxx.xxx.xxx.xxx - - [12/Jul/2020:08:47:40 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" "-"
  • docker inspect myweb 명령어로 nginx 컨테이너의 상세 내역을 확인할 수 있다.
root@ip-10-1-10-144:/home/ubuntu# docker inspect myweb
[
    {
        "Id": "25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303",
        "Created": "2020-07-12T08:42:49.891201482Z",
        "Path": "/docker-entrypoint.sh",
        "Args": [
            "nginx",
            "-g",
            "daemon off;"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 7625,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-07-12T08:42:50.505774075Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0901fa9da894a8e9de5cb26d6749eaffb67b373dc1ff8a26c46b23b1175c913a",
        "ResolvConfPath": "/var/lib/docker/containers/25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303/hostname",
        "HostsPath": "/var/lib/docker/containers/25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303/hosts",
        "LogPath": "/var/lib/docker/containers/25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303/25559b6435e178f8847856329a3cadb685eac2a368885adc48be88ff7a66f303-json.log",
        "Name": "/myweb",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "80"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/678c35badf1fd18bb3bf0402ca96a206e2a329290295b0b7ad87804a44b2e3e4-init/diff:/var/lib/docker/overlay2/f5e6206370c4d427023bd75ba44ed5bc107929eb7f535729741b5666faac8002/diff:/var/lib/docker/overlay2/848e020e762c1fe47dadfd811a91b607d13bd59dd34863956ab2368cb4a3a3a7/diff:/var/lib/docker/overlay2/e2276f21acd246e6b9f24b762c18e06f65757ebdb7978a1f7013c4ab58150e01/diff:/var/lib/docker/overlay2/dae8070d9b73414723506ff322f7ab196c70302b34d0e674283ae7f3714bcd15/diff:/var/lib/docker/overlay2/ce8c7693934b0709d5af5518dc416fd51c8bf5f89414396f2365515f77f6f318/diff",
                "MergedDir": "/var/lib/docker/overlay2/678c35badf1fd18bb3bf0402ca96a206e2a329290295b0b7ad87804a44b2e3e4/merged",
                "UpperDir": "/var/lib/docker/overlay2/678c35badf1fd18bb3bf0402ca96a206e2a329290295b0b7ad87804a44b2e3e4/diff",
                "WorkDir": "/var/lib/docker/overlay2/678c35badf1fd18bb3bf0402ca96a206e2a329290295b0b7ad87804a44b2e3e4/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "25559b6435e1",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NGINX_VERSION=1.19.1",
                "NJS_VERSION=0.4.2",
                "PKG_RELEASE=1~buster"
            ],
            "Cmd": [
                "nginx",
                "-g",
                "daemon off;"
            ],
            "Image": "nginx",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "NGINX Docker Maintainers <docker-maint@nginx.com>"
            },
            "StopSignal": "SIGTERM"
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "4894f5824f5cc2ecd89e6dc474cd61e9c8fa2ca2df690f436cf7126f9abf81c5",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "80"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/4894f5824f5c",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "eb2b873d79aa7031025623b486688455818be0c61aebf44c7719e55e3f0b1e45",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "8c7f30cc1dd47524a7f83c9900b25f05f13b90af3b974be2a8429baa20e69a95",
                    "EndpointID": "eb2b873d79aa7031025623b486688455818be0c61aebf44c7719e55e3f0b1e45",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

그 다음에 해볼 nginx 실습 두번째로

그러면 아래와 같은 nginx.conf 설정파일을 적용한 나만의 nginx 컨테이너를 띄워보자.

nginx.conf 내용

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

이 nginx.conf 파일을 로컬에서 우분투의 /home/ubuntu 경로로 복사해준다.

그런 다음에 docker run –name myweb -v /home/ubuntu/nginx.conf:/etc/ngix/nginx.conf -d -p 80:80 nginx 명령어를 실행한다.

위의 명령어에서 -v 옵션은 공유할 호스트파일과 컨테이너 파일을 공유하겠다는 의미이다.

-v : 공유할 디렉토리 설정, -v [호스트 디렉토리]:[컨테이너 디렉토리]

root@ip-10-1-10-144:/home/ubuntu# docker run --name myweb -v /home/ubuntu/nginx.conf:/etc/ngix/nginx.conf -d -p 80:80 nginx
4a5956442ecd9891eb3009ab8f6437be6c7bbf7903ccda23f862e0375b46e1ba

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
4a5956442ecd        nginx               "/docker-entrypoint.…"   5 seconds ago       Up 4 seconds        0.0.0.0:80->80/tcp   myweb

웹브라우저에서 호스트아이피:80 으로 접속하면 아래 그림과 같이 젠킨스가 정상적으로 구동되는 것을 확인할 수 있다.

image

11. 실습 : nginx 컨테이너와 jenkins 컨테이너를 연결해보는 실습

step 1) docker run -d -p 8080:8080 -p 5000:5000 –name myjenkins jenkins 명령어로 jenkins 컨테이너를 실행

root@ip-10-1-10-144:/home/ubuntu# docker run -d -p 8080:8080 -p 5000:5000 --name myjenkins jenkins
Unable to find image 'jenkins:latest' locally
latest: Pulling from library/jenkins
55cbf04beb70: Pull complete
1607093a898c: Pull complete
9a8ea045c926: Pull complete
d4eee24d4dac: Pull complete
c58988e753d7: Pull complete
794a04897db9: Pull complete
70fcfa476f73: Pull complete
0539c80a02be: Pull complete
54fefc6dcf80: Pull complete
911bc90e47a8: Pull complete
38430d93efed: Pull complete
7e46ccda148a: Pull complete
c0cbcb5ac747: Pull complete
35ade7a86a8e: Pull complete
aa433a6a56b1: Pull complete
841c1dd38d62: Pull complete
b865dcb08714: Pull complete
5a3779030005: Pull complete
12b47c68955c: Pull complete
1322ea3e7bfd: Pull complete
Digest: sha256:eeb4850eb65f2d92500e421b430ed1ec58a7ac909e91f518926e02473904f668
Status: Downloaded newer image for jenkins:latest
5df9d25ce0eda2e6e901817fbdc9b48293bd12f549b98550834db6e871a9d350

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                       NAMES
5df9d25ce0ed        jenkins             "/bin/tini -- /usr/l…"   5 seconds ago       Up 4 seconds        0.0.0.0:5000->5000/tcp, 0.0.0.0:8080->8080/tcp, 50000/tcp   myjenkins

step 2) nginx to jenkins 연결을 설정하는 nginx.conf 설정파일 생성

아래와 같은 내용으로 nginx.conf 파일을 생성해준다.

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;

        location / {

          proxy_set_header        Host $host;
          proxy_set_header        X-Real-IP $remote_addr;
          proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header        X-Forwarded-Proto $scheme;

          # Fix the "It appears that your reverse proxy set up is broken" error.
          proxy_pass          http://jenkins:8080;
          proxy_read_timeout  90;
        }
      }
  }

이 nginx.conf 파일을 로컬에서 우분투의 /home/ubuntu 경로로 복사해준다.

step 3) docker run -p 80:80 -v /home/ubuntu/nginx.conf:/etc/nginx/nginx.conf –link myjenkins:jenkins -d nginx 명령어로 nginx 컨테이너를 실행하면서 jenkins 컨테이너를 연결해본다.

root@ip-10-1-10-144:/home/ubuntu# docker run -p 80:80 -v /home/ubuntu/nginx.conf:/etc/nginx/nginx.conf --link myjenkins:jenkins -d nginx
7ce3f8dfc43b1d408495214d595d075c8162575bd1acbdbf60da7b2537d614b8

root@ip-10-1-10-144:/home/ubuntu# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                       NAMES
7ce3f8dfc43b        nginx               "/docker-entrypoint.…"   8 seconds ago       Up 7 seconds        0.0.0.0:80->80/tcp                                          heuristic_dijkstra
5df9d25ce0ed        jenkins             "/bin/tini -- /usr/l…"   5 minutes ago       Up 5 minutes        0.0.0.0:5000->5000/tcp, 0.0.0.0:8080->8080/tcp, 50000/tcp   myjenkins

아래 그림과 같이 위에 명령어를 실행하고 웹브라우저에서 호스트아이피:80 으로 접속해보면 젠킨스가 뜨는 것을 확인할 수 있다.

7

  • docker ps -s 명령어로 컨테이너의 크기도 확인할 수 있다.
root@ip-10-1-10-144:/home/ubuntu# docker ps -s
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                                                       NAMES                SIZE
7ce3f8dfc43b        nginx               "/docker-entrypoint.…"   7 minutes ago       Up 7 minutes        0.0.0.0:80->80/tcp                                          heuristic_dijkstra   1.12kB (virtual 132MB)
5df9d25ce0ed        jenkins             "/bin/tini -- /usr/l…"   13 minutes ago      Up 13 minutes       0.0.0.0:5000->5000/tcp, 0.0.0.0:8080->8080/tcp, 50000/tcp   myjenkins            2.2MB (virtual 698MB)

12. 도커 컨테이너

  • 정의

1) 이미지를 실행한 상태

2) 읽기/쓰기가 가능한 파일 시스템(read-write layer)

3) 실행된 독립 어플리케이션

4) 컨테이너는 가상서버가 아니다.

8