Podman is a utility provided as part of the libpod library. It can be used to create and maintain containers. The following tutorial will teach you how to set up Podman and perform some basic commands.
The code samples are intended to be run as a non-root user, and use sudo where root escalation is required.
Getting help
To get some help and find out how Podman is working, you can use the help:
$ podman --help
$ podman <subcommand> --help
For more details, you can review the manpages:
$ man podman
$ man podman-<subcommand>
Please also reference the Podman Troubleshooting Guide to find known issues and tips on how to solve common configuration mistakes.
Searching, pulling & listing images
Podman can search for images on remote registries with some simple keywords.
$ podman search <search_term>
You can also enhance your search with filters:
$ podman search httpd --filter=is-official
Downloading (Pulling) an image is easy, too.
$ podman pull docker.io/library/httpd
After pulling some images, you can list all images, present on your machine.
$ podman images
Note: Podman searches in different registries. Therefore it is recommend to use the full image name (docker.io/library/httpd instead of httpd) to ensure, that you are using the correct image.
Running a container
This sample container will run a very basic httpd server that serves only its index page.
$ podman run -dt -p 8080:80/tcp docker.io/library/httpd
Note: Because the container is being run in detached mode, represented by the -d in the podman run command, Podman will print the container ID after it has executed the command. The -t also adds a pseudo-tty to run arbitrary commands in an interactive shell.
Note: We use port forwarding to be able to access the HTTP server. For successful running at least slirp4netns v0.3.0 is needed.
Listing running containers
The podman ps command is used to list created and running containers.
$ podman ps
Note: If you add -a to the podman ps command, Podman will show all containers (created, exited, running, etc.).
Testing the httpd container
As you are able to see, the container does not have an IP Address assigned. The container is reachable via it’s published port on your local machine.
$ curl http://localhost:8080
From another machine, you need to use the IP Address of the host, running the container.
You can “inspect” a running container for metadata and details about itself. podman inspect will provide lots of useful information like environment variables, network settings or allocated resources.
Since, the container is running in rootless mode, no IP Address is assigned to the container.
You can check the status of one or more containers using the podman ps command. In this case, you should use the -a argument to list all containers.
$ podman ps -a
Removing the container
Finally, you can remove the container:
$ podman rm -l
You can verify the deletion of the container by running podman ps -a.
Network
For a more detailed guide about Networking and DNS in containers, please see the network guide.
Checkpoint, Migration and Restoring containers
Checkpointing a container stops the container while writing the state of all processes in the container to disk. With this, a container can later be migrated and restored, running at exactly the same point in time as the checkpoint. For more details, see the checkpoint instructions.
Integration Tests
For more information on how to setup and run the integration tests in your environment, checkout the Integration Tests README.md.
More information
For more information on Podman and its subcommands, checkout the asciiart demos on the README.md page.
Docker 엔진을 실행하지 않았을 경우, docker 명령어를 수행하면 docker 명령어를 찾을 수 없다는 메시지가 출력된다.
$ docker --help
The command 'docker' could not be found in this WSL 2 distro.
We recommend to activate the WSL integration in Docker Desktop settings.
Window에 설치된 Docker Desktop 을 실행하면 Docker Enging이 실행되고 도커 데몬과 통신 할 수 있게 되어 docker 명령어가 정상적으로 수행된다.
즉, 도커 엔진이 실행되지 않을 경우 도커 엔진에서 관리하는 이미지나 컨테이너는 사용할 수 없게된다.
반면, podman은 엔진을 가지지 않으므로 별도의 엔진(데몬) 기동없이도 이미지나 컨테이너를 사용할 수 있다.
가상머신과 컨테이너
요즘 기술 트렌드를 보면 가상화 기술에서 컨테이너 기술로 사람들의 관심이 많이 넘어가고 있는 추세입니다. 왜 이렇게 컨테이너 기술에 사람들은 열광을 하는걸까요? 기술은 계속 진화하여 메인프레임 시대에서 클라우드 컴퓨팅 시대로 넘어 왔습니다. 수개월이 걸리던 시스템 구성을 단 몇 분안이면 끝낼 수 있는 환경이 되었습니다. 어플리케이션 또한, 동일 서버에서 모든 프로세스가 실행되던 방식에서 여러 분산된 환경에서 프로세스가 독립적으로 실행이 되도록 변경되었습니다. 이는 무엇을 의미할까요? 이제 누가 더 빨리 비즈니스 어플리케이션을 시장에 출시하느냐가 중요한 핵심 포인트가 되었다는 뜻일 것입니다.
따라서 이제는 가상화를 모르면 시스템을 운영하기조차 힘든 상황이 되어 버렸습니다. 이런 상황에서 기존에 사용하던 하이퍼바이저 위의 가상머신은 CPU, Memory, Network, Disk와 같은 물리자원을 가상화하여 사용함으로써 무거운데 반면, 운영체제 위의 컨테이너는 라이브러리 형식으로 가볍게 올라가 설치하고자 하는 어플리케이션만 실행하면 되기 때문에 매우 가볍습니다.
레드햇의 새로운 컨테이너 기술 Podman
아마도 컨테이너 하면 떠오르는 단어는 Docker일 것입니다. 그리고, Docker엔진을 통해 올라 가는 컨테이너를 관리하기 위한 가장 대표적인 관리 소프트웨어가 바로 Kubernetes일 것입니다. 그런데, 2017년에 Docker가 엔터프라이즈 버전을 상용화하면서 레드햇은 또다른 컨테이너 오픈소스 기술인 Podman을 사용하여 레드햇의 엔터프라이즈 제품들을 출시하였습니다.
가장 먼저 2019년 3월에 릴리즈한 Red Hat Enterprise Linux 8에 Podman이 추가되었습니다. 그리고, 뒤이어 릴리즈 된 Red Hat OpenShift Container Platform 4와 Red Hat OpenStack Platform 16 모두 Docker에서 Podman으로 변경되었습니다.
컨테이너 기술 Docker와 Podman
Docker와 Podman은 매우 유사한것 같지만, Docker와 Podman은 엄연히 크게 다른 부분이 존재합니다. 그럼 Docker와 Podman은 어떤 부분이 같고, 어떤 부분이 다른 걸까요? 지금부터 Docker와 Podman의 기술을 알아보겠습니다.
Docker는 애플리케이션을 빌드하고 컨테이너화하기 위한 Docker Engine, 컨테이너 이미지를 배포하고 제공하기 위한 Docker Registry, 여러개의 컨테이너 애플리케이션을 정의하고 실행하기 위한 Docker Compose, 사용자의 로컬 컴퓨터나 클라우드 인스턴스에 도커 호스트를 구성해주는 Docker Machine, 컨테이너 클러스터링 및 스케줄링을 위한 Docker Swarm으로 구성됩니다. Podman은 Docker의 핵심 기능인 Docker Engine 기능과 유사하다고 볼 수 있습니다.
Docker Engine에는 컨테이너 이미지를 관리하고, 컨테이너 이미지를 이용해 컨테이너를 실행하기 위한 Docker daemon이 있습니다. 그리고, 이미지와 컨테이너를 사용자가 관리하고 사용할 수 있도록 커맨드 기반으로 된 Docker Client가 있습니다. Podman 역시 컨테이너를 실행하기 위한 컨테이너 이미지, 그리고, 이미지를 통해 실행된 컨테이너와 이를 사용하기 위한 커맨드 기반의 유틸리티가 있습니다.
Docker는 컨테이너 레지스트리로부터 이미지를 받아와 Docker 내부의 이미지 저장소에 저장을 합니다. 그리고, 이미지 저장소에 저장된 이미지를 이용하여 컨테이너를 실행할 수 있으며, 실행 중인 컨테이너를 이미지로 빌드할 수도 있습니다. Docker는 이런 다양한 작업들을 Docker daemon을 통해 수행합니다. 그렇기 때문에 데몬에 문제가 발생했을 경우 모든 컨테이너와 이미지에 영향이 가며, 커맨드 명령어로 컨테이너를 제어할 때도 영향을 미칩니다.
반면에 Podman은 daemon 없이 커맨드로 컨테이너 레지스트리로부터 이미지를 받아와 Podman 호스트의 로컬 이미지 저장소에 이미지를 저장하고, 해당 이미지를 이용하여 컨테이너를 실행합니다. 이때 podman 라이브러리를 통해 바로 컨테이너를 실행하기 때문에 컨테이너 간에 서로 영향을 주지 않으며, 컨테이너와 이미지 사이, 커맨드 명령어로 컨테이너를 제어하거나 이미지를 관리할 때도 서로 영향을 주지 않습니다.
내가 경험한 컨테이너 이야기
이는 Docker 기반이였던 Red Hat OpenStack Platfom 13을 사용했을때와 현재 Red Hat OpenStack Platform 16에서 확실하게 경험할 수 있었습니다. 사실 Red Hat OpenStack은 11버전 (Ocata)부터 오픈스택의 모든 서비스들을 컨테이너화하기 위한 준비를 하고 있었습니다. 그리고, 13버전 (Queens)에서 Docker기반으로 오버클라우드의 오픈스택 서비스들이 모두 컨테이너 화가 되었습니다. 이 당시 모 프로젝트에서 OpenStack 13버전을 구축하게 되었는데, 그 당시 구축했던 버전의 Https Health-Check에서 메모리 누수 현상이 발생을 했었습니다. 메모리를 사용하면 메모리를 다시 반환해야 하는데, 반환하지 않아 사용 가능한 메모리가 줄어드는 현상이였습니다. 이런 경우 Docker 엔진이 영향을 받고, Docker 엔진이 정상적으로 수행할 수 없는 상태가 되면, 그 위에 올라가 있는 모든 컨테이너가 정상 동작을 하지 않습니다. 이렇게 되면 시스템 재부팅시 컨테이너를 모두 종료하고 시스템이 다운되는데, Docker 엔진이 정상적으로 종료되지 않기 때문에 컨테이너들을 제대로 종료할 수 없었습니다. 따라서, 강제 종료를 해야만 하는 상황이 발생을 합니다. 물론 이 문제는 그 다음 릴리즈에서 모두 해결되어 현재 설치하는 OpenStack 13 버전에서는 찾아볼 수 없는 현상이 되었습니다.
그런데, 이번에 릴리즈한 OpenStack 16(Train) 버전에서는 Docker 기반이 아닌 Podman으로 변경이 되었고, 설상가상으로 위와 같은 상황이 동일하게 발생한다고 하더라도, 특정 데몬 위에서 컨테이너가 실행되는 것이 아니므로 모든 컨테이너에 영향을 주지는 않을 것입니다. 문제가 발생한 특정 컨테이너만 트러블 슈팅을 하고 조치를 취하면 되기 때문입니다.
IT 업계 종사자라면 컨테이너(Container)에 대해 한 번쯤은 들어본 적이 있을 것입니다. 애플리케이션과 바이너리, 라이브러리 등을 패키지로 묶어 배포하는 컨테이너는 서로 다른 컴퓨팅 환경에서 애플리케이션을 안정적으로 실행할 수 있으며 개발 환경에 구애 받지 않고 빠른 개발과 배포가 가능하다는 장점이 있습니다. 대표적인 IT 기업 중 하나인 구글은 지메일에서 유튜브, 검색에 이르기까지 모든 제품을 컨테이너에서 실행하고 있기도 합니다. 이처럼 컨테이너 기술은 IT 개발과 운영에 있어서 빼놓을 수 없는 필수 요소로 자리잡았습니다.
컨테이너에 대한 관심이 급격히 증가하면서 대부분의 주요 IT 벤더와 클라우드 공급자들은 컨테이너 기반의 솔루션을 발표했고 관련 스타트업 또한 급증해 컨테이너의 생태계를 넓혀왔습니다. 하지만 포맷과 런타임에 대한 특정한 규격이 없다 보니 컨테이너의 미래는 불안했던 것이 사실입니다. 일례로 2013년 출시된 도커(Docker)가 사실상의 컨테이너 표준 역할을 했지만 코어OS(CoreOS)는 도커와는 다른 규격으로 표준화를 추진하려 했습니다. 이러한 문제를 해결하기 위해 2015년 6월 도커, 코어OS, AWS, 구글, 마이크로소프트, IBM 등 주요 플랫폼 벤더들은 애플리케이션의 이식성(Portability) 관점에서 컨테이너 포맷과 런타임에 대한 개방형 업계 표준을 만들기 위해 OCI(Open Container Initiative)를 구성하였습니다. 이후 컨테이너 시장은 OCI의 런타임 명세와 이미지 명세를 준수하는 방향으로 성장하였고 그 과정에서 2016년 12월 쿠버네티스(Kubernetes)의 컨테이너 런타임을 만들기 위한 CRI(Container Runtime Interface)가 등장했습니다.
2. 컨테이너 런타임
CRI의 등장 배경을 이해하려면 먼저 컨테이너 런타임에 대해 살펴봐야 합니다. 컨테이너를 실행하기 위해서는 다음과 같은 세 단계를 거칩니다.
[그림 1] 컨테이너 실행 단계
OCI가 만들어질 당시 비공식적 표준 역할을 하던 도커는 컨테이너 런타임의 표준화를 위해 필요한 모든 단계가 아닌 세 번째 단계인 컨테이너의 실행 부분만 표준화하였습니다. 이로 인해 컨테이너의 런타임은 실제 컨테이너를 실행하는 저수준 컨테이너 런타임인 OCI 런타임과 컨테이너 이미지의 전송 및 관리, 이미지 압축 풀기 등을 실행하는 고수준 컨테이너 런타임으로 나뉘게 되었습니다.
저수준 컨테이너 런타임(Low-Level Container Runtimes) 컨테이너는 Linux namespace와 cgroup을 사용하여 구현합니다. namespace는 각 컨테이너에 대해 파일 시스템이나 네트워킹과 같은 시스템 리소스를 가상화하고 cgroup은 각 컨테이너가 사용할 수 있는 CPU 및 메모리와 같은 리소스 양을 제한하는 역할을 합니다. 저수준 컨테이너 런타임은 이러한 namespace와 cgroup을 설정한 다음 해당 namespace 및 cgroup 내에서 명령을 실행합니다.
[그림 2] 도커와 runC
OCI를 준수하는 저수준 컨테이너 런타임으로 가장 잘 알려진 것은 runC입니다. runC는 원래 도커에서 컨테이너를 실행하기 위해 개발되었으나, OCI 런타임 표준을 위해 독립적인 라이브러리로 사용되었습니다. 저수준 컨테이너 런타임은 컨테이너를 실제 실행하는 역할을 하지만 이미지로부터 컨테이너를 실행하려면 이미지와 관련된 API 같은 기능이 필요합니다. 이러한 기능은 고수준 컨테이너 런타임에서 제공됩니다.
고수준 컨테이너 런타임(High-Level Container Runtimes) 일반적으로 고수준 컨테이너 런타임은 원격 애플리케이션이 컨테이너를 논리적으로 실행하고 모니터링 하는데 사용할 수 있는 데몬 및 API를 제공합니다. 또한 컨테이너를 실행하기 위해 저수준 런타임 위에 배치됩니다.
이처럼 컨테이너를 실행하려면 저수준 및 고수준 컨테이너 런타임이 필요하기 때문에 OCI 런타임과 함께 도커가 그 역할을 했습니다. 도커는 docker-containerd라는 가장 잘 알려진 고수준 컨테이너 런타임을 제공합니다. containerd도 runC와 마찬가지로 도커에서 컨테이너를 실행하기 위해 개발되었으나 나중에 독립적인 라이브러리로 추출되었습니다.
[그림 3] 고수준·저수준 컨테이너 런타임 관계와 도커 아키텍처
CRI(Container Runtime Interface) CRI는 쿠버네티스에서 만든 컨테이너 런타임 인터페이스로 개발자들의 컨테이너 런타임 구축에 대한 진입 장벽을 낮추어 줍니다. 초기 쿠버네티스는 컨테이너를 실행하기 위해 도커를 사용하였는데 이는 쿠버네티스 클러스터 워커 노드의 에이전트인 Kubelet 소스코드 내부에 통합되어 있었습니다. 이처럼 통합된 프로세스는 Kubelet에 대한 깊은 이해를 필요로 하였고 쿠버네티스 커뮤니티에 상당한 유지보수 오버헤드를 발생시켰습니다. 이러한 문제를 해결하기 위해 쿠버네티스는 CRI를 만들어 명확하게 정의된 추상화 계층을 제공함으로써 개발자가 컨테이너 런타임 구축에 집중할 수 있게 하였습니다.
[그림 4] Kubelet 동작 흐름과 CRI
3. 컨테이너의 새로운 생태계
CRI가 만들어진 후 주요 플랫폼 벤더들은 본격적으로 컨테이너 런타임 구축을 위해 노력하였습니다. 그 중 레드햇, 인텔, SUSE, Hyper, IBM 등의 관리자와 컨트리뷰터들이 커뮤니티 중심의 오픈소스 프로젝트인 CRI-O를 개발하였습니다.
CRI-O(Container Runtime Interface - Open Container Initiative) CRI-O는 CRI와 OCI에서 유래된 프로젝트로 컨테이너 런타임 및 이미지가 OCI와 호환되는 것에 중점을 두고 있습니다. CRI 표준 컴포넌트를 최소한의 런타임으로 구현하며 쿠버네티스에서 모든 OCI 호환 런타임 및 컨테이너 이미지를 지원합니다.
[그림 5] 쿠버네티스와 도커 및 CRI-O
CRI-O는 컨테이너의 실행을 목적으로 경량화했기 때문에 도커가 제공하는 컨테이너 생성 및 이미지 빌드와 같은 기능은 제공하지 않습니다. 즉, CRI-O 덕분에 쿠버네티스는 컨테이너를 실행할 때 도커가 필요없었으나, 컨테이너의 생성 및 이미지 빌드와 같은 과정에서는 여전히 도커를 필요로 했습니다. 이러한 이유로 CRI-O 개발팀은 도커를 대체할 수 있는 새로운 생태계를 만들기 위해 노력하였습니다.
도커의 문제점 도커가 컨테이너의 생성 및 이미지 빌드를 모두 처리하는데 새로운 툴이 왜 필요할까요? 물론 기존 방식대로 도커를 사용할 수 있습니다. 그럼에도 CRI-O 개발팀이 도커의 역할을 대신할 수 있는 생태계를 위한 툴(Buildah 빌다, Podman 포드맨, Skopeo 스코피오)을 개발한 이유는 다음과 같은 문제점이 제기되었기 때문입니다.
도커는 클라이언트/서버 애플리케이션으로 클라이언트인 Docker CLI와 서버인 Docker daemon으로 구성됩니다. 그 중 서버는 컨테이너 이미지 빌드, 관리, 공유, 실행 및 컨테이너 인스턴스 관리와 같이 너무 많은 기능을 담당하는 데몬으로 모든 컨테이너를 자식 프로세스로 소유합니다. 이로 인해 무거울 뿐 아니라 장애가 발생하면 모든 자식 프로세스에 영향을 끼쳐 단일 실패점(Single point of failure)이 될 위험이 있습니다. 또한 클라이언트-서버 모델을 사용할 경우 리눅스의 audit.log를 통해 관리자가 시스템의 보안 이벤트를 감시하고 기록된 정보를 볼 수 있는 audit 보안 기능을 사용할 수 없게 됩니다.
그림 6은 fork·exec 모델 및 클라이언트-서버 모델에서의 UID, auid 설정 동작 방식이 있으며, 클라이언트 - 서버의 경우 컨테이너 이미지 빌드, 관리, 공유 같이 많은 기능이 이 있어 무겁고 장애 발생 시 모든 자식 프로세스에 영향을 미치게 된다는 것을 보여주는 그림[그림 6] fork·exec 모델 및 클라이언트-서버 모델에서의 UID, auid 설정 동작 방식
추가로 모든 도커 명령은 루트 권한을 가진 사용자에 의해서만 실행할 수 있어 보안 문제가 발생할 수 있습니다. 이는 아래에 소개하는 Buildah, Podman, Skopeo를 사용하면 해결할 수 있습니다.
CRI-O와 함께 사용 가능한 툴: Buildah, Podman, Skopeo Buildah, Podman, Skopeo는 별도의 데몬 없이 전통적인 fork·exec 모델을 사용하며 사용자 네임 스페이스를 이용해 컨테이너를 실행함으로써 단일실패점, audit 보안 기능 사용 및 루트 권한 문제를 해결하였습니다. 도커의 서버가 너무 많은 기능을 가지고 있는 단점은 각 툴 별로 다음과 같이 기능을 나누어 제공하는 방식으로 보완하였습니다.
[그림 7] 도커의 동작 흐름 및 Podman, Buidah, Skopeo의 역할
Buildah는 CRI-O에서 이미지를 빌드할 때 도커의 종속성을 제거하기 위해 개발되었고 Dockerfile 없이 다른 스크립트 언어를 사용해 컨테이너 이미지를 빌드하는 것을 목표로 합니다.
Podman은 pull 및 tag 지정과 같은 OCI 컨테이너 이미지를 유지관리하고 수정하는데 도움이 되는 모든 명령 및 기능을 제공합니다. 또한 컨테이너 작성, 실행 및 유지보수도 할 수 있습니다. 즉, Docker CLI에서 수행할 수 있는 명령은 Podman CLI에서도 동일하게 수행 할 수 있습니다.
Buildah와 Podman은 일부 겹치는 기능이 있는데 Buildah는 OCI 이미지를 생성하는 효율적인 도구로, Podman은 그러한 이미지와 이미지를 통해 생성한 컨테이너를 유지하고 관리하는 도구로 이해하면 됩니다. 기술적으로 buildah run은 Dockerfile RUN을 에뮬레이트하며 podman run은 docker run을 에뮬레이트 합니다.
Skopeo는 이미지 저장소에서 다양한 작업을 수행하는 명령줄 도구입니다. 기존 도커가 다른 레지스트리에 이미지를 복사하기 위해 pull, tag, push를 사용했다면 Skopeo는 간단하게 copy 명령으로 해당 기능을 제공합니다. 추가로 저장소에 있는 이미지 이름에 대해 로우 레벨 정보를 제공해줍니다.
4. 컨테이너의 미래
지금까지 도커, OCI, CRI, Buildah, Podman 등 컨테이너 기술의 전반적인 흐름과 생태계에 대해 알아보았습니다. 컨테이너는 온프레미스 환경에서 클라우드 네이티브 환경으로 옮기는 것을 쉽게 해주기 때문에 클라우드 컴퓨팅 분야에서 가장 주목 받는 기술 중 하나로 성장하고 있습니다. 그리고 그 중심에는 단연 도커가 자리잡고 있습니다. 하지만 컨테이너의 표준화가 이뤄진 후 컨테이너 시장은 OCI와 CRI를 중심으로 성장하고 있습니다. 그 과정에서 사실상 컨테이너 표준으로 사용되던 도커의 역할을 대신하는 다양한 기술이 나오고 있으며 그 중 Buildah, Podman, Skopeo는 도커의 기능을 역할별로 나눠 구현하고 있습니다. 이들은 또한 도커의 보안 관련 단점을 보완하며 기존에는 없던 편리한 기능도 추가로 제공합니다.
컨테이너 생태계는 계속해서 성장하고 있으며 도커 외에도 사용할 수 있는 다양한 대체기술을 선보이고 있습니다. 향후 컨테이너는 OCI의 설립 목적인 ‘통일된 표준을 통해 어디서든 작동하는 이식성 제공’을 위해 OCI와 CRI 표준을 중심으로 생태계를 넓혀갈 것입니다.
이번 글은 Docker의 개념 보다는 Docker를 처음 접하게 되었을 때 혼란스러웠던 내용을 정리한 글이다. Docker 컨테이너를 사용하는 용도는 여러가지가 있겠지만 이 글에서는 개발자가 만든 애플리케이션을 Tomcat과 같은 애플리케이션 서버에 탑재해서 배포하는 경우 겪게 되었던 내용이다.
Docker는 Virtual machine이 아니다!
처음 docker를 실행할 때 다음과 같은 명령을 실행하면 우분투 서버가 실행된다고 생각했다. 즉, Virtual machine과 같이 컨테이너 내에 우분투 서버가 실행되는 줄 알았다.
$ docker run --name ubuntu_test ubuntu
위 명령을 실행하면 그냥 아무것도 실행하지 않은 것 처럼 아무런 변화가 없다. 다만 다음과 같이 실행되지 않는 docker container를 보는 옵션(-a)을 주고 docker container의 목록을 보면 종료(Exit)되었다고 나타난다.
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS
PORTS NAMES
243c9dff7955 ubuntu "bash" 19 minutes ago Exited (0) 19 minutes ago ubuntu_test
필자의 경우 여기서 부터 혼란스러웠다. 우분투 image를 실행했는데 왜 아무것도 실행되지 않고 바로 Exit 되었을까? 결론은 Docker의 컨테이너는 Virtual machine과 같이 하나의 온전한 서버를 제공하는 것이 아니라 명령을 실행하는 환경만 제공하고 그 명령을 실행할 뿐이다[1].
위의 예제에서 보면 "docker ps -a" 명령으로 나타난 컨테이너 목록에서 다음과 같은 내용을 볼 수 있다.
/bin/bash 19 seconds ago
이 결과로 유추해보면 우분투 컨테이너를 실행하면 우분투 서버가 실행되는 것이 아니라 "/bin/bash" 가 실행되는 것 뿐이다. 이것이 Virtual machine의 컨테이너와 Docker 컨테이너의 가장 큰 차이점이다. 일반적으로 Linux 서버(Ubuntu or CentOS 등)나 Windows와 같은 운영 체제를 실행한다는 의미에는 많은 것을 내포하고 있다. 대략 다음과 같은 기능들이 실행될 것이다.
프로그램 실행 기능
Memory, CPU 등의 하드웨어 자원을 이용하여 프로그램을 실행할 수 있는 환경 제공
네트워크 서비스 제공
NIC 등을 하드웨어 자원을 인식해서 네트워크 처리가 가능한 환경을 제공
키보드, 모니터, 마우스 등과 같은 주변 장치의 입출력에 대한 처리
사용자로부터의 입력과 결과를 출력해주는 기능 제공
외부에서 접속할 수 있는 환경
sshd 등과 같은 데몬을 실행하여 서버 외부에서 네트워크를 이용하여 원격에서 접속할 수 있는 기능 제공
그리고 이 모든 것은 사용자가 임의로 전원을 끄기 전에는 지속적으로 동작하는 특징을 가지고 있다. Virtual machine 들은 이런 속성을 가지고 있다. 다만 여러 하드웨어 자원을 Host OS로 부터 할당 받은 것만 사용하도록 되어 있는 것이다.
그러면 컨테이너를 실행(run)하면 bash가 실행되어 prompt가 container의 bash prompt가 나타나야 하는게 정상 아닌가? 왜 Exit 되어 버리는가?
Docker 컨테이너는 단지 명령만 실행하고 그 결과만 보여주는 기능을 수행한다.[1]
즉, 앞의 예제에서는 우분투의 docker image에서 설정된 default 실행 명령[2]인 "/bin/bash" 를 실행하고 그 결과를 출력하고 종료된 것이다. "/bin/bash" 명령은 표준 출력(STDOUT) 또는 표준 에러(STDERR)로 아무것도 출력을 하지 않기 때문에 사용자가 보기에는 실행이 안된 것과 같은 느낌으로 다가 온다. 다음을 실행해보면 무엇을 말하는 것인지 알 수 있다.
$ docker run --name ubuntu_test ubuntu "env"
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=c4dc55ac2ddb
HOME=/root
docker run 명령에서 마지막에 주는 인자 값은 이 컨테이너가 실행할 명령을 전달하는 인자이다. 우분투 컨테이너의 경우 아무런 값을 입력하지 않으면 "/bin/bash"가 실행되고, 인자를 전달하면 그 값이 실행된다. 예제에서는 "env" 명령을 실행하도록 하였는데 "env" 명령은 시스템의 환경 정보를 출력하는 명령이다. 디렉토리 목록을 출력하는 "ls" 명령도 실행할 수 있다.
$ docker run --name ubuntu_test ubuntu "ls"
bin
boot
dev
etc
home
lib
...
docker 컨테이너를 실행한 다음 동일한 명령을 실행하면 다음과 같은 에러가 나타나는데 이것은 docker run 명령이 "create" 와 "start" 명령을 한번에 실행시키는 명령이기 때문에 create 시 이미 동일한 이름의 컨테이너가 존재하기 때문에 발생하는 문제이다. 이 경우 docker rm <id or name>으로 삭제한 후 다시 실행하면 된다.
docker: Error response from daemon: Conflict. The container name "/ubuntu_test" is already in use by container "065b413106d50d69b01077daccc5f7c1c406d98f993c71e6834d6e22318b93e4". You have to remove (or rename) that container to be able to reuse that name. See 'docker run --help'.
아니면 docker run 명령에 "--rm" 옵션을 주어 docker 컨테이너가 종료됨과 동시에 자동으로 삭제되게 할 수 있다. 실제 환경에서는 이 옵션을 사용하기도 하지만 이 글에 있는 예제를 확인하기 위해서라면 --rm 옵션을 주지 않고 실행하는 것을 권장한다.
우분투의 bash shell에서 명령을 실행하려면
위 예제에서 Docker run 명령행이 아닌 우분투 image의 bash shell에서 "ls", "cat" 등과 같은 명령을 실행하려면 어떻게 해야 할까? Docker 컨테이너를 실행할 때 다음 두 옵션을 추가하면 가능한데 대략 다음과 같은 의미이다.
i : Interactive 모드로 표준입력과 표준출력을 키보드와 화면을 통해 가능하도록 하는 옵션이다.
t: 텍스트 기반의 터미널(TTY)을 애뮬레이션해주는 옵션이다.
실행은 다음과 같이 한다.
$ docker run -it --name ubuntu_test ubuntu
# 다음과 같이 ubuntu의 bash shell로 prompt가 나타나고 해당 container 내에서 명령을 실행할 수 있다.
root@7a08aa924dcd:/# df -k
Filesystem 1K-blocks Used Available Use% Mounted on
none 61896484 9147280 49581972 16% /
tmpfs 65536 0 65536 0% /dev
tmpfs 1023376 0 1023376 0% /sys/fs/cgroup
/dev/vda2 61896484 9147280 49581972 16% /etc/hosts
shm 65536 0 65536 0% /dev/shm
tmpfs 1023376 0 1023376 0% /sys/firmware
이 부분에서 Docker를 처음 접하는 개발자는 또 한번 혼란스러움을 겪을 수 있다.위 예제와 같이 shell 이 나오고 내가 필요한 명령이 사용 가능하게 되면 마치 우분투 서버가 실행되었다는 착각을 하게 된다. 그리고 해당 shell에서 tomcat이나 rails와 같은 애플리케이션 서버를 설치하고, 실행해본다. 잘 돌아간다. 문제는 이렇게 한 다음 shell에서 "exit" 를 입력하여 shell에서 나오는 순간 컨테이너는 다시 중지된다.
Docker 컨테이너를 백그라운드로 실행하면?
여기까지 진행해보면 이런 생각을 하게 된다.
Docker의 컨테이너도 Host OS의 입장에서 보면 하나의 프로세스이기 때문에 프로세스가 종료(위에서는 shell에서 exit를 입력) 되면 컨테이너가 종료되겠지. 그러면 종료되지 않게 Docker 컨테이너 프로세스를 백그라운드로 실행하면 되지 않을까?
Docker 명령 옵션에 보면 다음과 같은 옵션이 있다.
$ docker help run
-d, --detach Run container in background and print container ID
$ docker run -d --name ubuntu_test ubuntu
981c0ec37c33631a8625549027ca644bb064d5e00eecb4d890b011d4396dbdb9
$ docker ps -a | grep ubuntu
981c0ec37c33 ubuntu "/bin/bash" 7 seconds ago Exited (0) 6 seconds ago ubuntu_test
"-d" 옵션이 Docker의 컨테이너를 백그라운드 프로세스로 실행하는 옵션이다. 위 예제에서 처럼 실행하면 컨테이너 ID가 출력되는데 이 ID나 --name 옵션으로 입력한 이름을 이용하여 컨테이너에 접근할 수 있다. "-d" 옵션을 주고 실행해도 docker의 컨테이너 상태를 확인해보면 "Exited" 상태인 것을 알 수 있다.
왜 이렇게 되는 것일까? docker 의 컨테이너를 실행한다는 것은 Host OS에서 프로세스를 실행하는 것과 동일한 개념이기 때문에 docker 컨테이너에서 실행되는 명령이 계속 실행되고 있는 상황이 아니면 그 명령이 종료됨과 동시에 컨테이너도 종료되기 때문이다. 이제 앞에서 실행한 interactive 모드인 "-it" 옵션을 주어 실행해보자.
$ docker run -d -it --name ubuntu_test ubuntu
8e7e71b7b692c7f293593d3f504bacec70e5541bae2021ebc0dbb28d9b8add21
$ docker ps -a | grep ubuntu
8e7e71b7b692 ubuntu "/bin/bash" 2 seconds ago Up 2 seconds ubuntu_test
이렇게 해서 일단 1차 원하는 목적이었던 shell을 백그라운드로 실행하는데는 성공하는 듯 보였다.
일반적으로 Virtual machine 으로 우분투를 실행한 경우, 이 서버에 접속하려면 ssh 와 같은 리모트쉘을 이용하지만 docker 컨테이너의 경우 일반적으로는 sshd를 실행하지 않는다. 대신 Host OS에서 docker attach 명령을 이용하여 컨테이너에 접속할 수 있다. 다음 명령을 이용하여 docker의 컨테이너에 접속할 수 있다.
$ docker attach ubuntu_test
root@2b206e1f3c07:/#
root@2b206e1f3c07:/# ls -al
total 72
drwxr-xr-x 34 root root 4096 Dec 17 13:02 .
drwxr-xr-x 34 root root 4096 Dec 17 13:02 ..
-rwxr-xr-x 1 root root 0 Dec 17 13:02 .dockerenv
하지만 여기서도 여전히 문제가 발생한다. 이 shell에서 "exit" 명령을 이용하여 shell을 나오게 되면 컨테이너도 같이 종료하게 된다.
root@2b206e1f3c07:/# exit
$ docker ps -a | grep ubuntu
8e7e71b7b692 ubuntu "/bin/bash" 5 seconds ago Exited (0) 5 seconds ago ubuntu_test
이것은 run -it 옵션과 attach 명령의 내용을 조금만 보면 예측할 수 있다. "-it" 옵션은 컨테이너의 입출력을 interactive 하게 하는 옵션과 TTY 터미널을 애뮬레이션 해주는 옵션이다. 이것을 백그라운드로 실행시킨 것이다. 그리고 attach 명령은 Virtual machine의 리모트쉘 접속과 같은 개념이 아니라 컨테이너의 현재 Host OS shell(local)의 stdout, stderr을 docker 컨테이너에 붙이는 명령인 것 뿐이다.
attach Attach local standard input, output, and error streams to a running container
즉 -it 옵션을 이용하여 interactive 모드로 실행하고 이것을 다시 -d 옵션을 주어 백드라운드로 실행하게 되면 interactive 쉘이 백그라운드로 동작하고 있는 것이다. 여기에 attach 명령으로 접속하여 exit 명령을 실행하면 interactive 쉘(/bin/bash)이 종료되고 이 쉘이 종료되면 결국 docker 컨테이너도 종료하게 되는 것이다.
Docker에 애플리케이션 서버 실행하기
여기까지 확인한 상태에서 필자가 내뱉은 한마디는 "이런 황당한 시츄에이션이! 이런 방식이면 어떻게 애플리케이션 서버를 실행하냐고?" 였다. 하지만 정답은 위에서 이미 다 나와 있었다. Docker의 컨테이너에서 실행되는 명령(위 예제에서는 /bin/bash)을 영원히 실행되게 하면 된다. 예를 들어 다음과 같이 컨테이너를 실행한다.
$ docker run -d --name ubuntu_test ubuntu /bin/bash -c "while true; do echo "still live"; sleep 100; done"
eb3b9e69b18d826dcc8788fc01930b4c411dabee4cbdfb646af79cb2cfbeacba
$ docker ps -a | grep ubuntu
eb3b9e69b18d ubuntu "/bin/bash -c 'whi..." 7 seconds ago Up 8 seconds ubuntu_test
위 실행 옵션은 /bin/bash를 실행하면서 -c 옵션에 있는 명령을 실행하게 하는 것이다. -c 에 있는 옵션은 무한 루프를 돌면서 100초마다 한번씩 "still live"를 출력하는 기능을 수행하는 shell script 이다. 이렇게 무한 루프를 도는 명령을 -d 옵션을 이용하여 백드라운드로 실행하기 때문에 컨테이너 실행 후 바로 Host OS의 Prompt로 돌아오지만 컨테이너는 여전히 살아 있는 것을 확인할 수 있다.
이 컨테이너에 이제 attach 해보자. attach 명령을 실행해보면 아무 반응도 없고 100초마다 "still live"만 출력하는 것을 볼 수 있다. 그렇다고 shell prompt가 나타나지도 않는다. 이것은 attach 명령어가 stdout, stderr을 가져오는 것이기 때문에 당연한 것이다. Shell에 접속하기 위해서는 attach가 아닌 exec 명령을 이용해서 컨테이너의 쉘 환경에 접속할 수 있다.
$ docker help exec
Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Run a command in a running container
Options:
-i, --interactive Keep STDIN open even if not attached
--privileged Give extended privileges to the command
-t, --tty Allocate a pseudo-TTY
$ docker exec -it eb3b9e69b18d /bin/bash
root@eb3b9e69b18d:/# exit
$ docker ps -a | grep ubuntu
eb3b9e69b18d ubuntu "/bin/bash -c 'whi..." 14 minutes ago Up 14 minutes ubuntu_test
이렇게 접속한 다음 exit 명령을 이용하여 shell을 빠져 나와도 컨테이너는 정상적으로 동작하는 것을 알 수 있다.
지금까지 내용을 종합해보면 Docker의 컨테이너 내에 애플리케이션 서버를 실행하려면 애플리케이션 서버가 무한루프로 동작하게 해야 한다. 하지만 이미 애플리케이션 서버들은 무한루프로 동작하는 프로그램들이다. 따라서 다음 내용만 주의하면 된다.
Docker 컨테이너에서 실행되는 애플리케이션 서버(DB 서버 포함)은 back ground 모드가 아닌 fore ground 모드로 실행해야 한다.
Tomcat의 경우 예를 들면 일반적으로 다음과 같이 실행하여 백드라운드 모드로 동작하게 한다. 이유는 tomcat 서버를 실행시킨 shell이 종료되더라도 tomcat 서버는 정상적으로 계속 동작하게 하기 위해서이다.
$ cd $CATALINA_HOME/bin;
$ ./catalina.sh start;
하지만 docker 환경에서 이렇게 하면 컨테이너가 바로 종료되어 Tomcat 서버가 죽는 것과 동일한 상황을 맞게 된다. 다음과 같이 fore ground로 실행해야 한다.
$ cd $CATALINA_HOME/bin;
$ ./catalina.sh run;
실제 docker 환경에서 tomcat을 실행하는 경우 위 예제와 같이 명령을 직접 입력하지 않고 Dockerfile에 실행 명령을 지정하는데 이때 위와 같이 fore ground 명령을 사용해야 하는 것이다. dockerhub에 있는 공식 tomcat 컨테이너의 image를 만드는 Dockerfile에도 다음과 같이 사용하고 있다.
여기까지 진행하면 Docker가 대충 어떻게 돌아가는 지를 이해했으며 원하는 목적을 이루었다. 하지만 이 상황에서 다시 몇가지 사소한 이슈가 발생하였다. 가장 큰 이슈는 컨테이너 내부에 들어가면 애플리케이션 서버를 관리할 수 있는 것이 아무것도 없다는 것이다. Docker의 컨테이너는 대부분 Minimalism을 중요시하기 때문에 딱 필요한 것만 설치한다. 이렇게 작게 만드는 것은 마이크로 서비스 환경에서 하나의 서버에 수십개 이상의 컨테이너가 실행되는 환경을 상상해보면 쉽게 이해할 수 있다.
하지만 컨테이너를 작게 만들다 보니 기본적인 도구조차 없는 경우가 대부분이다. 필자의 경우 기본으로 제공하는 이미지를 사용하지 않고 다음 정도는 설치되어 있는 환경을 구성하여 사용하고 있다.
JRE 가 아닌 JDK로 구성 이렇게 구성하는 가장 큰 이유는 JRE로 구성하게 되면 자바 프로세스에 대한 모니터닝을 할 수 있는 도구가 없다. 애플리케이션 서버에 성능상 문제가 발생했을 때 jstat, jmap, jstack 등과 같은 명령을 이용하여 jvm의 상태 정보를 조회할 수 있어야 하는데 이런 도구가 없어 불편한 경우가 많다.
vi 파일을 내용을 확인하기 위해서는 cat, grep 등 기본 명령만으로는 부족해서
net-tools ifconfig도 없고, netstat 등 네트워크 관련 뭔가 볼 수 있는게 없는데 기본적으로 이런 명령은 되어야 운영 환경에서 문제가 생겼을 때 원인 파악이라도 할 수 있어야 하기 때문이다.
환경설정을 바꾸고 다시 실행하면...
앞에서 설명했듯이 Docker 컨테이너에서 실행되는 애플리케이션 서버는 fore ground로 실행되는데 이렇게 할 경우 귀찮은 문제가 발생한다. 간단한 성능 확인이나 기능 확인 등을 위해 Tomcat 서버의 옵션을 하나 수정한 다음 재시작하게 될 때 문제가 된다. fore ground로 실행되어 있기 때문에 Tomcat 서버가 재 시작되면 해당 컨테이너가 종료된다. 즉, 옵션 하나 바꾸는 것도 컨테이너에서 직접 바꾸면 안되고 Dockerfile을 이용해서 바꾼 후 이미지를 빌드하고, 컨테이너를 시작해야만 적용할 수 있다. 이런 사이클은 개발 단계나 운영 환경에 문제가 발생하여 지속적으로 튜닝을 하면서 상태를 지켜보는 과정이라면 좋은 사이클이라 할 수 없다.
필자가 선택한 방법은 서비스 개발 후 초기 얼마 동안은 다음과 같은 형태로 컨테이너를 구성하였다.
애플리케이션 서버는 백그라운드로 실행
애플리케이션 서버 실행 후 바로 shell script로 무한 반복 스크립트 실행
즉, 다음과 같은 bootstrap.sh 명령을 실행하도록 하였다.
# Run background
bin/catalina.sh start
# Run script forever
while true;
do echo "still live";
sleep 600;
done
이렇게 하면 설정 변경 후 재시작해도 Docker 컨테이너는 여전히 계속 살아 있고 변경된 옵션에 대해 확인할 수 있다. 이 방법은 서비스 초기 어떤 옵션이 서비스에 맞는지 확인하는 용도로만 사용하고, 정상적인 운영환경에서는 사용하지 않는 것을 권장한다.
프로그램에서 출력하는 로그는 어떻게 해야 하나?
일반적인 환경에서 tomcat등과 같은 애플리케이션 서버의 로그는 파일에 저장하도록 하였다. 로그를 파일에 저장하고 로그 파일의 크기 또는 일자에 따라 파일을 롤링하는 방식을 많이 사용하였는데 이것은 애플리케이션 서버를 백그라운드로 실행하기 때문에 백그라운드로 실행된 상태에서 로그를 확인하기 위해서는 로그를 표준출력으로 보내기 보다는 파일로 저장하는 것이 훨씬 관리하기 편했기 때문이다. 물론 백그라운드로 실행했다고 해서 파일로 저장 못하는 것은 아니지만 사이즈, 크기 등에 따른 롤링 등을 설정하기 위해서는 별도 작업을 해줘야 하는 번거로움이 있다.
그러면 Docker 컨테이너에 애플리케이션 서버를 실행하는 경우 로그는 어떻게 해야 할까? 다음 세가지 방안 정도로 생각할 수 있다.
이전과 동일하게 파일로 저장한다.이것은 컨테이너의 특정 디렉토리에 저장하게 한다는 의미인데 이렇게 할 경우 해당 컨테이너가 삭제되면 로그도 같이 삭제되기 때문에 권장하지 않는다.
모든 로그를 표준 출력(STDOUT) 또는 표준 에러(STDERR) 로 출력한다.Docker 는 컨테이너에서 STDOUT나 STDERR로 출력하는 모든 메시지를 Host OS의 특정 디렉토리에 저장하고 이를 쉽게 조회할 수 있는 명령도 제공한다(docker logs 명령). 따라서 모든 로그를 표준 출력으로 보내면 쉽게 로그에 접근할 수 있게 된다.
이 방식도 문제가 존재하는데 이 로그 파일을 하나의 파일로 관리하게 되면 파일이 너무 커지게 되어 스토리지를 모두 차지하게 되는 문제가 있다. 최근 버전의 Docker에서는 로그 파일을 롤링할 수 있는 기능을 제공하는데 이 방식을 사용할 경우 반드시 이 옵션을 사용하는 것을 권장한다.
1번과 같이 파일에 로그를 저장하지만 로그 디렉토리를 Host OS의 볼륨을 이용한다.이렇게 하면 1번의 로그가 삭제되는 문제와 2번의 롤링 문제를 해결할 수 있지만 컨테이너 생성 시 볼륨을 붙여줘야 한다.
필자의 환경에서는 2번을 사용하고 있다. 스테이징 환경에서는 사이즈나 롤링 설정을 하지 않아 가끔 스테이징 서버의 디스크가 Full 나는 상황이 발생하는데 대부분 로그 문제 때문이다.
맺음말
지금까지 필자가 Docker 를 이용하여 애플리케이션 서버를 구성할 때 부딪혔던 Docker 컨테이너에 대해 잘못 알고 있었던 내용과 몇가지 이슈를 설명하였다. 필자가 속해 있는 개발팀에 Docker 를 처음 접해보는 개발자들이 어떻게 Docker를 이해하는지 유심히 살펴보니 대략 필자와 비슷한 오해와 사용을 하고 있는 것을 관찰할 수 있었다. 그리고 대부분의 Docker 문서에서는 이런 내용들에 대한 설명이 많지 않다. 이 글이 이런 오해를 하는 개발자들에게 조금이나마 도움이 되었으면 하는 바램이다.
각주
[1]물론 Docker 내부적으로는 다른 무엇인가 있겠지만 그런 내용을 설명하기 위한 글이 아니라 이렇더라 정도를 알려주는 것이 목적이기 때문에 이렇게만 설명한다. 이것도 정확한 내용이라기 보다는 필자가 나름대로 추측해서 정리한 것이다. 필자 역시 Docker에 대해 깊게 고민을 하지 않았다.
[2] 이것은 Docker image를 만들때 임의로 지정할 수 있다. 우분투 기본 image가 /bin/bash를 실행하게 만들어졌다.
Knowing the various states of the Docker Container is essential for any serious Docker user.
I'll explain the container lifecycle and then show the Docker commands for each stage of the lifecycle.
But before you learn all those things, let's revisit the concept of the container once more.
What are Docker containers, again?
Most traditional definitions of containers go like this:
Containers are a form of operating system virtualization. While traditional hypervisor based virtualization requires separate kernels for separate VMs, containers share the same host kernel, and is therefore, much more lightweight and faster to spin up
The definition will differ from source to source, but the gist is the same.
I find it boring and unnecessarily complicated. I'd like to use something different here to define containers.
Containers are a bunch of processes that are being cheated on.
Why do I say that? Because containers are just a collection of processes, sometimes just a single process. And these processes are being lied to about different resources of its host like networks, process tree, filesystem, hostname etc.
You can run any process, even a shell like bash, and hide your actual process tree from it, give it a different set of networks, hide the actual root filesystem from it, give it a different hostname and essentially, what you'll end up doing is creating a containerized version of the process.
This is achieved by namespaces, separate root filesystem and cgroups.
Docker is just a wrapper around the lower level tools that run and manage the containers, or more specifically saying the container lifecycle.
Apart from that, Docker also does many other things, like making networking for the containers easy, handling storage, pulling & pushing container images etc.
Docker is here to make our life easier.
Now, let's look at the Docker Container Lifecycle
The container lifecycle is basically a series of stages, starting from the creation of the container to its destruction.
The following diagram is going to make this a lot clear.
Container Lifecycle
Let me explain each stage of the container lifecycle.
Creation: Many people think that when you run a container, it's one single step. But that's not the case. There is a process which creates the containers first before anything else. More on this later.
Started/Running: Once a container is created, it can be started, after which the status changes to Running. This is when the container is actually doing something.
Paused: Traditionally to pause a process (which containers basically are), we use the SIGSTOP signal, and to unpause, the SIGCONT signal. But since this signal is observable by the processes, instead of signals, cgroup freezers are used. This way the processes are suspended by freezing the cgroup.
Exited/Stopped: The opposite of Running, but not the same as Paused. Stopping a container means sending the SIGTERM signal to the main container process, i.e. PID 1 in the container namespace. It then waits for 10 seconds to let the process exit gracefully. If it doesn't, a SIGKILL signal is sent, and we all know what that means, don't we?
Destroyed/Deleted: The container doesn't exist anymore, all the resources that it once allocated, is now gone.
I hope this has made the concept of container lifecycle clearer now. In the following section I'll go through all the specific docker commands that'll help you in managing all these states of containers.
Docker Commands to Manage Container Lifecycle
All the commands (subcommands, if being more specific) that control the container lifecycle belongs to the subcommand container.
In a terminal if you execute docker container --help you'll get a list of subcommands that are associated with multiple operations performable on containers.
But we're not concerned about all of them here. Let's focus only on a specific subset of those.
Container Creation
Container creation is handled by the following commands:
docker container create
docker create
The first one is the long form, while the second one, you guessed it right, is the short form.
I recommend you use the long form as it's more verbose and something I consider a good practice.
What is container creation?
Container creation is creating the R/W layer on top of the specified image's R/O layer[s], and preparing it to run the required program. Creating a container does not start the actual process, you can specify all the configuration parameters like capabilities, CPU limit, memory limit, container image etc right at the creation stage and then start the container anytime you want without having to re-specify those parameters.
Read docker container create --help for a list of configurable options.
Example
First create a container like the following (I used an alpine image here to run the command sleep infinity)
Once the container is created, you should get the ID of it in the terminal screen. Now you can filter the container list to find the containers that aren't running, but just created.
docker container ls --filter=status=created
Here I'm filtering the list so that I get only the containers that are created. Take a look at the STATUS column, that's what specifies a container's state. You should see something like the following:-
➟ docker container ls --filter=status=created
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3f8d56fb3f78 alpine:3.13.4 "sleep infinity" 17 seconds ago Created alpine
You can also inspect the container and see what state it is in.
Using docker create will not give you anything different.
Container Startup
To start a container, use one of the following two commands:-
docker container start
docker start
Same thing here, one long and one short version. And I recommend you use the ...container start command.
What is container startup?
Once a container has been created, you can start it. Starting the container means actually running the containerized application.
While creating a container merely prepares all the configuration (how the container will run, runtime environment, runtime constraints, container name etc), it does not allocate any of the resources.
Starting a container allocates the necessary resources and runs the application.
Example
Consider the previous container that we created. Simply start the command with the container name or ID like this:
docker container start alpine
Once the container is started, it's status changes from Created to Running. In the container list, you can filter by the status again like you did previously:-
docker container ls --filter=status=running
On the STATUS column, instead of Running it'll show how long the container has been running since it started.
➟ docker container ls --filter=status=running
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3f8d56fb3f78 alpine:3.13.4 "sleep infinity" 8 minutes ago Up 18 seconds alpine
You can also inspect a container to see it's state. I'll use Go templates to format the output to the only thing that I need, i.e. the state.
Not to sound redundant, but docker start will do just the same thing.
The Special Docker Run Command
This is a special command that ties the container creation and startup together and this is the command that we all use the most.
docker container run
docker run
These commands essentially (i) creates the container and then immediately (ii) starts the same container.
This is useful because creating and leaving a container to start at a later time isn't something we do all too often. When you are at the command line, with the docker CLI, you are here to run a container. And that's exactly what ...container run command does.
Example
Example of this command is very simple. To run a container, instead of docker container create, use docker container run.
You will have to pass all the options you'd pass to docker container create to this docker container run command. This is because docker needs all that information right at that moment since there no more second steps.
➟ docker container run --name echo-me alpine:3.13.4 echo "Subscribe to Linux Handbook"
Subscribe to Linux Handbook
Pausing a container means exactly how it sounds. We're not stopping any processes, just pausing it. So if a process inside a container is counting from 1 through 100, and it was paused while it was at count 50 and then unpaused at a later time, the count will resume from 50.
One thing to understand is that while Paused is an actual state, Unpaused is not. When you're unpausing some paused container, you're essentially changing the state from Paused to Running.
The commands that are used to pause a container are as follows:-
docker container pause
docker pause
Similarly you can unpause a container with the unpause counterparts:-
docker container unpause
docker unpause
How a container is paused?
A process is paused by using the SIGSTOP signal, and to unpause, the SIGCONT signal is used. Since these signals can be observed by the processes, instead of signals, cgroup freezers are used. This way the processes are suspended by freezing the cgroup. Freezing a cgroup freezes all of its tasks, and all of its child cgroups.
Example:
For the sake of this demo, I've created a special container. Pull the image by executing the following command:-
docker image pull debdutdeb/pause-demo:v1
You can check the Dockerfile and the code right here.
Once pulled, on one terminal, start a container with this image
docker container run --name pause-demo debdutdeb/pause-demo:v1
It should now show counting starting from 0 and going. Should look something like the following
➟ docker container run --name pause-demo debdutdeb/pause-demo:v1
Count at 30
On another terminal, pause this container.
docker container pause pause-demo
The moment you're pausing the container, you should see the countdown stop, but the terminal isn't back to you yet. This is because the container isn't yet stopped (I'll talk about this later in this article). Once you unpause this container, countdown should resume, not restart.
docker container unpause pause-demo
To get the terminal back, on a separate terminal run
docker container stop pause-demo
Here is a short video that'll show this in action:-
Before stopping the container you can like the previous ones, check the state of the paused container like so:
Stopping a container means stopping all the processes associated with it.
This is not the same as pausing a container. If you stop a container, you can restart it, but the processes are not going to resume from the state that they were previously in. A process can save its state information in a "file", and restore its state from that file, but that's a different case.
For example, after you stopped the previous pause-demo container, if you try and restart it using the ...container start command, it'll start counting from the beginning, unlike its pause counterpart which resumes the counting.
How the process works?
When you ask Docker to stop a container, it sends a SIGTERM signal to PID 1 of the container. After that, it waits for 10 seconds, which is its graceful time period, the process is given this time to gracefully exit, in other words clean up and finish whatever it was working. After the 10 seconds is over, Docker sends a final SIGKILL signal, I don't have to tell you what happens next.
Docker sends the signal to PID 1 of the container because every other process is a child of PID 1, if this process gets terminated/killed, the chil processes will automatically cease to exist.
This become clearer with the example below.
Example:
You need to pull an image, again.
docker image pull debdutdeb/stop-demo:v1
For the Dockerfile and source code, check out this gist.
In one terminal, start a container from this image.
docker container run --name stop-demo debdutdeb/stop-demo:v1
Once executed, you should see a screen telling you its PID and that it's waiting.
➟ docker container run --name stop-demo debdutdeb/stop-demo:v1
My PID in this container is 1
Waiting...
Open another terminal, and execute the stop command on this container.
docker container stop stop-demo
Once run, you should see on the terminal that was running the container, telling you what IT is experiencing, i.e. receiving the SIGTERM signal.
Afterwards it starts counting the seconds, and you'll see after 10 seconds it just stops counting. This isn't because I hard-coded it that way, actually I hard-coded it to go on infinitely.
But after 10 seconds docker sends a SIGKILL signal that we can't catch or ignore, the process is bound to be killed.
You can change the time docker waits before sending the SIGKILL signal by using the -t option with docker container stop.
Once everything is done, you should see something like this
➟ docker container run --name stop-demo debdutdeb/stop-demo:v1
My PID in this container is 1
Waiting...
SIGTERM ignored,
Starting count..
10 seconds
Here is a small video demonstrating this:-
You can check the state of this container now using ...container inspect like so:-
A container is deleted using one of the following two commands:-
docker container rm
docker rm
Container deletion is the opposite of container creation. When you delete a container, it's gone, you can't bring that specific container back. You can start a new one from the same image using the same configuration, make it identical, but it won't be that exact previous one.
Example:
For an example just remove the previous stop-demo container.
docker container rm stop-demo
Until now, all the containers that you created and then stopped can be removed with a single command:-
✗ docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
ffbdd621c01d0eb3f42d348eeb75c731ddd9bd85674bb90dece32bd70357e541
21b9ed6a6198cd6ee7e162aebd936ae3e93b3b0f738161924a825a27794f2b20
f5f5149866a6ced675ad3bfff0b7386f75ee3fdbddca86be8b8ba341dba4b27f
Total reclaimed space: 0B
So, you learned the container life cycle concept. And you also learned the Docker commands to manage each stage of the lifecycle of the containers. If you want some more Docker tips, you may learn about these lesser known but useful Docker commands.
docker ps 명령어로 현재 실행되고 있는 컨테이너를 조회하면 방금 생성한 컨테이너가 보이지 않습니다. 왜냐하면, 생성은 되었지만 실행이 되지 않았기 때문입니다.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
docker ps -a 명령어로 실행중이거나 중지된 모든 컨테이너를 조회해보면 STATUS가 Created이고 이름이 container-1인 컨테이너를 볼 수 있습니다.
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
71c041429247 ubuntu "bash" 2 minutes ago Created container-1
docker run 명령어로 container-2라는 이름의 컨테이너를 생성하고 실행해 보겠습니다.
$ docker run -d -it --name container-2 ubuntu
c28cec7d600b3379c0d9440378427dd7343bca3d02777d62bba79d6f08c6f003
container-2 가 실행되고 있고 STATUS가 Up인 상태인 것을 볼 수 있습니다. 즉, docker run 명령어는 컨테이너를 생성하고 시작합니다.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c28cec7d600b ubuntu "bash" 18 seconds ago Up 17 seconds container-2
docker stop 명령어로 실행 중인 container-2 컨테이너를 중지합니다.
$ docker stop container-2
container-2
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
c28cec7d600b ubuntu "bash" 3 minutes ago Exited (137) About a minute ago container-2
71c041429247 ubuntu "bash" 25 minutes ago Created container-1
docker start 명령어로 docker create로 생성한 container-1 컨테이너를 실행해 봅니다. 아래와 같이 컨테이너가 실행된 것을 확인할 수 있습니다.
$ docker start container-1
container-1
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
468813d90e4c ubuntu "bash" About a minute ago Up 2 seconds container-1
도커 컨테이너 및 이미지 삭제
docker rm -f 명령어로 container-1 컨테이너를 강제 삭제합니다. 즉, 실행중인 컨테이너를 중지하고 컨테이너를 삭제합니다.
docker rmi 명령어로 ubuntu 이미지를 삭제합니다. 이제 컨테이너도 이미지도 남아 있지 않습니다.
아래와 같이 docker run 명령어를 수행합니다. local 서버에서 이미지를 찾을 수 없다는 메시지와 함께 이미지를 라이브러리에서 Pulling하고 설치하고 실행합니다.
$ docker run -d -it --name container-3 ubuntu
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
ea362f368469: Pull complete
Digest: sha256:b5a61709a9a44284d88fb12e5c48db0409cfad5b69d4ff8224077c57302df9cf
Status: Downloaded newer image for ubuntu:latest
4b3269f98b4dc91fd934bd039d8141dc6a6e6ffb763d2c758238a1d005469220
다운로드된 이미지와 시작된 컨테이너을 확인합니다.
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4b3269f98b4d ubuntu "bash" About a minute ago Up About a minute container-3
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu latest d13c942271d6 9 days ago 72.8MB
위와 같이 이미지가 다운로드되었고 컨테이너가 시작된 것을 확인할 수 있습니다.
결론적으로 docker run 명령어는 pull, create, start 를 상황에 따라 수행하는 명령어입니다. 즉, 이미지가 없을 때는 pull, create, start를 이미지가 있을 때는 create, start를 수행하고 컨테이너가 있을 경우에는 start를 수행합니다.
윈도우키(Windows 로고 키) + R 키를 누른후 winver 를 치면 아래와 같은 화면이 나타나는데 윈도우 버전과 빌드 운영체제를 확인할 수 있다.
시작(윈도우 로고키) - 설정 - Windows 업데이트 를 선택하여 최신 Windows 버전으로 업데이트할 수 있습니다.
WSL 설치
DISM으로 WSL 기능 활성화
명령창을 관리자 권한으로 실행합니다.
DISM(배포 이미지 서비스 및 관리) 명령어로 Microsoft-Windows-Subsystem-Linux 기능을 활성화합니다.
$ dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
배포 이미지 서비스 및 관리 도구
버전: 10.0.19041.844
이미지 버전: 10.0.19042.870
기능을 사용하도록 설정하는 중
[==========================100.0%==========================]
작업을 완료했습니다.
다음으로 dism 명령어로 VirtualMachinePlatform 기능을 활성화합니다.
$ dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
배포 이미지 서비스 및 관리 도구
버전: 10.0.19041.844
이미지 버전: 10.0.19042.870
기능을 사용하도록 설정하는 중
[==========================100.0%==========================]
작업을 완료했습니다.
Microsoft Store를 열고 wsl로 검색하여 WSL에서 사용할 수 있는 리눅스 배포판을 검색하고 설치합니다.
검색된 앱 중 Ubuntu 20.04 LTS 를 설치하고 시작 버튼을 클릭해 줍니다.
Ubuntu 설치 화면에 username 을 입력하라는 메시지가 나타납니다. 원하는 임의의 계정을 입력합니다. 향후 WSL에서 사용할 계정입니다.
계정을 입력한 후 계정에 대한 패스워드를 입력하면 최종 아래와 같이 설치 완료 화면이 보입니다.
wsl -l 명령어를 실행하면 우분투 배포판이 설치된 것을 확인할 수 있습니다.
wsl -l
Linux용 Windows 하위 시스템 배포:
Ubuntu-20.04(기본값)
6단계 - WSL 2를 기본 버전으로 설정
명령창을 관리자 권한으로 열고 wsl 버전을 확인합니다. 만약 VERSION이 1 이라면
wsl --set-version Ubuntu-20.04 2 명령어를 수행해 줍니다.
wsl -l -v
NAME STATE VERSION
* Ubuntu-20.04 Stopped 2
명령창을 관리자 권한으로 열고 이 명령을 실행하여 새 Linux 배포를 설치할 때 WSL 2를 기본 버전으로 설정합니다.
wsl --set-default-version 2
WSL2 리눅스 커널 업데이트 및 배포판에서 2 버전 활성화하기
관리자 PowerShell 또는 Windows 명령 프롬프트에 wsl --install 명령을 입력한 다음 컴퓨터를 다시 시작하여 Linux용 Windows 하위 시스템(WSL)을 실행하는 데 필요한 모든 것을 설치할 수 있습니다.
wsl --install
이 명령은 필수 선택적 구성 요소를 활성화하고, 최신 Linux 커널을 다운로드하고, WSL 2를 기본값으로 설정하고, Linux 배포를 설치합니다(default 우분투) 새로 설치된 Linux 배포판을 처음 실행하면 콘솔 창이 열리고 파일이 압축을 풀고 컴퓨터에 저장될 때까지 기다리라는 메시지가 표시됩니다.
Window Old 빌드를 사용 중이거나 설치 명령을 사용하지 않고 단계별 설치를 원하는 경우 이전 버전에 대한 WSL 수동 설치 를 참조하세요.
Linux 사용자 계정 설정
WSL 설치가 완료되면 아래와 같이 Linux 배포에 대한 사용자 계정과 패스워드를 입력하는 창이 나타납니다. 한번 만들면 해당 계정이 배포의 기본 사용자가 되며 시작 시 자동으로 로그인됩니다.
이 계정은 sudo(Super User Do) 명령을 실행할 수 있는 Linux 관리자입니다.
설치된 WSL 버전 확인
PowerShell 또는 Windows 명령 프롬프트에서 wsl -l -v 명령을 입력하여 설치된 Linux 배포판을 나열하고 각각 설정된 WSL 버전을 확인할 수 있습니다.
WSL 사용
PowerShell 또는 Windows 명령 프롬프트에서 wsl 명령어를 입력하면 WSL 에 진입합니다.