본문 바로가기

DevOps/Docker

RedHat(Oracle) Linux 7.6에 Docker 설치 및 NGINX 실행

반응형

What's Container & Docker?

Docker Site에서는 Container와 Docker를 아래와 같이 정의하고 있다.

A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.

요약하면 SW를 구동시킬 때 필요한 Code와 연관된 Library를 하나의 Package로 구성해 실행하기 편하게 구성하는 것을 Container라 하고 Docker는 그 Container 기술을 가볍고, 독립적이게 실행 가능하게 구현했다고 할 수 있다.

설치 및 실행

Step 1. Yum Repository Update

 

Oracle Linux 7에서는 Docker 설치를 위한 Yum repository가 활성화 되지 않아서, Yum Repository 설정을 Update 하는 작업을 아래와 같이 수행했다.

[root@localhost ~]# mv /etc/yum.repos.d/public-yum-ol7.repo /etc/yum.repos.d/public-yum-ol7.repo_org1
...
[root@localhost ~]# wget http://yum.oracle.com/public-yum-ol7.repo
...
[root@localhost ~]# vi /etc/yum.repos.d/public-yum-ol7.repo
...

[ol7_latest]
name=Oracle Linux $releasever Latest ($basearch)
baseurl=http://yum.oracle.com/repo/OracleLinux/OL7/latest/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
gpgcheck=1
enabled=1

[ol7_UEKR4]
name=Latest Unbreakable Enterprise Kernel Release 4 for Oracle Linux $releasever ($basearch)
baseurl=http://yum.oracle.com/repo/OracleLinux/OL7/UEKR4/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
gpgcheck=1
enabled=1

[ol7_addons]
name=Oracle Linux $releasever Add ons ($basearch)
baseurl=https://yum.oracle.com/repo/OracleLinux/OL7/addons/$basearch/
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-oracle
gpgcheck=1
enabled=1
...

 

Step 2. Docker 설치

 

Yum Repository를 추가한 후에 아래 Command를 실행시키면 Docker engine이 설치된다.

...
[root@localhost ~]# yum install -y docker-engine
...
Complete!

설치 과정을 자세히 보면 아래 '자세히'를 버튼을 Click하자. 의존 관계에 있는 7개의 Package가 같이 설치되고 있고 여기에는 Docker Engine의 기반이 되는 container 관련 Package 2개와 shell에서의 제어를 위한 CLI(Command Line Interface)가 포함되어 있다.

자세히
...
[root@localhost ~]# yum install docker-engine
Loaded plugins: langpacks, ulninfo
ol7_UEKR5                                                | 2.5 kB     00:00     
ol7_addons                                               | 2.5 kB     00:00     
ol7_latest                                               | 2.7 kB     00:00     
(1/2): ol7_addons/x86_64/updateinfo                        |  62 kB   00:00     
(2/2): ol7_addons/x86_64/primary_db                        | 126 kB   00:00     
Resolving Dependencies
--> Running transaction check
---> Package docker-engine.x86_64 0:18.09.1.ol-1.0.8.el7 will be installed
--> Processing Dependency: runc < 1.0.0-20 for package: docker-engine-18.09.1.ol-1.0.8.el7.x86_64
--> Processing Dependency: container-selinux >= 2:2.77 for package: docker-engine-18.09.1.ol-1.0.8.el7.x86_64
--> Processing Dependency: containerd for package: docker-engine-18.09.1.ol-1.0.8.el7.x86_64
--> Processing Dependency: docker-cli for package: docker-engine-18.09.1.ol-1.0.8.el7.x86_64
--> Running transaction check
---> Package container-selinux.noarch 2:2.77-5.el7 will be installed
---> Package containerd.x86_64 0:1.2.0-1.0.5.el7 will be installed
---> Package docker-cli.x86_64 0:18.09.1.ol-1.0.8.el7 will be installed
---> Package runc.x86_64 0:1.0.0-19.rc5.git4bb1fe4.0.4.el7 will be installed
--> Processing Dependency: criu for package: runc-1.0.0-19.rc5.git4bb1fe4.0.4.el7.x86_64
--> Running transaction check
---> Package criu.x86_64 0:3.9-5.el7 will be installed
--> Processing Dependency: libprotobuf-c.so.1(LIBPROTOBUF_C_1.0.0)(64bit) for package: criu-3.9-5.el7.x86_64
--> Processing Dependency: libprotobuf-c.so.1()(64bit) for package: criu-3.9-5.el7.x86_64
--> Processing Dependency: libnet.so.1()(64bit) for package: criu-3.9-5.el7.x86_64
--> Running transaction check
---> Package libnet.x86_64 0:1.1.6-7.el7 will be installed
---> Package protobuf-c.x86_64 0:1.0.2-3.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package            Arch    Version                           Repository   Size
================================================================================
Installing:
 docker-engine      x86_64  18.09.1.ol-1.0.8.el7              ol7_addons   19 M
