The Docker User Guide

The Docker User Guide


Docker Main 홈페이지있는  Docker User Guide를 토대로 테스트한 결과를 정리해 보았습니다.

작업하던중 안되거나 아려웠던점 공유해 봅니다.


1. Getting Started with Docker Hub

  • How do I use Docker Hub?
  • Overview
    • Docker를 위한 중앙 hub 서비스
      • public docker 이미지를 호스팅
      • build를 돕기 위한 서비스 제공
      • docker 환경 관리
    • hosting 대상으로 만들어진 서비스
  • Note
    • 호스팅 서비스 이므로 해당 관련 사항 pass
  • URL

2. Dockerizing Applications: A "Hello world"

  • How do I run applications inside containers?
  • Overview
    • Docker는 container-based virtualization platform을 application에 제공
    • Docker 화 된 application 실행 해 보기
  • Note
    • Docker는 항상 container 안에서 application을 실행

2.1. Hello world

  • Hello world 실행
ubuntu@ubuntu:~$ sudo docker run ubuntu:14.04 /bin/echo 'Hello world'
Hello world
    • 실행 구문 설명
      • docker run
        • 명령어 구문
      • ubuntu:14.04
        • 특정 이미지
      • /bin/echo 'Hello world'
        • 신규 컨테이너에서 실행 할 문장

2.2. An Interactive Container

  • Overview
    • 대화형 컨테이너
      • 컨테이너 실행 시 shell로 접근
  • docker run
$ sudo docker run -t -i ubuntu:14.04 /bin/bash
root@af8bae53bdd3:/#
    • 실행 구문 설명
      • -t flag
        • 신규 컨테이너  내부에서 터미널 또는 tty 승인
      • -i flag
        • container와 대화형 접속 설정을 위한 설정
      • /bin/bash
        • container 내부에서 Bash shell 실행
  • 컨테이너 내부 확인
root@4ec41e45e35f:/# pwd
/
root@4ec41e45e35f:/# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr
  • Container에서 작업 종료 후 나올 때
    • Ctrl+D 또는 exit
root@4ec41e45e35f:/# exit
exit

2.3. A Daemonized Hello world

  • Overview
    • container를 daemon 형태로 실행
  • Docker daemon 형태로 실행
$ sudo docker run -d ubuntu:14.04 /bin/sh -c "while true; do echo hello world; sleep 1; done"

83a03c9e5f48e94cfa234d7d14efc16a6dfdff58b8405bbab0e1d991730d25a1
    • 실행 구문 설명
      • -d flag
        • container를 damonize 화 하여 실행
      • /bin/sh -c "while true; do echo hello world; sleep 1; done"
        • 1초 마다 hello world 실행
  • docker daemon 확인
ubuntu@ubuntu:~$ docker ps
CONTAINER ID        IMAGE               COMMAND                CREATED             STATUS              PORTS               NAMES
83a03c9e5f48        ubuntu:14.04        "/bin/sh -c 'while t   9 minutes ago       Up 9 minutes                            naughty_mccarthy
  • docker container log 확인
    • while 문이 실행되는 결과 정보를 해당 컨테이너에서 확인 하기
ubuntu@ubuntu:~$ docker logs naughty_mccarthy
hello world
hello world
...
^C
  • container 중지
ubuntu@ubuntu:~$ docker stop naughty_mccarthy
naughty_mccarthy
  • container 확인
$ docker ps
CONTAINER ID  IMAGE         COMMAND               CREATED        STATUS       PORTS NAMES

3. Working with containers

  • Overview
    • docker version 확인
      • Go 언어를 사용하므로 client 버전과 Go 버전 정보가 같이 나옴
ubuntu@ubuntu:~$ docker version
Client version: 1.6.2
Client API version: 1.18
Go version (client): go1.4.2
Git commit (client): 7c8fca2
OS/Arch (client): linux/amd64
Server version: 1.6.2
Server API version: 1.18
Go version (server): go1.4.2
Git commit (server): 7c8fca2
OS/Arch (server): linux/amd64

3.1. Get Docker command help

  • Docker 도움말 명령어
    • $ docker --help
  • Docker 특정 명령어의 도움말 확인 시 --help를 뒤에 작성
$ docker attach --help

Usage: docker attach [OPTIONS] CONTAINER

Attach to a running container

 --help=false        Print usage
 --no-stdin=false    Do not attach stdin
 --sig-proxy=true    Proxy all received signals to the process

3.2. Running a web application in Docker

  • Web application 동작을 위해 Python Flask application을 실행하는 예
$ docker run -d -P training/webapp python app.py
    • 실행 구문 설명
      • -P flag
        • host 내의 container에서 network port가 요구 될 때 mapping 하는 역할을 해줌
      • training/webapp
        • 단순한 Python Flask web application을 미리 빌드한 image

3.3. Viewing our web application container

  • 동작중 인 docker container 확인
ubuntu@ubuntu:~$ docker ps -l
CONTAINER ID        IMAGE                    COMMAND             CREATED             STATUS              PORTS                     NAMES
4582dc3ab9c9        training/webapp:latest   "python app.py"     39 minutes ago      Up 39 minutes       0.0.0.0:32768->5000/tcp   elegant_rosalind  
  • 위와 같이 임의 포트 외 특정 포트 사용하도록 설정하는 방법
$ docker run -d -p 80:5000 training/webapp python app.py
    • 실행 구문 설명
      • -p flag
        • 80포트에서 5000 포트로 전달 되도록 설정
  • 동작중 인 web application 확인

