갈루아의 반서재

728x90

 

Step 1 — Installing Docker

최신 버전의 도커 설치를 위해 우분투 저장소가 아닌 공식 도커 저장소를 통해 설치하도록 한다. 새로운 패키지 소스를 추가한 뒤, 다운로드가 유효한지 확인하기 위해 도커로부터 GPG 키를 추가한 후 해당 패키지를 설치하게 된다. 먼저 현재 패키지 리스트부터 업데이트하도록 하자.

Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.4.0-1030-gcp x86_64)
deepedx@deepedx:~$ sudo apt-get update

apt가 HTTPS를 통해 패키지를 사용할 수 있도록 몇 가지 패키지를 설치한다.

deepedx@deepedx:~$ sudo apt install apt-transport-https ca-certificates curl software-properties-common

공식 도커 저장소용 GPG 키를 시스템에 추가한다.

deepedx@deepedx:~$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
OK

APT 소스에 도커 저장소를 추가한다.

deepedx@deepedx:~$ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"

패키지 데이터베이스를 업데이트한다. 

deepedx@deepedx:~$ sudo apt update

기본 우분투 저장소가 아닌 도커 저장소를 통해 설치할 수 있도록 하자. 아래 결과를 보면 docker-ce 가 설치되어 있지 않음을 알 수 있다.

deepedx@deepedx:~$ apt-cache policy docker-ce
docker-ce:
  Installed: (none)
  Candidate: 5:19.03.14~3-0~ubuntu-focal
  Version table:
     5:19.03.14~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:19.03.13~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:19.03.12~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:19.03.11~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:19.03.10~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
     5:19.03.9~3-0~ubuntu-focal 500
        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages
deepedx@deepedx:~$

docker-ce 부터 설치하자.

deepedx@deepedx:~$ sudo apt install docker-ce

도커 설치가 되었고, 데몬이 구동을 하게 된다. 상태를 체크해보자. 서비스가 가동중임을 알 수 있다.

deepedx@deepedx:~$ sudo systemctl status docker
● docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2020-12-05 09:49:28 UTC; 28s ago
TriggeredBy: ● docker.socket
       Docs: https://docs.docker.com
   Main PID: 4915 (dockerd)
      Tasks: 12
     Memory: 38.8M
     CGroup: /system.slice/docker.service
             └─4915 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.551568519Z" level=warning msg="Your kernel does not support cgroup rt runtime"
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.551574961Z" level=warning msg="Your kernel does not support cgroup blkio weight"
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.551580433Z" level=warning msg="Your kernel does not support cgroup blkio weight_device"
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.551802194Z" level=info msg="Loading containers: start."
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.639190641Z" level=info msg="Default bridge (docker0) is assigned with an IP address 172.17.0.0/16. Daemon option --bip can be used to set a preferred IP address"
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.676858941Z" level=info msg="Loading containers: done."
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.687622596Z" level=info msg="Docker daemon" commit=5eb3275d40 graphdriver(s)=overlay2 version=19.03.14
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.687714137Z" level=info msg="Daemon has completed initialization"
Dec 05 09:49:28 deepedx dockerd[4915]: time="2020-12-05T09:49:28.705146472Z" level=info msg="API listen on /run/docker.sock"
Dec 05 09:49:28 deepedx systemd[1]: Started Docker Application Container Engine.

 

Step 2 — Executing the Docker Command Without Sudo (Optional)

기본적으로 도커 명령어는 root 사용자 또는 도커 설치과정에서 자동적으로 설치되는 docker 그룹내 사용자만 실행할 수 있다. sudo 를 사용하지 않고, 또는 docker 그룹에 속해있지 않는 경우에도 도커 명령어를 쓸려고 하면 다음과 같은 결과를 보게 될 것이다.

Output
docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
See 'docker run --help'.

도커 명령어를 실행할 때마다, sudo 타이핑을 하고 싶지 않은 경우 사용자 이름을 다음과 같이 docker 그룹에 추가한다. 