Installing for dependencies:
 container-selinux  noarch  2:2.77-5.el7                      ol7_addons   37 k
 containerd         x86_64  1.2.0-1.0.5.el7                   ol7_addons   21 M
 criu               x86_64  3.9-5.el7                         ol7_latest  432 k
 docker-cli         x86_64  18.09.1.ol-1.0.8.el7              ol7_addons   14 M
 libnet             x86_64  1.1.6-7.el7                       ol7_latest   57 k
 protobuf-c         x86_64  1.0.2-3.el7                       ol7_latest   27 k
 runc               x86_64  1.0.0-19.rc5.git4bb1fe4.0.4.el7   ol7_addons  1.9 M

Transaction Summary
================================================================================
Install  1 Package (+7 Dependent packages)

Total download size: 57 M
Installed size: 248 M
Is this ok [y/d/N]: y
Downloading packages:
(1/8): container-selinux-2.77-5.el7.noarch.rpm             |  37 kB   00:00     
(2/8): criu-3.9-5.el7.x86_64.rpm                           | 432 kB   00:00     
(3/8): docker-cli-18.09.1.ol-1.0.8.el7.x86_64.rpm          |  14 MB   00:02     
(4/8): protobuf-c-1.0.2-3.el7.x86_64.rpm                   |  27 kB   00:00     
(5/8): libnet-1.1.6-7.el7.x86_64.rpm                       |  57 kB   00:01     
(6/8): containerd-1.2.0-1.0.5.el7.x86_64.rpm               |  21 MB   00:04     
(7/8): runc-1.0.0-19.rc5.git4bb1fe4.0.4.el7.x86_64.rpm     | 1.9 MB   00:00     
(8/8): docker-engine-18.09.1.ol-1.0.8.el7.x86_64.rpm       |  19 MB   00:03     
--------------------------------------------------------------------------------
Total                                              8.1 MB/s |  57 MB  00:07     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : 2:container-selinux-2.77-5.el7.noarch                        1/8 
  Installing : containerd-1.2.0-1.0.5.el7.x86_64                            2/8 
  Installing : libnet-1.1.6-7.el7.x86_64                                    3/8 
  Installing : docker-cli-18.09.1.ol-1.0.8.el7.x86_64                       4/8 
  Installing : protobuf-c-1.0.2-3.el7.x86_64                                5/8 
  Installing : criu-3.9-5.el7.x86_64                                        6/8 
  Installing : runc-1.0.0-19.rc5.git4bb1fe4.0.4.el7.x86_64                  7/8 
  Installing : docker-engine-18.09.1.ol-1.0.8.el7.x86_64                    8/8 
xfs_info: /var/lib is not a mounted XFS filesystem
  Verifying  : protobuf-c-1.0.2-3.el7.x86_64                                1/8 
  Verifying  : runc-1.0.0-19.rc5.git4bb1fe4.0.4.el7.x86_64                  2/8 
  Verifying  : 2:container-selinux-2.77-5.el7.noarch                        3/8 
  Verifying  : criu-3.9-5.el7.x86_64                                        4/8 
  Verifying  : docker-engine-18.09.1.ol-1.0.8.el7.x86_64                    5/8 
  Verifying  : docker-cli-18.09.1.ol-1.0.8.el7.x86_64                       6/8 
  Verifying  : libnet-1.1.6-7.el7.x86_64                                    7/8 
  Verifying  : containerd-1.2.0-1.0.5.el7.x86_64                            8/8 

Installed:
  docker-engine.x86_64 0:18.09.1.ol-1.0.8.el7                                   

Dependency Installed:
  container-selinux.noarch 2:2.77-5.el7                                         
  containerd.x86_64 0:1.2.0-1.0.5.el7                                           
  criu.x86_64 0:3.9-5.el7                                                       
  docker-cli.x86_64 0:18.09.1.ol-1.0.8.el7                                      
  libnet.x86_64 0:1.1.6-7.el7                                                   
  protobuf-c.x86_64 0:1.0.2-3.el7                                               
  runc.x86_64 0:1.0.0-19.rc5.git4bb1fe4.0.4.el7                                 

Complete!
[root@localhost ~]# 

...

 

Step 3. Docker Service 실행

 

'systemctl enable' command로 부팅시 docker engine의 자동 실행되게 한 후에, 'systemctl start'로 docker를 실행시켰다.

[root@localhost ~]# systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
[root@localhost ~]# systemctl start docker
...

 

Step 4. Docker Service 실행 상태 확인

 

docker가 잘 설치되었는 지 확인하기 위해 'docker -v'로 현재 설치된 docker의 버전을 확인했다.

[root@localhost ~]# docker -v
Docker version 18.09.1-ol, build e32a1bd

 