3.4. A network port shortcut

  • 특정 container에서 사용하는 port에 대한 host port query
ubuntu@ubuntu:~$ docker port elegant_rosalind 5000
0.0.0.0:32768

3.5. Viewing the web application’s logs

  • web application container 이름을 활용하여 logs 정보 확인
ubuntu@ubuntu:~$ docker logs -f elegant_rosalind
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
10.0.0.1 - - [19/Jun/2015 05:47:12] "GET / HTTP/1.1" 200 -
10.0.0.1 - - [19/Jun/2015 05:47:12] "GET /favicon.ico HTTP/1.1" 404 -

3.6. Looking at our web application container’s processes

  • docker top 명령어로 container 내에서 동작중 인 application 알아보기
ubuntu@ubuntu:~$ docker top elegant_rosalind
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                8660                747                 0                   14:02               ?                   00:00:01            python app.py

3.7. Inspecting our web application container

  • Docker container의 상태 및 상세 정보 보기
ubuntu@ubuntu:~$ docker inspect elegant_rosalind
[{
   "AppArmorProfile": "",
   "Args": [
       "app.py"
   ],
   "Config": {
       "AttachStderr": false,
       "AttachStdin": false,
       "AttachStdout": false,
       "Cmd": [
           "python",
           "app.py"
       ],
...
  • inspect 명령어 특정 요소를 추가하여 해당 값을 알아 오기
ubuntu@ubuntu:~$ docker inspect -f '{{ .NetworkSettings.IPAddress }}' elegant_rosalind
172.17.0.2

3.8. Stopping our web application container

  • container 중지
ubuntu@ubuntu:~$ docker stop elegant_rosalind
elegant_rosalind
  • container 상태 확인
ubuntu@ubuntu:~$ docker ps -l
CONTAINER ID        IMAGE                    COMMAND             CREATED             STATUS                        PORTS               NAMES
4582dc3ab9c9        training/webapp:latest   "python app.py"     About an hour ago   Exited (137) 19 seconds ago

3.9. Restarting our web application container

  • 중지한 container를 다시 시작하는 경우
    • 기존 중지된 container를 시작함
ubuntu@ubuntu:~$ docker start elegant_rosalind
elegant_rosalind
  • container 상태 확인
ubuntu@ubuntu:~$ docker ps -l
CONTAINER ID        IMAGE                    COMMAND             CREATED             STATUS              PORTS                     NAMES
4582dc3ab9c9        training/webapp:latest   "python app.py"     About an hour ago   Up 16 seconds       0.0.0.0:32769->5000/tcp   elegant_rosalind  
  • container를 재시작 하는 경우
ubuntu@ubuntu:~$ docker restart elegant_rosalind
elegant_rosalind

3.10. Removing our web application container

  • Overview
    • container 가 더 이상 필요 없는 경우 삭제
  • container 삭제 Error
ubuntu@ubuntu:~$ docker rm elegant_rosalind
Error response from daemon: Conflict, You cannot remove a running container. Stop the container before attempting removal or use -f
FATA[0000] Error: failed to remove one or more containers
  • container 중지 후 삭제
ubuntu@ubuntu:~$ docker stop elegant_rosalind
elegant_rosalind
ubuntu@ubuntu:~$ docker rm elegant_rosalind
elegant_rosalin

4. Working with Docker images

4.1. Listing images on the host

  • Overview
    • host 내에 있는 image 살펴 보기
    • tag 이미지 별로 실행하는 방법 살펴 보기
      • Repository의 TAG 정보를 명시하여 사용하는 것을 권장
  • image list
ubuntu@ubuntu:~$ docker images
REPOSITORY             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                 14.04               6d4946999d4f        6 days ago          188.3 MB
ubuntu                 latest              6d4946999d4f        6 days ago          188.3 MB
10.0.0.56:5000/hello   0.2                 25389a11bac2        10 days ago         227.3 MB
training/webapp        latest              02a8815912ca        4 weeks ago         348.8 MB
hello-world            latest              91c95931e552        8 weeks ago         910 B
  • Tag 이미지 별로 실행하는 방법
    • ubuntu:14.04
      • $ docker run -t -i ubuntu:14.04 /bin/bash
    • ubuntu:12.04
      • $ docker run -t -i ubuntu:12.04 /bin/bash
    • ubuntu:latest
      • 최신 버전의 ubuntu image 정보가 실행tag된

4.2. Getting a new image

  • Overview
    • 신규 이미지를 받는 방법
    • container 실행을 위해서 image를 미리 받을 경우를 위함
  • centos 이미지를 받는 방법
ubuntu@ubuntu:~$ docker pull centos
latest: Pulling from centos
f1b10cd84249: Pull complete
...
centos:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.
Digest: sha256:a4627c43bafc86705af2e8a5ea1f0ed34fbf27b6e7a392e5ee45dbd4736627cc
Status: Downloaded newer image for centos:latest
  • centos container 실행
    • 미리 이미지 다운로드 되어 기다림 없이 실행
ubuntu@ubuntu:~$ docker run -t -i centos /bin/bash
[root@94814c491656 /]#

4.3. Finding images

  • Overview
    • Docker image 검색 하기
    • Docker image는 다양한 목적으로 작성한 경우가 많으므로 검색 명령어가 용이
  • sinatra 이미지 검색
ubuntu@ubuntu:~$ docker search sinatra
NAME                           DESCRIPTION                       STARS     OFFICIAL   AUTOMATED
tdiary/rpaproxy-sinatra                                          1                    [OK]
shaoheshan/sinatra                                               0                    [OK]
hacker314159/ruby-sinatra                                        0                    [OK]
zoomix/sinatra-galleria                                          0                    [OK]
larmar/sinatra-puppet                                            0                    [OK]
dcarley/example-ruby-sinatra                                     0                    [OK]
llamashoes/docker-sinatra                                        0                    [OK]
erikap/ruby-sinatra            Docker for hosting Sinatra apps   0                    [OK]
synctree/sinatra-echo                                            0                    [OK]
gwjjeff/sinatra                                                  0                    [OK]

4.4. Pulling our image

  • Overview
    • 위에서 검색한 이미지를 토대로 다운 받아 테스트 해보기
  • image 받기
ubuntu@ubuntu:~$ docker pull shaoheshan/sinatra
  • 컨테이너 실행 테스트
ubuntu@ubuntu:~$ docker run -t -i shaoheshan/sinatra /bin/bash
root@3a0dae284315:/#

4.5. Creating our own images

  • Overview
    • 이미지로 생성된 container를 변경하여 그결과를 이미지에 저장
    • Dockerfile을 사용하여 이미지를 생성

4.5.1. Updating and committing an image

  • 이미지 update를 위해 해당 이미지로 container 생성
ubuntu@ubuntu:~$ docker run -t -i shaoheshan/sinatra /bin/bash
root@e99b7bd3a7dc:/#
  • 실행 중인 container 내에서 json gem을 추가
    • 작업 완료 후 exit로 나온다
root@e99b7bd3a7dc:/# gem install json
Installing RDoc documentation for json-1.8.3...
root@e99b7bd3a7dc:/# exit
  • container 변경된 내용 생성 하기
    • docker commit 명령어를 사용하여 이미지에 container 복사 본을 commit 함
ubuntu@ubuntu:~$ docker commit -m "Added json gem" -a "Taemin Kwon"  e99b7bd3a7dc ouruser/sinatra:v2

1d4bb779237d6734c07c171420d29a074557501d2d2afa30015b20abb23dfd8d
    • 실행 구문 설명
      • -m flag
        • 특정 커밋 메시지
      • -a flag
        • 작성자 이름
      • e99b7bd3a7dc
        • 특정 container로 신규 이미지 생성
      • ouruser/sinatra:v2
        • target 이미지 정보
        • ouruser
          • 신규 사용자 정보
        • sinatra
          • 원본 이미지 정보
        • v2
          • 이미지 tag 정보
  • 생성된 image 확인
ubuntu@ubuntu:~$ docker images
REPOSITORY             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ouruser/sinatra        v2                  1d4bb779237d        7 minutes ago       352.1 MB
shaoheshan/sinatra     latest              67dc32e67de1        3 months ago        347 MB
...
  • 신규 생성된 이미지로 container 실행
ubuntu@ubuntu:~$ docker run -t -i ouruser/sinatra:v2 /bin/bash
root@4b761250f9cc:/#

4.5.2. Building an image from a Dockerfile

  • Overview
    • docker commit을 사용하면  이미지 확장에 있어 매우 단순한 방법
    • 작업이 성가시거나 팀 사이의 이미지를 공유 함에 있어 개발 프로세스가 쉽지 않은 경우 신규 명령어 사용
      • docker build로 신규 이미지를 build
      • Dockerfile로 이미지를 어떻게 build 할 것인지 구성
  • 디렉터리와 Dockerfile 생성
ubuntu@ubuntu:~$ mkdir ~/sinatra
ubuntu@ubuntu:~$ cd ~/sinatra
ubuntu@ubuntu:~/sinatra$ touch Dockerfile
  • Dockerfile 수정
ubuntu@ubuntu:~$ vi ~/sinatra/Dockerfile

# This is a comment
FROM ubuntu:14.04
MAINTAINER Taemin Kwon
RUN apt-get update && apt-get install -y ruby ruby-dev
RUN gem install sinatra
    • Dockerfile 설명
      • 명령어 문장 형태로 구성
        • INSTRUCTION statement
        • 명령어는 대문자로 구성
      • #
        • 주석
      • FROM
        • base image 정보
      • MAINTAINER
        • 신규 이미지 관리자
      • RUN
        • 명령어를 실행 구문
  • Dockerfile과 docker build 명령어를 사용하여 이미지 생성하기
ubuntu@ubuntu:~/sinatra$ pwd
/home/ubuntu/sinatra
ubuntu@ubuntu:~/sinatra$ ls
Dockerfile
ubuntu@ubuntu:~/sinatra$ docker build -t ouruser/sinatra:v2 .
Removing intermediate container 013812932dd2
Successfully built c04f72210820
    • docker build 명령어 설명
      • -t flag
        • 신규 이미지
      • .
        • Dockerfile이 있는 위치를 가리켜야 함
          • 여기서는 현재 디렉터리
    • c04f72210820
      • image ID 정보
  • docker image 확인
ubuntu@ubuntu:~/sinatra$ docker images
REPOSITORY             TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ouruser/sinatra        v2                  c04f72210820        20 seconds ago      319.4 MB
  • 신규 이미지로 container 실행
ubuntu@ubuntu:~/sinatra$ docker run -t -i ouruser/sinatra:v2 /bin/bash
root@ada4da943649:/#

4.6. Setting tags on an image

  • Overview
    • commit 하거나 build 한 이미지에 tag 추가하기
  • image에 tag 생성
ubuntu@ubuntu:~$ docker tag 1d4bb779237d ouruser/sinatra:devel
  • 변경된 image 확인
ubuntu@ubuntu:~$ docker images ouruser/sinatra
REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ouruser/sinatra     v2                  c04f72210820        12 minutes ago      319.4 MB
ouruser/sinatra     devel               1d4bb779237d        49 minutes ago      352.1 MB

4.7. Image Digests

  • Overview
    • Image는 v2 또는 그 이후 버전을 사용하는 경우 digest라 불리는 내용 주소 식별자를 가지고 있음
    • 오랫동안 이미지 생성하는데 사용되는 값은 변하지 않기 때문에 digest를 예측이 가능
    • 해당 작업 정상 테스트 하지 못함
      • DIGEST 정보가 none 처리
  • digest 정보 확인
ubuntu@ubuntu:~# docker images --digests |head

REPOSITORY             TAG                 DIGEST              IMAGE ID            CREATED             VIRTUAL SIZE
ouruser/sinatra        v2                                c04f72210820        6 days ago          319.4 MB
ouruser/sinatra        devel                             1d4bb779237d        6 days ago          352.1 MB
centos                 latest                            7322fbe74aa5        7 days ago          172.2 MB
ubuntu                 14.04                             6d4946999d4f        13 days ago         188.3 MB
ubuntu                 latest                            6d4946999d4f        13 days ago         188.3 MB
ubuntu                 12.04                             78cef618c77e        13 days ago         133.7 MB
10.0.0.56:5000/hello   0.2                               25389a11bac2        2 weeks ago         227.3 MB
training/webapp        latest                            02a8815912ca        5 weeks ago         348.8 MB
hello-world            latest                            91c95931e552        9 weeks ago         910 B
    • Note
      • 여기서는 none으로 나와서 아무런 내용도 없음
  • push 또는 pull 명령어 사용 시 digest 사용하는 예
$ docker pull ouruser/sinatra@cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf
    • Note
      • tag를 사용하지 않고 digest 정보를 사용함을 알려줌
      • 정상 테스트 하지 못함
        • digest 정보 none
  • Note
    • create, run, rmi 명령어에서도 digest 정보를 참조하여 실행 가능

4.8. Push an image to Docker Hub

  • Overview
    • docker push 명령어를 사용하여 Docker hub에 이미지를 넣는 명령어
    • 현재 private repository로 연결되지 않았으므로 테스트 하지 않음
  • docker push
$ docker push ouruser/sinatra
The push refers to a repository [ouruser/sinatra] (len: 1)
Sending image list
Pushing repository ouruser/sinatra (3 tags)
. . .

4.9. Remove an image from the host

  • Overview
    • host에 등록된 image를 삭제 하는 명령어
  • shaoheshan/sinatra 삭제
    • container run 되어 있는지 확인
$ docker ps -a | grep shaoheshan/sinatra
e99b7bd3a7dc        shaoheshan/sinatra:latest   "/bin/bash"            6 days ago          Exited (0) 6 days ago                         focused_lovelace     
3a0dae284315        shaoheshan/sinatra:latest   "/bin/bash"            6 days ago          Exited (0) 6 days ago                         jovial_lovelace
    • 해당 container 삭제 후 image 삭제 가능
    • container 삭제
ubuntu@ubuntu:~# docker rm e99b7bd3a7dc
e99b7bd3a7dc
ubuntu@ubuntu:~# docker rm 3a0dae284315
3a0dae284315
    • image 삭제
ubuntu@ubuntu:~# docker rmi shaoheshan/sinatra
Untagged: shaoheshan/sinatra:latest
    • 삭제 image 확인
ubuntu@ubuntu:~# docker images | grep shaoheshan/sinatra
  • Note
    • images 가 삭제가 안되는 경우 run container를 확인 하여 삭제 후 삭제
ubuntu@ubuntu:~# docker rmi shaoheshan/sinatra

Error response from daemon: Conflict, cannot delete 67dc32e67de1 because the container 4b761250f9cc is using it, use -f to force
FATA[0000] Error: failed to remove one or more images


5. Linking containers together

  • Overview
    • container와 network port 간의 연동이 어떤 형태로 이루어 지는 지 확인

5.1. Connect using network port mapping

  • container 생성 후 Python Flask 프로그램 실행 해 보기
ubuntu@ubuntu:~# docker run -d -P training/webapp python app.py
198a42d4d5cdafb74ef9dc5e4e234a66b5afd814ae542dc25f6c19822ad8f52e
    • Note
      • inspect 명령어를 통해 IP 정보와 다양한 network 정보 확인
ubuntu@ubuntu:~$ docker inspect -f '{{ .NetworkSettings.IPAddress }}' focused_blackwell
  • 실행 된 docker port 확인
ubuntu@ubuntu:~# docker ps | grep focused_blackwell
198a42d4d5cd        training/webapp:latest   "python app.py"     11 minutes ago      Up 11 minutes       0.0.0.0:32768->5000/tcp   focused_blackwell
    • Note
      • 현재 임의의 포트(32768)로 5000에 연결된 것 확인
  • 80 port에 5000 port가 맵핑 되도록 구성되게 container 실행
    • host의 모든 80 port를 대상으로 할 때
ubuntu@ubuntu:~$ docker run -d -p 80:5000 training/webapp python app.py
65108f6d0f64da0ae046dfe6de46698f8570c819a7427b2712647669daa7e5c9
    • 특정 interface(localhost) 를 대상으로 할 때
ubuntu@ubuntu:~$ docker run -d -p 127.0.0.1:80:5000 training/webapp python app.py
3a35bef615b74681201c9b3073fe158d7d908df3adcff7777d25b25738560ed6
      • Note
        • 127.0.0.1 또는 localhost로 접근 하는 경우 forwarding 된다
    • udp protocol을 대상으로 할 때
ubuntu@ubuntu:~$ docker run -d -p 127.0.0.1:80:5000/udp training/webapp python app.py
968348d062f753ba3b980ca7519199572da17814b59d4a7c2f2cff8955fd72d8
  • docker port 정보 확인
    • focused_blackwell container에서 사용 중인 5000 포트 정보 확인
ubuntu@ubuntu:~$ docker port focused_blackwell 5000
0.0.0.0:32768

5.2. Connect with the linking system

5.2.1. The importance of naming

  • Overview
    • focused_blackwell 이름은 docker에서 자동 생성된 이름
    • web 또는 db 같은 형태로 이름을 특정 가능
    • --name flag를 사용하여 container 이름을 특정하기
  • web 이름 container 생성
ubuntu@ubuntu:~$ docker run -d -P --name web training/webapp python app.py
5aecdb1b64a1d64fdf41b45cdd8b2f4e149d9eae4431a157def2c501b8da977b
  • 최신 생성된 container 명령어로 web container 확인
ubuntu@ubuntu:~$ docker ps -l
CONTAINER ID        IMAGE                    COMMAND             CREATED              STATUS              PORTS                     NAMES
5aecdb1b64a1        training/webapp:latest   "python app.py"     About a minute ago   Up About a minute   0.0.0.0:32769->5000/tcp   web
  • Note
    • container 이름은 유일 해야 함
      • web 이란 이름의 container는 하나만 사용 가능
      • 실행 중인 web container 가 있다면 container 삭제가 선행 되어야 함

5.3. Communication across links

  • Overview
    • 컨테이너 간의 정보 전송을 위해 컨테이너 들 끼로 서로를 발견하여 연결하는 작업을 link 라 함
    • web과 db간의 연결
  • db container 생성
ubuntu@ubuntu:~$ docker run -d --name db training/postgres
  • 기존에 생성된 web 컨테이너 삭제
ubuntu@ubuntu:~$ docker rm -f web
  • db container에 연결되도록 web 컨테이너 생성
ubuntu@ubuntu:~$ docker run -d -P --name web --link db:db training/webapp python app.py

2fa7a37dc7cacfb4ff007cd5e78a71f98d2bd5f23bc81b0eabd24f74984ee302
    • 실행 구문 설명
      • --link db:db
        • --link :alias
        • --link 이 형태로 사용도 가능
  • inspect 명령어로 연결된 정보 확인
    • “[큰 따옴표]
ubuntu@ubuntu:~$ docker inspect -f "{{ .HostConfig.Links }}" web

[/db:/web/db]
    • Note
      • docker는 source container의 연결된 정보를 알려주어야 함
        • 환경 변수로 정의
        • /etc/hosts 파일 수정

5.3.1. Environment variables

  • Overview
    • Source container에 의한 port 변수 정의
      • _PORT__
      • components 설명
        • 은 --link parameter에 정의된 이름
        • 은 TCP, UDP 둘중 하나
    • prefix format 환경 변수
      • prefix_ADDR / IP 주소 정보
        • WEBDB_PORT_8080_TCP_ADDR=172.17.0.82
      • prefix_PORT / PORT 정보
        • WEBDB_PORT_8080_TCP_PORT=8080
      • prefix_PROTO / Protocol 정보
        • WEBDB_PORT_8080_TCP_PROTO=tcp
  • container 생성 시 만들어지는 환경 변수 확인
    • 아래 명령은 container를 실행 후 바로 삭제되고 env 명령어로 환경변수를 확인하는 명령어
ubuntu@ubuntu:~$ docker run --rm --name web2 --link db:db training/webapp env

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=2a2461cc2de5
DB_PORT=tcp://172.17.0.1:5432
DB_PORT_5432_TCP=tcp://172.17.0.1:5432
DB_PORT_5432_TCP_ADDR=172.17.0.1
DB_PORT_5432_TCP_PORT=5432
DB_PORT_5432_TCP_PROTO=tcp
DB_NAME=/web2/db
DB_ENV_PG_VERSION=9.3
HOME=/root

5.3.2. Important notes on Docker environment variables

  • Overview
    • 환경 변수에 저장된 IP 정보는 source container가 재시작 되는 경우 자동으로 update 되지 않음
    • container 연결된 IP 정보를 /etc/hosts 에 등록하는 것을 권장

5.3.3. Updating the /etc/hosts file

  • web container 실행 후 /etc/hosts 정보 확인
ubuntu@ubuntu:~$ docker run -t -i --rm --link db:webdb training/webapp /bin/bash

root@75611ea38ea0:/opt/webapp# cat /etc/hosts

172.17.0.4 75611ea38ea0
...
172.17.0.1 webdb 4ae0778616d3 db
  • webdb 로 ping 테스트
root@75611ea38ea0:/opt/webapp# apt-get install -yqq inetutils-ping
(Reading database ... 18233 files and directories currently installed.)
Removing ubuntu-minimal (1.325) ...
Removing iputils-ping (3:20121221-4ubuntu1.1) ...
Selecting previously unselected package inetutils-ping.
(Reading database ... 18221 files and directories currently installed.)
Preparing to unpack .../inetutils-ping_2%3a1.9.2-1_amd64.deb ...
Unpacking inetutils-ping (2:1.9.2-1) ...
Setting up inetutils-ping (2:1.9.2-1) …

root@75611ea38ea0:/opt/webapp# ping webdb
PING webdb (172.17.0.1): 56 data bytes
64 bytes from 172.17.0.1: icmp_seq=0 ttl=64 time=0.164 ms
64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.076 ms
  • source container 재시작 되는 경우 /etc/hosts 정보가 자동으로 update 됨
    • restart db container
ubuntu@ubuntu:~$ docker restart db
db
    • /etc/hosts 정보가 바뀐것 확인
ubuntu@ubuntu:~$ docker run -t -i --rm --link db:db training/webapp /bin/bash

root@69d81f7d1657:/opt/webapp# cat /etc/hosts
172.17.0.6 69d81f7d1657
172.17.0.5 db 4ae0778616d3
root@69d81f7d1657:/opt/webapp#
      • Note
        • 다른 container에서도 db host 정보가 바뀐 것것 확인 가능

6. Managing data in containers

  • Docker에서 data 관리 방법
    • Data volumes
    • Data volume containers
  • Note
    • 6.2. 항목과 6.3. 항목 다시 테스트가 필요

6.1. Data volumes

  • Data volume 특징
    • container가 생성될 때 볼륨이 초기화 됨
      • 만약 container 기반 이미지에 특정 mount 포인트 정보를 가지고 있으면, 신규 볼륨 초기화 시 해당 정보도 같이 복사
    • data volume은 container 사이 재사용되며 공유 될 수 있음
    • data volume에 대한 변경 사항은 직접 만들어짐
    • data volume에 대한 변경 사항은 image에 변경 시 적용되지 않음
    • 이미지를 업데이트 할 때 데이터 볼륨에 대한 변경 사항은 포함되지 않음
    • data volume은 container가 삭제 되어도 지워 지지 않음

6.1.1. Adding a data volume

  • Overview
    • -v flag를 사용하여 data volume을 container 추가 가능
  • 단일 volume을 web application에 mount 하기
ubuntu@ubuntu:~$ docker run -d -P --name web -v /webapp training/webapp python app.py

33047231a042e88e1058419553880e1fec8f04dc7643b6a7f16216e0d5860590
    • 실행 구문 설명
      • -v /webapp
        • container 내부의 신규 볼륨을 생성
    • Error
      • 같은 이름의 continaer 있는 경우 Error 발생
FATA[0000] Error response from daemon: Conflict. The name "web" is already in use by container 2fa7a37dc7ca. You have to delete (or rename) that container to be able to reuse that name.

6.1.2. Locating a volume

  • volume 정보 확인
ubuntu@ubuntu:~$ docker inspect web

...
   "Volumes": {
       "/webapp": "/var/lib/docker/vfs/dir/76ae781f0981e59b8eb777af50f81108e8e2ab91229c4e47e4cf3959b0293b7a"
   },
   "VolumesRW": {
       "/webapp": true
   }
}
]
    • VolumesRW
      • volume이 read/write 가 가능 하도록 특정한 것

6.1.3. Mount a host directory as a data volume

  • Overview
    • docker daemon의 host 디렉터리를 container에 mount 하는 경우 -v 사용
    • 사용 형태
      • docker run -v /Users/:/
  • host 디렉터리를 container에 mount 하기
    • /src/webapp to /opt/webapp
ubuntu@ubuntu:~$ docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py

d87a92105dfb44732b846472630600893578c6b6676fa12248d249108cb7db53
  • read-only 형태로 mount 하기
ubuntu@ubuntu:~$ docker run -d -P --name web -v /src/webapp:/opt/webapp:ro training/webapp python app.py

334ccb42985c827b1016cfe8e54fe552d31706e80136c75c2723c547b34a084f
    • container 상세 확인
ubuntu@ubuntu:~$ docker inspect web
...
   },
   "Volumes": {
       "/opt/webapp": "/src/webapp"
   },
   "VolumesRW": {
       "/opt/webapp": false
   }
}
]