deepedx@deepedx:~$ sudo usermod -aG docker ${USER}

그리고 새로운 멤버쉽 적용을 위해 로그아웃 후 다시 로그인하거나 아니면 다음과 같이 입력한다. 해당 사용자의 암호를 입력하고 계속 진행한다.

deepedx@deepedx:~$ sudo su - ${USER}

이렇게 추가한 사용자가 제대로 docker 그룹에 들어갔는지 확인해보자.

deepedx@deepedx:~$ id -nG
deepedx adm dialout cdrom floppy audio dip video plugdev netdev lxd docker ubuntu google-sudoers

 

Step 3 — Using the Docker Command

docker 명령어 구문 형식은 다음과 같다.

docker [option] [command] [arguments]

특정 명령어에 사용가능한 옵션은 다음과 같이 살펴볼 수 있다.

deepedx@deepedx:~$ docker docker-subcommand --help

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/home/deepedx/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/home/deepedx/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/home/deepedx/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/home/deepedx/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  engine      Manage the docker engine
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.
deepedx@deepedx:~$

Docker 시스템 전반에 대한 정보는 다음과 같이 확인가능하다.

deepedx@deepedx:~$ docker info
Client:
 Debug Mode: false

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 0
 Server Version: 19.03.14
 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: ea765aba0d05254012b0b9e595e995c09186427f
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  apparmor
  seccomp
   Profile: default
 Kernel Version: 5.4.0-1030-gcp
 Operating System: Ubuntu 20.04.1 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 15.64GiB
 Name: deepedx
 ID: 66SJ:KDZC:AZIV:MQM7:HB7A:ODUE:ABST:MH7C:ZRRZ:XUWF:S5QK:AJ2I
 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
deepedx@deepedx:~$

 

Step 4 — Working with Docker Images

도커 컨테이너는 도커 이미지로부터 만들어진다. 기본적으로 도커는 이러한 이미지들을 Docker Hub로부터 가져온다. 그리고 누구나 각자의 도커 이미지를 이 도커 허브에 올릴 수 있다. 도커 허브의 이미지에 접근해서 다운로드 가능한지 확인하기 위해 다음과 같이 입력해보자.  

아래 결과를 보면 로컬에서는 hello-world 를 찾을 수가 없어, 기본 저장소인 도커 허브로부터 이미지를 다운로드 받게 된다. 일단 이미지 다운로드가 끝나면 도커는 해당 이미지로부터 컨테이너를 생성하게 되고, 이렇게 생성된 컨테이너 내의 어플리케이션이 작동해서 메시지를 보여주게 된다.  

deepedx@deepedx:~$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:e7c70bb24b462baa86c102610182e3efcb12a04854e8c582838d92970a09f323
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

deepedx@deepedx:~$

docker 명령어와 search 라는 서브명령어를 통해 다음과 같이 Ubuntu 이미지를 찾을 수 있다. 도커 허브를 크롤링하여 검색어의 문자열과 일치하는 모든 이미지의 리스트를 보여주게 된다. 다음과 같다. OFFICIAL 컬럼의 OK 라는 값을 통해서 해당 이미지가 프로젝트에 의해 공식 지원되는 이미지임을 확인할 수 있다. 