그리고 'systemctl status' command로 docker가 정상적으로 실행되고 있음을 확인했다.

[root@localhost ~]# systemctl status docker
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/docker.service.d
           └─docker-sysconfig.conf
   Active: active (running) since 화 2019-06-25 13:41:33 KST; 10s ago
     Docs: https://docs.docker.com
 Main PID: 5032 (dockerd)
    Tasks: 36
   Memory: 58.2M
   CGroup: /system.slice/docker.service
           ├─5032 /usr/bin/dockerd --selinux-enabled
           └─5057 containerd --config /var/run/docker/containerd/containerd.t...

 6월 25 13:41:31 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:31 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:31 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:32 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:32 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:32 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:32 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:32 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:33 localhost.localdomain dockerd[5032]: time="2019-06-25T13:41...
 6월 25 13:41:33 localhost.localdomain systemd[1]: Started Docker Applicatio...
Hint: Some lines were ellipsized, use -l to show in full.

 

Docker 실행 상태 

Docker Repository에서 Docker Image를 Download 하거나, Local에서 Build를 하면 Local Repository에 docker Image가 저장되게 된다. 이후 'docker run' command를 통해 docker image를 실행시키게 되면 container running상태가 되고 실행이 끝나거나, 'docker stop' command로 중지 시키면 container existed 상태가 된다. 그리고 exited 상태인 container들은 'docker rm' command로 제거할 수 있다.

<pic 1. 간단한 Docker State Diagram >

주요 명령어

아래는 docker를 주제로 내부 세미나 준비 과정에서 사용했던 Command들이다. 필자는 많이 사용했었는데, 사용자에 따로 다른 명령어를 사용할 수 있으니 참고만 하시면 된다.

docker pull [IMAGE NAME] 
docker images 

docker start [CONTAINER ID | CONTAINER NAME] 
docker stop [CONTAINER ID | CONTAINER NAME] 
docker container ls (또는 docker ps)
docker container ls -a (또는 docker ps -a)
docker rm [CONTAINER ID | CONTAINER NAME] 
docker rmi [IMAGE ID]

  • docker pull ; Docker Image를 Repository에서 가져온다. Default Repository는 DockerHub 이다.
  • docker images : 시스템에서 가지고 있는 Docker Image List를 조회한다.
  • docker run [IMAGE NAME] : Docker Image를 실행시킨다. 여기에 연관된 Command는 뒤에 다시 정리하겠다.  한 번 실행한 후 Stop 상태에 있는 Container와 동일한 이름으로 run을 실행할 수 없다.
  • docker start [CONTAINER ID | CONTAINER NAME] : 이미 실행되고 끝난 container를 다시 실행시킨다.
  • docker stop [CONTAINER ID | CONTAINER NAME] : 현재 실행되는 container를 종료시킨다.
  • docker container ls : Image를 실행한 상태를 Container라 하는데 docker container는 container management command이고, 여기에 ls command를 추가하면 현재 실행되는 Container List를 조회한다. ('docker ps' command도 동일한 결과를 보여준다.)
  • docker container ls -a : 현재 실행되는 Container외에 Stop 상태인 Container도 함께 조회한다. ('docker ps -a' command도 동일한 결과를 보여준다.)
  • docker rm [CONTAINER ID | CONTAINER NAME] : Stop 상태의 Container를 제거한다.
  • docker rmi [IMAGE ID] : Local Repository에 등록되어 있는 docker image를 삭제한다.

아래 '자세히' 버튼을 누르면 전체 Option및 Command를 확인할 수 있다.

자세히
[root@localhost ~]# docker --help

Usage:	docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -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 "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.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
  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.

Demo : Docker Image로 NGINX 실행

NGINX는 Apache HTTPd와 함께 가장 많이 사용되는 Open Source 웹서버 프로그램이다. 아래는 NGINX를 docker image로 실행하는 Demo이다.

 

Step 1 : NGINX docker image download

 

'docker pull' command를 통해 nginx docker image를 Repository에서 가져온다. 별다른 설정 없이 image를 가져오게 되면, marking한 것과 같이 Repository url이 'docker.io'로 시작하고 있다. 기본 Repository가 dockerhub 라는 의미이다. Image 뒤에 별다른 Tag를 명시하지 않으면 기본적으로 'latest' tag가 첨부되서 최신 버전의 Image를 가져오게 된다. Download 종료 후 'docker images' commad를 실행하면 download된 image를 확인한다.

[root@localhost ~]# docker pull nginx
Using default tag: latest
Trying to pull repository docker.io/library/nginx ... 
latest: Pulling from docker.io/library/nginx
123275d6e508: Pull complete 
9a5d769f04f8: Pull complete 
faad4f49180d: Pull complete 
Digest: sha256:4d947aef8841aed19cc0896a38e12d49d50feba7f583998a164ffeb31e655919
Status: Downloaded newer image for nginx:latest