6.1.4. Mount a host file as a data volume

  • Overview
    • -v flag를 사용하여 단일 파일을 마운트
  • file mount
ubuntu@ubuntu:~$ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash
root@3845dedc1128:/# cat .bash_history
    • Note
      • bash shell의 history 정보를 확인 가능

6.2. Creating and mounting a data volume container

  • Overview
    • 컨테이너들 사이에서 지속적으로 사용 가능한 데이터 관리를 위해 사용
    • 추후 추가 테스트가 필요
      • data volume에 대한 접근 방법 인지 아닌지
  • training/postgres 를 재사용하여 container 생성
    • application을 동작하지는 않음
ubuntu@ubuntu:~$ docker create -v /dbdata --name dbdata training/postgres /bin/true

c833e8289fee7d81c8d8200f6deb8d3c32dd9e2e68c92d41e64cded682bb2a1e
  • 기존 생성한 container의 /dbdata를 다른 container에 mount 함
ubuntu@ubuntu:~$ docker run -d --volumes-from dbdata --name db1 training/postgres

f9e9837f018216084c396afa22980169cbbec9bda562483668543f2665114aa4

ubuntu@ubuntu:~$ docker run -d --volumes-from dbdata --name db2 training/postgres
4379539ab956c170e825e855790335c66b1b0d06c67e136b73d227d6ddf01be4
  • db1, db2의 생성된 정보를 통해서 다른 container에 확장하여 실행