deepedx@deepedx:~$ docker search ubuntu
NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   11552               [OK]
dorowu/ubuntu-desktop-lxde-vnc                            Docker image to provide HTML5 VNC interface …   476                                     [OK]
rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   250                                     [OK]
consol/ubuntu-xfce-vnc                                    Ubuntu container with "headless" VNC session…   228                                     [OK]
ubuntu-upstart                                            Upstart is an event-based replacement for th…   109                 [OK]
neurodebian                                               NeuroDebian provides neuroscience research s…   76                  [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5      ubuntu-16-nginx-php-phpmyadmin-mysql-5          50                                      [OK]
ubuntu-debootstrap                                        debootstrap --variant=minbase --components=m…   44                  [OK]
i386/ubuntu                                               Ubuntu is a Debian-based Linux operating sys…   24
solita/ubuntu-systemd                                     Ubuntu + systemd                                24                                      [OK]
nuagebec/ubuntu                                           Simple always updated Ubuntu docker images w…   24                                      [OK]
1and1internet/ubuntu-16-apache-php-5.6                    ubuntu-16-apache-php-5.6                        14                                      [OK]
1and1internet/ubuntu-16-apache-php-7.0                    ubuntu-16-apache-php-7.0                        13                                      [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mariadb-10   ubuntu-16-nginx-php-phpmyadmin-mariadb-10       11                                      [OK]
1and1internet/ubuntu-16-nginx-php-5.6-wordpress-4         ubuntu-16-nginx-php-5.6-wordpress-4             7                                       [OK]
1and1internet/ubuntu-16-apache-php-7.1                    ubuntu-16-apache-php-7.1                        6                                       [OK]
darksheer/ubuntu                                          Base Ubuntu Image -- Updated hourly             5                                       [OK]
1and1internet/ubuntu-16-nginx-php-7.0                     ubuntu-16-nginx-php-7.0                         4                                       [OK]
pivotaldata/ubuntu                                        A quick freshening-up of the base Ubuntu doc…   4
pivotaldata/ubuntu16.04-build                             Ubuntu 16.04 image for GPDB compilation         2
1and1internet/ubuntu-16-php-7.1                           ubuntu-16-php-7.1                               1                                       [OK]
pivotaldata/ubuntu-gpdb-dev                               Ubuntu images for GPDB development              1
1and1internet/ubuntu-16-sshd                              ubuntu-16-sshd                                  1                                       [OK]
smartentry/ubuntu                                         ubuntu with smartentry                          1                                       [OK]
pivotaldata/ubuntu16.04-test                              Ubuntu 16.04 image for GPDB testing             0
deepedx@deepedx:~$

다음과 같이 공식 ubuntu 이미지를 컴퓨터에 다운로드받을 수 있다. 

deepedx@deepedx:~$ docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
da7391352a9b: Pull complete
14428a6d4bcd: Pull complete
2c2d948710f2: Pull complete
Digest: sha256:c95a8e48bf88e9849f3e0f723d9f49fa12c5a00cfc6e60d2bc99d87555295e4c
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest
deepedx@deepedx:~$

이미지 다운로드가 되었는지 다음과 같이 확인할 수 있다.

deepedx@deepedx:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              f643c72bc252        9 days ago          72.9MB
hello-world         latest              bf756fb1ae65        11 months ago       13.3kB
deepedx@deepedx:~$

 

Step 5 — Running a Docker Container

컨테이너는 가상 머신에 가깝지만, 좀 더 자원친화적이다. 예를 들어, Ubuntu 최신 이미지를 사용하여 컨테이너를 실행한다고 하자. -i-t 스위치 결합을 통해 인터랙티브한 셀 접근이 가능하다. 이제 프로프트가 바뀌면서 여러분이 컨테이너 내부에서 작업중임을 알려주게 된다. 

deepedx@deepedx:~$ docker run -it ubuntu
root@5d93decd8389:/# apt update
Get:1 http://archive.ubuntu.com/ubuntu focal InRelease [265 kB]
Get:2 http://security.ubuntu.com/ubuntu focal-security InRelease [109 kB]
Get:3 http://security.ubuntu.com/ubuntu focal-security/universe amd64 Packages [643 kB]
Get:4 http://archive.ubuntu.com/ubuntu focal-updates InRelease [114 kB]
Get:5 http://archive.ubuntu.com/ubuntu focal-backports InRelease [101 kB]
Get:6 http://archive.ubuntu.com/ubuntu focal/restricted amd64 Packages [33.4 kB]
Get:7 http://archive.ubuntu.com/ubuntu focal/multiverse amd64 Packages [177 kB]
Get:8 http://archive.ubuntu.com/ubuntu focal/universe amd64 Packages [11.3 MB]
Get:9 http://security.ubuntu.com/ubuntu focal-security/multiverse amd64 Packages [1165 B]
Get:10 http://security.ubuntu.com/ubuntu focal-security/restricted amd64 Packages [103 kB]
Get:11 http://security.ubuntu.com/ubuntu focal-security/main amd64 Packages [489 kB]
Get:12 http://archive.ubuntu.com/ubuntu focal/main amd64 Packages [1275 kB]
Get:13 http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages [875 kB]
Get:14 http://archive.ubuntu.com/ubuntu focal-updates/restricted amd64 Packages [136 kB]
Get:15 http://archive.ubuntu.com/ubuntu focal-updates/universe amd64 Packages [874 kB]
Get:16 http://archive.ubuntu.com/ubuntu focal-updates/multiverse amd64 Packages [30.4 kB]
Get:17 http://archive.ubuntu.com/ubuntu focal-backports/universe amd64 Packages [4248 B]
Fetched 16.6 MB in 3s (6431 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
root@5d93decd8389:/#

컨테이너 내에 어플리케이션을 설치해보자. 아래와 같이 Node.js 를 설치하자.

root@5d93decd8389:/# apt install nodejs

설치가 끝나면 다음과 같이 설치된 Node.js 버전을 터미널 내에 표시해보자.

root@5d93decd8389:/# node -v
v10.19.0
root@5d93decd8389:/#

컨테이너 내의 모든 변화는 해당 컨테이너에만 영향을 미친다. 컨테이너를 빠져나오기 위해서는 exit 를 입력하면 된다. 

 

Step 6 — Managing Docker Containers

도커를 사용하다보면 여러분의 컴퓨터 내에는 다수의 구동중인 또는 그렇지 않은 컨테이너를 가지게 된다. 현재 호라동중인 컨테이너들은 다음과 같이 확인가능하다.

root@5d93decd8389:/# ^C
root@5d93decd8389:/# docker ps
bash: docker: command not found
root@5d93decd8389:/# exit
exit
deepedx@deepedx:~$ ^C
deepedx@deepedx:~$

결과는 다음과 같다.

deepedx@deepedx:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
deepedx@deepedx:~$

활성화여부를 떠나 전체 컨테이너를 볼려면 다음과 같이 docker ps 명령어에 -a 스위치를 붙인다. 

deepedx@deepedx:~$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
5d93decd8389        ubuntu              "/bin/bash"         2 minutes ago       Exited (127) 41 seconds ago                       nostalgic_banach
ad480fc16b5d        hello-world         "/hello"            4 minutes ago       Exited (0) 4 minutes ago                          vigilant_solomon
deepedx@deepedx:~$

가장 최근에 생성된 컨테이너는 -l 스위치를 붙여서 확인할 수 있다.

deepedx@deepedx:~$ docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
5d93decd8389        ubuntu              "/bin/bash"         3 minutes ago       Exited (127) 56 seconds ago                       nostalgic_banach
deepedx@deepedx:~$

컨테이너는 다음과 같이 컨테이너 ID 나 컨테이너 이름을 통해 시작할 수 있다. 컨테이너가 시작되면 docker ps 명령을 통해 해당 컨테이너의 상태를 확인할 수 있다. 

deepedx@deepedx:~$ docker start 5d93decd8389
5d93decd8389
deepedx@deepedx:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
5d93decd8389        ubuntu              "/bin/bash"         3 minutes ago       Up 7 seconds                            nostalgic_banach
deepedx@deepedx:~$

작동을 멈출려면 stop 명령어 뒤에 컨테이너 ID 나 이름을 붙이면 된다. 

deepedx@deepedx:~$ docker stop nostalgic_banach
nostalgic_banach
deepedx@deepedx:~$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
deepedx@deepedx:~$

더 이상 해당 컨테이너를 사용하지 않기로 했다면 다음과 같이 docker rm 명령어 뒤에 ID 또는 이름을 붙여 삭제할 수 있다.  

docker rm youthful_curie

 

www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04

728x90