[root@localhost ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              5a8dfb2ca731        23 hours ago        127MB

 

Step 2 : NGINX docker image 실행

 

'docker run' command의 사용방법은 아래와 같다.

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

제일 많이 사용했던 OPTION들을 아래에 정리했다. (COMMAND와 ARG는 실행하는 image에 적용되는 사항이다.)

 

  • - v [docker volumn | Host HW Directory]:[docker 내부 path] : docker image가 실행될 때 container 내부의 특정 path를 사용하는 경우, 그 path를 docker volumn이나 Host Machine 디렉토리와 mount.
  • --name [string] : docker image가 실행될 때 Container의 Name 설정
  • -p [Host HW port:docker container port] : docker image가 실행될 때 container에서 사용하는 Network Port를 Host HW의 Network port로 Port mapping.
  • -d : 실행되는 container가 Background에서 실행
  • --rm : container가 stop될 때 자동으로 container를 제거

좀 더 자세한 사항은 아래 '자세히' 버튼을 클릭하면 확인할 수 있다.

자세히
[root@localhost ~]# docker run --help

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

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -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
      --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
      --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
      --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 string                 Connect a container to a network (default "default")
      --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)
      --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
      --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 a container (default "SIGTERM")
      --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

 

아래는 nginx의 docker image를 Background에서 'browndwarf_web_server'라는 이름으로 80 port를 mapping해서 실행하는 예이다. NGINX service를 구동하는 것과 동일한 결과를 가진다고 생각하면 된다.

[root@localhost ~]# docker run --name browndwarf_web_server -d -p 80:80 nginx:latest 
a1615258cbda1609ee90d4f5099fd5c11b26875df99ca9f47186498bbce970ce

 

Step 3 : NGINX docker image 결과

 

Browser에서 localhost를 호출하면 <pic 2>와 같이 NGINX의 기본 화면을 확인할 수 있다.

 

<pic 2> 실행된 NGINX 

또, 위에서 정리했던 'docker container ls' 또는 'docker ps' command를 통해 실행되고 있는 Container 확인할 수 있다. STATUS Column에서 'Up...'이라고 명시되어 있으면 시작된 상태이고, 'Exited..."라고 명시되어 있으면 종료된 상태의 Container이다. 그리고 PORTS column을 통해 docker 내부에서 사용하는 80 port가 Host Machine의 80 port와 mapping이 되어 있는 것을 알 수 있고, NAMES column을 보면 'docker run'시 부여했던 Container name이 적용된 것을 알 수 있다.

[root@localhost ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
a1615258cbda        nginx:latest        "nginx -g 'daemon of…"   4 minutes ago       Up 4 minutes        0.0.0.0:80->80/tcp   browndwarf_web_server
[root@localhost ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                NAMES
a1615258cbda        nginx:latest        "nginx -g 'daemon of…"   5 minutes ago       Up 5 minutes        0.0.0.0:80->80/tcp   browndwarf_web_server

 

참고로 /var/lib/docker/containers Path를 조회하면 현재 실행되는 container의 존재를 확인할 수 있다. Directory 이름 앞 글자가 CONTAINER ID와 동일하게 시작된다는 점을 참고하자.

[root@localhost ~]# ll /var/lib/docker/containers
total 4
drwx------. 4 root root 4096 Apr 17 18:35 a1615258cbda1609ee90d4f5099fd5c11b26875df99ca9f47186498bbce970ce

 

Step 4 : 실행한 Container 정리

 

'docker stop' command로 실행하는 Container를 정지시키면 'docker container ls'나 'docker ps'로 확인할 수 없게 된다. 'docker ps -a' 또는 'docker container ls -a'를 통해야만 실행 종료된 Container들을 확인할 수 있다. 이들은 'docker start'로 다시 시작할 수도 있고, 아예 제거할 수도 있다. Container를 제거할 때에는 'docker rm' command를 통해 제거해야 하는데, 'docker run' 실행 시에 '--rm' option을 사용하면 Container가 종료될 때 자동으로 제거된다.

# 실행되는 Container를 정지
[root@localhost ~]# docker stop browndwarf_web_server 
browndwarf_web_server
...
# 실행되는 Container List 조회
[root@localhost ~]# docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@localhost ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
...
# 전체 Container List 조회
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
a1615258cbda        nginx:latest        "nginx -g 'daemon of…"   6 minutes ago       Exited (0) 12 seconds ago                       browndwarf_web_server
...
# 정지되어 있는 Container 'browndwarf_web_server' 제거
[root@localhost ~]# docker rm browndwarf_web_server 
browndwarf_web_server
...
# 전체 Container List 조회
[root@localhost ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

Reference

Install Docker on Oracle Linux 7

A Simple Guide to docker installation on Oracle Limux 7.5