Docker Desktop の基本的なログを表示する
このステップでは、Docker コンテナからの基本的なログを表示する方法を学びます。ログはコンテナ内で動作するアプリケーションのデバッグや監視に不可欠です。
まず、何らかの出力を生成するシンプルなコンテナを実行しましょう。メッセージを表示して終了する非常に小さなイメージであるhello-world
を使用します。
docker run hello-world
以下のような出力が表示され、Docker デーモンがイメージをプルしてコンテナを正常に実行したことがわかります:
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:f52335ce493178fc15f729218f180e9988e31c374a6ce98da40cbb890f97f10e
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.
(Assuming it was not already locally available.)
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 learn more, try the following commands:
docker run -it ubuntu bash
docker images
docker ps
docker stop <containerid>
docker rm <containerid>
To get started with Docker Desktop, visit:
https://www.docker.com/products/docker-desktop
この出力は、コンテナからの標準出力 (stdout) と標準エラー(stderr) ストリームです。Docker はこれらのストリームをキャプチャし、ログとして利用可能にします。
次に、実行状態を維持し、時間とともにログを生成するコンテナを実行しましょう。alpine
イメージを使用し、5 秒ごとにメッセージを表示するシンプルなコマンドを実行します。
まず、alpine
イメージをプルします:
docker pull alpine
イメージがプルされていることを示す出力が表示されます:
Using default tag: latest
latest: Pulling from library/alpine
... (ダウンロード進捗を示す出力)
Digest: sha256:...
Status: Downloaded newer image for alpine:latest
docker.io/library/alpine:latest
次に、alpine
コンテナをデタッチモード (-d
) で実行し、バックグラウンドで動作させ、簡単に参照できるように名前 (--name mylogger
) を付けます。コマンドwhile true; do echo "Hello from mylogger at $(date)"; sleep 5; done
は、5 秒ごとに現在の日付を含むメッセージを表示します。
docker run -d --name mylogger alpine sh -c 'while true; do echo "Hello from mylogger at $(date)"; sleep 5; done'
このコマンドはコンテナ ID を出力します。
実行中のコンテナのログを表示するには、docker logs
コマンドの後にコンテナ名または ID を指定します。
docker logs mylogger
コンテナのコマンドによって生成された出力が表示され、約 5 秒ごとに新しい行が追加されます。Ctrl+C
を押すとログの表示を停止できます。
ログをリアルタイムで追跡するには、-f
(follow) オプションを使用します:
docker logs -f mylogger
これにより、新しいログエントリが生成されると継続的に表示されます。Ctrl+C
を押すとログの追跡を停止します。
最後に、作成したコンテナを停止して削除しましょう:
docker stop mylogger
docker rm mylogger
これにより、コンテナリソースがクリーンアップされます。