前回の記事「Dockerのインストール | Linux」ではLinuxにDockerをインストールし、Docker MachineとDocker Composeという有用なツールをインストールしました。
この記事では、いくつかの基本コマンドを見ていくとともに、取り合えずDockerで何ができるか、どうすれば目的のサービスをDocker上で起動できるかについて説明します。題材の1つとしてnginxを使います。nginxをDockerで起動する方法について探している方は、本記事「常時起動のサービスまたはアプリケーション」セクションをご参照ください。
コマンドヘルプの表示(docker help)
始めのコマンドはやはりコマンドの説明を表示してくれるヘルプコマンドです。コマンドやコマンドのオプションにどういうものがあるか調べたい、あるいは使い方を調べたいなど、困ったときのヘルプコマンドです。
docker help
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default "/home/developer/.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/developer/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default "/home/developer/.docker/cert.pem")
--tlskey string Path to TLS key file (default "/home/developer/.docker/key.pem")
--tlsverify Use TLS and verify the remote
-v, --version Print version information and quit
Management Commands:
app* Docker App (Docker Inc., v0.9.1-beta3)
builder Manage builds
buildx* Build with BuildKit (Docker Inc., v0.5.1-docker)
config Manage Docker configs
container Manage containers
context Manage contexts
image Manage images
manifest Manage Docker image manifests and manifest lists
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.
To get more help with docker, check out our guides at https://docs.docker.com/go/guides/
大量にコマンドが用意されていることがわかります。不要なものが多いのでしょう、と思ったりもするかもしれませんが、どれも重要なコマンドです。docker helpでは、各コマンドの概要を表示しますが、詳細なオプションを調べるには、さらにコマンドを指定し、--helpオプションを指定します。
docker <<COMMAND>> --help
例えば、containerコマンドを調べてみます。以下を見るとrunというサブコマンドがあることがわかります。説明には、新しいコンテナを起動するためのコマンドであることが記載されています。
docker container --help Usage: docker container COMMAND Manage containers Commands: attach Attach local standard input, output, and error streams to a running container 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 exec Run a command in a running container export Export a container's filesystem as a tar archive inspect Display detailed information on one or more containers kill Kill one or more running containers logs Fetch the logs of a container ls List containers pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container prune Remove all stopped containers rename Rename a container restart Restart one or more containers rm Remove one or more containers run Run a command in a new container 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 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 wait Block until one or more containers stop, then print their exit codes Run 'docker container COMMAND --help' for more information on a command.
Dockerコンテナの実行(docker container run)
Docker上でプログラムを実行する目的としては大まかに2つあるのではないでしょうか。1つは、プログラムの実行が完了後、リソースを開放して処理を終了する用途(単体プログラムの実行)、2つ目はWebサーバやGUIアプリケーションのように、ユーザやシステムが明確な停止指示を出すまでは常時起動しておく用途(常時起動のサービスまたはアプリケーション)です。
単体プログラムの実行
プログラミング言語の入門時には必ずと言っていいほど「Hello World!」という文字列を画面に表示するプログラムを題材にするのが王道です(笑) ここでは、
Dockerの入門でも同様に、hello-worldコンテナを起動して画面に文字列を表示してみましょう。実行するのは簡単です。単にsudo docker container run hello-worldをコマンド実行するだけです。
sudo docker container run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:31b9c7d48790f0d8c50ab433d9c3b7e17666d6993084c002c2ff1ca09b96391d
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/
初回の起動のためインターネットからhello-worldコンテナイメージをダウンロード(Pull)しています。その後、このイメージからコンテナを作成・起動し、コンテナの実行結果である「Hello
from Docker!」を表示してくれました。
実行結果の後には、実行結果は正常だったのか、このコマンドによって具体的に何が行われたのかという説明が表示されました。そして、一旦実行が終わると、コンテナは停止されます。
利用したいサービス(例:hello-world)は何かさえわかれば、あとはコンテナ起動コマンドに指定して実行するだけで、必要なことはすべてDockerがやってくれるということです。すごいしくみです。
常時起動のサービスまたはアプリケーション
続いてWebサーバであるnginxをDockerで起動してみます。実行するのは先ほどと同様に1行のコマンドですが、Web通信を受けるための設定をコマンドに指定するため、コマンドは少し長くなります。
sudo docker container run -d --name nginx-test -p 8080:80 nginx Unable to find image 'nginx:latest' locally latest: Pulling from library/nginx 45b42c59be33: Pull complete d0d9e9ea897e: Pull complete 66e650438339: Pull complete 76a3dfe4406b: Pull complete 410ff9d97480: Pull complete Digest: sha256:8e10956422503824ebb599f37c26a90fe70541942687f70bbdb744530fc9eba4 Status: Downloaded newer image for nginx:latest 999ff9c9374fc83a1f9483a87fcc1bda64cce138de66dbdca87b3e9fb336622d
コマンドオプションの説明は以下の通りです。
-dバックグラウンドで実行-nameコンテナ名としてnginx-testを指定-p8080/tcpに来た通信をこのコンテナのhttpにフォーワード
初回は、nginxコンテナイメージがローカル環境にないため、最新のイメージをインターネットからダウンロードしてきています。その後、上記コマンドオプションの条件でnginxを実行しています。
ブラウザからhttp://localhost:8080/を指定して、nginxサービスにアクセスしてみましょう。
nginxのWelcomeページが表示されました。
このコンテナは明示的に停止指示を出さないと起動しっぱなしになります。docker container lsコマンドで起動中のコンテナを確認してみます。
sudo docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 999ff9c9374f nginx "/docker-entrypoint.…" 15 minutes ago Up 15 minutes 0.0.0.0:8080->80/tcp nginx-test
不要になったらdocker container stopおよびdocker container rmコマンドでコンテナを停止・削除します。
sudo docker container stop nginx-test nginx-test $ sudo docker container rm nginx-test nginx-test $ sudo docker container ls CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
これで起動中のコンテナはなくなりました。
おわりに
今回は、Dockerで目的のサービスを起動するための基本コマンドの紹介と簡易な手順を説明しました。1行のコマンドでサービスやアプリケーションが実行できるのはまさに驚きですね。
またnginxサーバの起動では、少し起動オプションとしてどのように起動するのかを指定してみました。ヘルプコマンドを活用し、サービスの要件に合わせてコマンドオプションを指定してみてください。
本記事ではLinux上でDockerコマンドを実行しましたが、これらのコマンドはDockerを実行しているホストがどこであろう(OSが何であろうと)と関係なく同じように動作します。Docker技術のすごさが垣間見れました。
