Heesung Yang

Docker

docker-ce 20.10.12 기준으로 작성된 내용

설치

CentOS 7

~$ yum install yum-utils device-mapper-persistent-data lvm2
~$ yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
~$ yum install docker-ce
~$ systemctl enable --now docker

설정

  • 설정 파일 : /etc/docker/daemon.json

데이터 저장 위치 변경

  • default : /var/lib/docker
{
    "data-root": "/home/docker",
}

docker0 IP 변경

  • default : 172.17.0.1/255.255.0.0
  • 가끔 호스트 대역과 겹치는 일이 발생하여 IP 대역을 바꿔야 할 경우 사용
{
    "bip": "254.254.0.1/24",
}

docker container network 변경

{
    "default-address-pools":[
        {
            "base":"254.254.0.0/16",
            "size":24
        }
    ]
}

runtime 추가

nvidia runtime

docker 19.03 이전 버전까지는 nvidia 사용을 위해 nvidia runtime을 설정해야 했다. 이를 위해선 nvidia-docker2 패키지도 설치해야 한다. docker 19.03 버전부터는 docker native gpu 를 지원하므로 nvidia runtime을 추가할 필요가 없다.

  1. nvidia-docker2 설치

    ~$ distribution=$(. /etc/os-release;echo $ID$VERSION_ID)
    ~$ curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo
    ~$ sudo yum install nvidia-docker2
    
  2. runtime 추가

    {
        "runtimes": {
            "nvidia": {
                "path": "/usr/bin/nvidia-container-runtime",
                "runtimeArgs": []
            }
        }
    }
    

명령어

이미지 찾기

아래 명령어로는 각 이미지의 tag를 검색할 수 없다.

# docker search <image>
~$ docker search centos
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
centos                            The official build of CentOS.                   7018      [OK]
ansible/centos7-ansible           Ansible on Centos7                              135                  [OK]
consol/centos-xfce-vnc            Centos container with "headless" VNC session…   135                  [OK]
jdeathe/centos-ssh                OpenSSH / Supervisor / EPEL/IUS/SCL Repos - …   121                  [OK]
centos/systemd                    systemd enabled base container.                 105                  [OK]
imagine10255/centos6-lnmp-php56   centos6-lnmp-php56                              58                   [OK]
tutum/centos                      Simple CentOS docker image with SSH access      48
centos/postgresql-96-centos7      PostgreSQL is an advanced Object-Relational …   45
jdeathe/centos-ssh-apache-php     Apache PHP - CentOS.                            31                   [OK]
kinogmt/centos-ssh                CentOS with SSH                                 29                   [OK]
guyton/centos6                    From official centos6 container with full up…   10                   [OK]
nathonfowlie/centos-jre           Latest CentOS image with the JRE pre-install…   8                    [OK]
centos/tools                      Docker image that has systems administration…   7                    [OK]
drecom/centos-ruby                centos ruby                                     6                    [OK]
roboxes/centos8                   A generic CentOS 8 base image.                  5
mamohr/centos-java                Oracle Java 8 Docker image based on Centos 7    4                    [OK]
darksheer/centos                  Base Centos Image -- Updated hourly             3                    [OK]
amd64/centos                      The official build of CentOS.                   2
miko2u/centos6                    CentOS6 日本語環境                                   2                    [OK]
dokken/centos-7                   CentOS 7 image for kitchen-dokken               2
blacklabelops/centos              CentOS Base Image! Built and Updates Daily!     1                    [OK]
mcnaughton/centos-base            centos base image                               1                    [OK]
starlabio/centos-native-build     Our CentOS image for native builds              0                    [OK]
jelastic/centosvps                An image of the CentOS Elastic VPS maintaine…   0
smartentry/centos                 centos with smartentry                          0                    [OK]

이미지 받기

# docker pull <image>:<tag>
~$ docker pull centos:7
7: Pulling from library/centos
Digest: sha256:c73f515d06b0fa07bb18d8202035e739a494ce760aa73129f60f4bf2bd22b407
Status: Downloaded newer image for centos:7
docker.io/library/centos:7

다운받은 이미지 리스트 확인

# 두 명령어 모두 사용 가능
~$ docker images
~$ docker image ls
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
centos        7         eeb6ee3f44bd   5 months ago    204MB
golang        1.12.5    1ef078f0da9e   2 years ago     774MB
postgres      11.3      4e045cb8eecd   2 years ago     312MB

container 생성과 시작

# docker run -it --name <container name> <image>:<tag> <command>
~$ docker run -it --name hello centos:7 /bin/bash

실행 시 아래와 같이 container 내부의 bash 쉘이 실행된 상태가 된다. hostname은 container ID다.

[root@fb53ec6b4d0d /]#

container 빠져나오기

~$ docker run -it --name hello centos:7 /bin/bash