ubuntu@ubuntu:~$ docker run -d --name db3 --volumes-from db1 training/postgres
ba1c396a7c19850e507a5b9ca9d349047e101124744138417626c2806f1f702a

6.3. Backup, restore, or migrate data volumes

  • Overview
    • volume에 대한 백업 복구 마이그레이션을 위한 기능
    • 테스트 실행 실패
  • 기존에 --volumes-from flag를 통한 신규 container에 volume mount를 활용
$ docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata

tar: Removing leading `/' from member names
/dbdata/
    • 명령어 설명
      • 신규 컨테이너 실행하고 dbdata container의 volume을 mount 함
        • host 디렉터리의 /backup 폴더에 mount
      • dbdata volume 내용을 backup.tar 파일로 압축 하여 /backup 디렉토리에 넣음
      • 명령어 완료 후  container 정지
  • 복구할 container 생성
ubuntu@ubuntu:~$ docker run -v /dbdata --name dbadata2 ubuntu /bin/bash
  • un-tar 신규 컨테이너에 복구
ubuntu@ubuntu:~$ docker run --volumes-from dbdata2 -v $(pwd):/backup ubuntu cd /dbdata && tar xvf /backup/backup.tar

FATA[0000] Error response from daemon: Could not apply volumes of non-existent container "dbdata2".


7. Working with Docker Hub

7.1. Get started with Docker Hub

  • Overview
    • Docker Hub의 공개 repository 사용과 함께 사설 repository 구성

7.2. Docker commands and Docker Hub

  • Overview
    • docker search, pull, login and push 명령어를 활용한 Docker Hub 서비스 사용

7.2.1. Account creation and login

  • Overview
    • Docker Hub에 login 하기
    • 인증 정보 저장을 위해 .dockercfg 파일 사용
      • 사용자 home directory에 저장
  • login
$ docker login

7.3. Searching for images

  • Overview
    • docker hub에 등록된 image 검색하기
  • search centos
ubuntu@ubuntu:~$ docker search centos
NAME                          DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
centos                        The official build of CentOS.                   1099      [OK]       
tutum/centos                  Centos image with SSH access. For the root...   13                   [OK]
blalor/centos                 Bare-bones base CentOS 6.5 image                9                    [OK]
torusware/speedus-centos      Always updated official CentOS docker imag...   6                    [OK]
million12/centos-supervisor   Base CentOS-7 with supervisord launcher, h...   5                    [OK]
jdeathe/centos-ssh            CentOS-6 6.6 x86_64 / EPEL Repo. / OpenSSH...   3                    [OK]
layerworx/centos              A general CentOS 6 image with the EPEL6 an...   2                    [OK]
jdeathe/centos-ssh-mysql      CentOS-6 6.6 x86_64 / MySQL.                    2                    [OK]
pdericson/centos              Docker image for CentOS                         0                    [OK]
nathonfowlie/centos-jre       Latest CentOS image with the JRE pre-insta...   0                    [OK]
    • 검색 결과 살펴 보기
      • tutum/centos
        • tutum은 사용자 이름을 가리킴
        • centos로 표시된 두번째 이름은 명시적으로 centos 를 가리키는 것은 아님
      • Official Repositories 로 정의된 항목이 공식적인 image 정보
  • pull 명령어로 이미지 가져오기
ubuntu@ubuntu:~$ docker pull centos

latest: Pulling from centos

f1b10cd84249: Download complete
c852f6d61e65: Download complete
7322fbe74aa5: Download complete
Digest: sha256:a4627c43bafc86705af2e8a5ea1f0ed34fbf27b6e7a392e5ee45dbd4736627cc
Status: Image is up to date for centos:latest

7.4. Contributing to Docker Hub

  • Overview
    • docker hub 내용은 누구나 pull 이 가능
    • 이미지 공유를 위해서는 인증이 필요

7.5. Pushing a repository to Docker Hub

  • Docker hub에 이미지 등록
    • 이미지 등록 형태
      • $ docker push yourname/newimage

7.6. Features of Docker Hub

  • 개인 repository 기능
    • sign up 하여 public 공간에 private repository 구현
  • 조직과 팀
    • 사설 repository를 통하여 구성원에게만 제공 되도록 설정 가능
  • 자동 빌드
    • docker hub 위에 직접 올려서 github, bitbucket에 이미지가 등록되면 자동으로 build 되는 것
  • Webhooks
    • image나 변경된 image가 push 될 때 이벤트를 일으켜 repository에 접근하도록 하는 것
    • image push 하거나 배포할 때 특정 URL과 JSON을 사용


8. Docker Compose

8.1. Overview of Docker Compose

  • Overview
    • Docker가 multi-container에서 동작하고 정의하기 위해 사용하는 tool
    • 단일 파일에서 multi-continaer를 정의하기 위함
    • compose는 개발 환경 구성에 적합
  • Compose 기본 구성 3단계
    • Dockerfile에 app에 요구되는 변수 정보 정의
    • docker-compose.yml 파일 안에 app 실행에 필요한 종속되는 환경 정보와 함께 서비스를 정의
    • dcoker-compose up 명령어를 통해 전체 app을 실행하고 시작함
    • docker-compose.yml 파일 예
web:
 build: .
 ports:
  - "5000:5000"
 volumes:
  - .:/code
 links:
  - redis
redis:
 image: redis
  • Compose 명령어는 application의 전체 lifecycle을 관리
    • 서비스의 시작, 중지와 Rebuild
    • 서비스 상태 확인
    • 서비스 로깅 정보 확인
    • 서비스에 명령(일회성) 실행

8.2. Compose documentation

8.3. Quick start

  • Overview
    • Compose 명령어를 통해 간단한 web app을 실행해 보기

8.3.1. Installation and set-up

8.3.1.1. install Docker and Compose

  • github에서 docker-compose 파일 받아오기
    • 파일 받아오고 권한 설정
$ sudo -i
$ curl -L https://github.com/docker/compose/releases/download/1.3.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

$ chmod +x /usr/local/bin/docker-compose

8.3.1.2. Installing Command Completion

  • /etc/bash_completion.d/ 디렉토리 안에 해당 파일 가져오기
$ sudo -i
$ curl -L https://raw.githubusercontent.com/docker/compose/$(docker-compose --version | awk 'NR==1{print $NF}')/contrib/completion/bash/docker-compose > /etc/bash_completion.d/docker-compose
    • URL
      • https://docs.docker.com/compose/completion/

8.3.1.3. directory and 환경 파일 생성

  • 디렉토리 생성
$ mkdir composetest
$ cd composetest
  • 디렉터리 안에 appy.py 파일 생성
from flask import Flask
from redis import Redis
import os
app = Flask(__name__)
redis = Redis(host='redis', port=6379)

@app.route('/')
def hello():
   redis.incr('hits')
   return 'Hello World! I have been seen %s times.' % redis.get('hits')

if __name__ == "__main__":
   app.run(host="0.0.0.0", debug=True)
  • 디렉토리 안에 requirements.txt 파일 생성
flask
redis

8.3.2. Create a Docker image

  • Overview
    • App에 종속적인 docker image 생성하기
  • Dockerfile 생성
    • 위에서 생성한 composetest 디렉터리 안에 Dockerfile 생성
FROM python:2.7
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt
CMD python app.py
    • 설정 내용 설명
      • ADD . /code
        • 현재 디렉터리 /code 안에 이미지를 생성
      • WORKDIR /code
        • 작업 디렉터리는 /code 임
      • FROM python:2.7
        • python install
      • CMD python app.py
        • 명령어 실행

8.3.3. Define services

  • docker-compose.yml 파일 정의
web:
 build: .
 ports:
  - "5000:5000"
 volumes:
  - .:/code
 links:
  - redis
redis:
 image: redis
    • 설정 내용 설명
      • web
        • 현재 디렉터리에 빌드 됨
        • 5000 port 사용
        • redis 서비스와 연결
      • redis
        • docker hub에 등록된 redis 이미지 사용

8.3.4. Build and run your app with Compose

  • Overview
    • docker-compose 명령어를 사용하여 위에서 정의한 정보대로 구성 보기
  • docker-compose 실행
ubuntu@ubuntu:~/$ cd composetest

ubuntu@ubuntu:~/composetest$ docker-compose up
Recreating composetest_redis_1...
Building web...
Step 0 : FROM python:2.7
web_1   |  * Restarting with stat
Hello World! I have been seen 1 times.
  • docker-compose를 daemon 형태로 실행
    • daemon 형태로 실행
ubuntu@ubuntu:~/composetest$ docker-compose up -d
Recreating composetest_redis_1...
Recreating composetest_web_1...
  • docker-compose로 동작 중인 것 확인
ubuntu@ubuntu:~/composetest$ docker-compose ps
     Name             Command             State              Ports       
-------------------------------------------------------------------------
composetest_redi   /entrypoint.sh     Up                 6379/tcp         
s_1                redis-server                                           
composetest_web_   /bin/sh -c         Up                 0.0.0.0:5000->50
1                  python app.py                         00/tcp
  • docker-compose run 명령어로 container에 단일 명령 수행
    • web container에 env 명령어를 수행하여 살펴 보기
ubuntu@ubuntu:~/composetest$ docker-compose run web env
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=90b5c98adf5e
TERM=xterm
REDIS_1_PORT=tcp://172.17.0.5:6379
REDIS_1_PORT_6379_TCP=tcp://172.17.0.5:6379
REDIS_1_PORT_6379_TCP_ADDR=172.17.0.5
  • docker-compose stop 으로 container 중지
ubuntu@ubuntu:~/composetest$ docker-compose stop
Stopping composetest_web_1...
Stopping composetest_redis_1...
    • docker-compose up으로 수행된 모든 container가 중단되는 것 확인 가능

9. Docker Machine / Beta / Pass

  • Overview
    • computer, cloud 제공자, data center에 docker host를 생성 시 docker machine을 사용
    • 현재 beta 버전 테스트 중이므로 pass


10. Docker Swarm / Beta / Pass

  • Overview
    • docker native cluster 구현을 위한 프로젝트
    • 현재 beta version 이므로 pass


11. Getting help / Link




Google Drive

https://docs.google.com/document/d/1V0zZHfi9BOQ3wpLHTn6_nEePhSwkR8fnL1QXdNeLVk8/edit?usp=sharing

댓글

이 블로그의 인기 게시물

CoreOS Vagrant on Windows.md

Install Docker