Docker

도커(Docker) 개념 잡기

늘이 2022. 12. 14. 15:15

1. 정의

우리가 작성한 코드를 서버에서 실행하기 위해서는 OS 설치, 실행 환경 세팅, 빌드, 라이브러리 다운로드 등의 많은 과정이 필요함.

도커는 우리가 만든 어플리케이션을 원하는 환경에서 실행하는 것을 도와주는 것

 

 

2. 구성요소

출처: https://docs.docker.com/get-started/overview/

Client

사용자가 docker를 사용하기 위해 사용하는 CLI(Command Line Interface)

 

DOCKER_HOST

1) 컨테이너(Containers)

- 이미지를 사용하여 실행한 것으로 프로세스의 독립성을 보장하기 위해서 네트워크나 저장소가 분리되어 있음

- 격리된 공간에서 프로세스가 동작하는 기술, 가상화 기술의 일종이지만 기존 가상화는 OS 가상화가 일반적이였다면, 도커는 프로세스를 격리하는 방식으로 cpu나 메모리도 필요한 만큼만 사용하기 때문에 성능 손실이 거의 없음

 

 

2) 이미지(Images)

- 컨테이너 실행에 필요한 파일과 설정값 등을 포함하고 있는 파일

- 예를 들어 ubuntu이미지는 ubuntu를 실행하기 위한 모든 파일을 가지고 있고, MySQL이미지는 MySQL을 실행하는데 필요한 파일과 실행 명령어, 포트 정보 등을 가지고 있음

 

 

3) Dockerd(docker daemon)

- 도커 API request를 받아서 도커 object(images, container 등)를 관리

 

 

Registry

- 도커 이미지를 저장하는 공간

 

- 보통 도커 이미지의 용량은 수백 메가 이상으로 기가 이상의 용량의 경우도 많아 큰 용량의 이미지를 서버에 저장하고 관리하는 것이 쉽지 않지만 도커는 Docker hub를 제공하여 공개 이미지를 무료로 관리해줌

 

 

3. 장점

- 컨테이너 실행을 위한 모든 파일을 가지고 있기 때문에 의존성 파일을 컴파일하고 설치할 필요 없음

- 새로운 서버가 추가되면 준비되어있는 이미지를 다운받고 컨테이너를 생성하면 됨

- 한 서버에 여러개의 컨테이너 실행이 가능함

 

 

4. 도커 기본 명령어

 

명령어의 옵션 확인

docker run은 docker image를 사용해서 container를 실행하는 명령어

// 옵션 확인하기
docker run --help

더보기
Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
      --annotation map                 Add an annotation to the container (passed through to the OCI runtime) (default map[])
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always", "missing", "never") (default "missing")
  -q, --quiet                          Suppress the pull output
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop the container
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container
 sky  ~ 
 sky  ~  docker run --help

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Create and run a new container from an image

Aliases:
  docker container run, docker run

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
      --annotation map                 Add an annotation to the container (passed through to the OCI runtime) (default map[])
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always", "missing", "never") (default "missing")
  -q, --quiet                          Suppress the pull output
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop the container
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

 

1) run: 실행

docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...]

 

[자주사용하는 옵션]

옵션 설명
-d detach, 도커를 run(실행)하면 바로 컨테이너 process 자체가 쉘에 뜨는데 이 옵션을 넣으면 백그라운드로 실행한다는 뜻
-p publish, 호스트 포트와 컨테이너의 포트 연결(포워딩)
이 설정을 사용하기 위해서는 호스트(서버 또는 pc)에서 사용 중인 포트 번호와 겹치지 않는지 확인 필요
-v 호스트와 컨테이너의 디렉토리 연결(마운트)
-name 컨테이너명 설정
-rm 프로세스 종료 시 컨테이너 자동 제거
-it -i 입력, -t 터미널, 터미널 입력
-link 컨테이너 연결[컨테이너:별칭]

 

 

- docker/getting-started 실행 예시

docker run -d -p 80:80 docker/getting-started
// docker run 도커 실행
// -d 백그라운드 실행
// -p 호스트 포트와 컨테이너 포트를 연결
// 80:80 호스트포트:컨테이너포트
// 실행할 이미지명

 

 

 

 

- MySQL 실행 예시

docker run -d -p 3306:3306 -e MYSQL_ALLOW_EMPTY_PASSWORD=true --name mysql mysql:8.0

- 실행할 이미지가 없는 경우 이미지가 다운로드(pull) 됨

 

- Redis 실행 예시

더보기

telnet 설치와 telnet으로 redis 확인

 

 

 

 

 

2) ps: 컨테이너 목록 확인

docker ps [OPTIONS]

- CONTAINER ID: 컨테이너 고유 ID

- IMAGE: 이미지 이름

- COMMAND: 컨테이너에서 실행한 command

- CREATED: 생성된 기간? 정도?

- STATUS: 실행 시간

- PORTS: 포트를 publish(-p옵션)하는 경우 어떻게 되어 있는지