위와 같이 bash 명령어로 container를 실행한 경우 exit 명령어를 입력하면 container도 같이 종료된다. exit 명령어는 현재 실행 중인 bash shell을 종료하고, bash shell이 종료되면 container는 더 이상 실행할 명령어가 없기 때문이다.

만약 container를 중지하지 않고 container 외부로 빠져나오고 싶은 경우, 아래 커맨드를 입력한다.

Ctrl+P , Ctrl+Q

container 접속

docker attach <container name>
docker attach hello
  • container 실행 시 /bin/bash 를 실행했으므로 명령 프롬프트가 뜸
  • container 실행 시 application 을 실행했다면 출력만 볼 수 있음
docker exec -it <container name> /bin/bash

container 목록

  • 실행 중인 container 목록

    ~$ docker ps
    
    NAMES                IMAGE         STATUS                      PORTS
    hello                centos:7      Up 5 minutes
    
  • 실행 중지된 conatiner 포함 목록

    ~$ docker ps -a
    
    NAMES                IMAGE         STATUS                      PORTS
    hello                centos:7      Up 5 minutes
    nostalgic_robinson   eeed133b351f  Exited (7) 14 hours ago
    

container 시작

container 이름과 ID 중 하나를 사용하면 된다.

# docker start <container id>
~$ docker start 478a9a66b354

# docker start <container name>
~$ docker start hello

container 재시작

container 이름과 ID 중 하나를 사용하면 된다.

# docker restart <container name / container ID>
~$ docker restart hello

외부에서 container 안의 명령 실행하기

  • 패키지 설치등을 할때 사용하면 유용

    # docker exec <container name> <command> <arguments>
    ~$ docker exec hello yum install openssh-clients
    
  • 만약, bash shell 처럼 사용자 입력이 필요한 명령어를 실행할 경우 -it 옵션을 사용해야 한다.

    # docker exec -it <container name> <command>
    ~$ docker exec -it hello /bin/bash
    

container 중지

# docker stop <container name / container ID>
~$ docker stop hello
  • 특정 이미지로 만들어진 container 모두 종료

    # ancestor : 이미지 명
    ~$ docker stop $(docker ps -q --filter ancestor=centos:7)
    

container 삭제

# docker rm <container name>
~$ docker rm hello
  • 특정 이미지로 만들어진 container 모두 종료

    # ancestor : 이미지 명
    ~$ docker rm $(docker ps -a -q --filter ancestor=centos:7)
    

이미지 삭제

# docker rmi <image>:<tag>`
~$ docker rmi centos:7`

# 이미지의 모든 태그 삭제
# docker rmi <image>`
~$ docker rmi centos`

전체 container ip 확인

~$ docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -qa)
/hello - 172.21.0.4
/hello2 - 172.21.0.3

docker container terminal resize

종종 host 터미널 창 크기보다 container 내부의 터미널 창 크기가 작아서 글씨가 잘리는 경우가 있다. 그럴 때 사용하자.

~$ docker exec -it -e COLUMNS=$COLUMNS hello /bin/bash

-e는 환경 변수를 설정하는 옵션이고, 사용 가능한 환경 변수 중 터미널과 연관된 환경 변수는 다음과 같다.

  • COLUMNS : 터미널 가로 크기
  • LINES : 터미널 세로 크기

Docker 이미지 생성

  1. Dockerfile 생성

    FROM centos:7
    
  2. docker 이미지 생성

    ~$ docker build --tag <tag> .
    ~$ docker build --tag vod:0.1 .
    ~$ docker build --tag build-cdn:1.0 -f Dockerfile.castis.build.cdn .
    

Docker tip

docker conatiner 내부에서 한글 사용해야 할 때 (ubuntu 기준)

RUN apt-get update
RUN apt-get install  -y language-pack-ko
RUN locale-gen ko_KR.UTF-8
ENV LANG ko_KR.UTF-8
ENV LANGUAGE ko_KR.UTF-8
ENV LC_ALL ko_KR.UTF-8

Container 내부에서 netstat 명령어 없이 listen port 확인

~$ docker exec -it ${CONTAINER_NAME} bash
~$ awk 'function hextodec(str,ret,n,i,k,c){
    ret = 0
    n = length(str)
    for (i = 1; i <= n; i++) {
        c = tolower(substr(str, i, 1))
        k = index("123456789abcdef", c)
        ret = ret * 16 + k
    }
    return ret
}
function getIP(str,ret){
    ret=hextodec(substr(str,index(str,":")-2,2)); 
    for (i=5; i>0; i-=2) {
        ret = ret"."hextodec(substr(str,i,2))
    }
    ret = ret":"hextodec(substr(str,index(str,":")+1,4))
    return ret
} 
NR > 1 {{if(NR==2)print "Local - Remote";local=getIP($2);remote=getIP($3)}{print local" - "remote}}' /proc/net/tcp 

docker-compose

# 이미지 새로 빌드
docker-compose up -d --force-recreate --build