- NAMES: 컨테이너 이름( 따로 지정하지 않으면 과학자? 이름으로 랜덤 조합해서 들어감)

 

ps -a 옵션:  Exited(종료된 컨테이너)를 추가로 확인할 수 있음

 

// ps 명령, -a 옵션
docker ps -a

- 컨테이너는 종료되어도 삭제되지 않고 존재하고 재 시작 가능, 컨테이너 읽기/쓰기 레이어가 존재함

 

 

3) stop: 컨테이너 중지

 

docker stop [OPTIONS] CONTAINER ID [CONTAINER...]

- 컨테이너 아이디는 전부 입력하지 않아도 됨, 겹치는 부분이 없다면 1-2자만 입력 가능

- OPTIONS는 컨테이너를 하나 또는 여러개(띄어쓰기 구분)으로 중지 가능

- SIGTERM 신호를 보냄

 

3-1) kill: 컨테이너 중지

docker kill {container_id|container_name}

- SIGKILL 신호를 보냄

 

4) rm: 컨테이너 제거

docker rm [OPTIONS] CONTAINER [CONTAINER...]

// 중지된 컨테이너 일괄 제거
docker rm -v $(docker ps -a -q -f status=exited)

- OPTIONS는 컨테이너를 하나 또는 여러개(띄어쓰기 구분)으로 제거 가능

 

5) logs: 컨테이너 로그 보기

 

docker logs [OPTIONS] CONTAINER

 

logs --tail 숫자: 로그의 마지막 부분을 지정한 라인 수 만큼 보기

 

// 마지막 줄 5줄만 보기
docker logs --tail 5 CONTAINER ID

 

logs -f: 실시간 로그 확인

docker logs -f CONTAINER ID

- 로그 보기 중지: ctrl + c

 

 

6) exec: 컨테이너 실행

 

docker exec [OPTIONS] CONTAINER ID COMMAND [ARG...]

- it 옵션: 키보드 입력을 위해 추가

 

 

exec 컨테이너명 ls: 컨테이너 내부에 있는 파일 목록과 구조 확인

 

docker exec CONTAINER ID ls

 

exec 컨테이너명 sh: 컨테이너 내부에서 쉘 스크립트 실행, ls옵션으로 내부 리스트도 볼 수 있음

-t 옵션(-tty) : 터미널환경을 만들어서 쉘스크립트를 사용할 수 있는 환경을 만들기 위한 옵션

-i 옵션(interactive) 쉘스크립트 Input 받기위해 사용, terminal 로컬호스트에서 입력한것을 컨테이너로도 사용

 

 

7) cat: 파일을 화면으로 보기

- exit: 쉘 나가기

 

 

8) images: 이미지 목록 확인하기

 

docker images [OPTIONS] [REPOSITORY[:TAG]]

 

 

9) pull: 이미지 다운로드

 

docker pull [OPTIONS] NAME[:TAG|@DIGEST]

 

 

10) rmi: 이미지 삭제

 

docker rmi [OPTIONS] IMAGE [IMAGE...]

- 도커 컨테이너 업데이트: 새 버전의 이미지를 pull 받고 기존 컨테이너를 삭제한 후 새 이미지를 기반으로 run하면 됨

❗️주의: 컨테이너를 삭제하는 것은 컨테이너에서 생성된 파일도 함께 삭제됨, 외부 스토리지에 저장 필요(AWS S3과 같은 클라우드 서비스 또는 데이터 볼륨을 컨테이너에 추가해서 사용)

 

 

11) 네트워크 조회

 

docker network ls

- 따로 연결 네트워크를 명시하지 않은 컨테이너는 default bridge에 연결

 

 

현재 실행중인 컨테이너가 존재하면 아래 명령어로 확인할 수 있음

 

docker network inspect bridge

 

12) restart: 되살리기

docker restart {container_id|container_name}

 

5. Docker Compose

복잡한 설정을 쉽게 관리하기 위해서 YAML 방식의 설정 파일을 이용한 툴, Docker for Mac을 설치하면 자동으로 설치됨

 

version: "3" // docker compose의 파일 포맷 버전

// 서비스 부분은 1개 또는 여러 개의 docker container 설정
service:
  db:
    image: mysql:5.7 // 이미지는 docker container의 이름 정의
    restart: always // dcoker container 다운 시 항상 재시작 설정
    volumes: // 도커 run 명령 -v 옵션과 같은 역할로 디렉토리 마운트 경로 지정, 여러개 지정 가능(리스트로 작성) 
      - ./mysqldata:/var/lib/mysql
    environment: // dockerfile의 ENV 옵션 역할
      - MYSQL_ROOT_PASSWORD=dgkcoding
      - MYSQL_DATABASE=dgkdb
    ports: // 도커 run 명령 -p 옵션의 역할
      - "3306:3306"
    networks: // 도커 컨테이너 간 네트워크 관리(옵션 설정)