はじめに
基本コマンド
docker run はコンテナを作成して起動します。-d でバックグラウンド実行、-p でホストポートをコンテナポートへマッピングします。pull はレジストリ(デフォルトは Docker Hub)からイメージをダウンロードします。
# check version
docker --version
# pull an image
docker pull nginx:latest
# run a container
docker run -d --name mynginx -p 8080:80 nginx
# list running containers
docker ps
# list all containers (including stopped)
docker ps -a
# stop and remove a container
docker stop mynginx
docker rm mynginx
# list images
docker imagesコンテナのライフサイクル
run は内部で create + start を行います。stop は SIGTERM を送り優雅な停止を促し、kill は即座に SIGKILL を送ります。pause は cgroup フリーザーを使い、プロセスを止めずにスナップショットを取るのに有用です。
# create a container without starting it
docker create --name web nginx
# start a created (or stopped) container
docker start web
# stop gracefully (SIGTERM then SIGKILL after 10s)
docker stop web
# force kill immediately
docker kill web
# restart a container
docker restart web
# pause/resume (freezes process with cgroups)
docker pause web
docker unpause webイメージの基本
イメージは読み取り専用 のレイヤーです。rmi はコンテナがまだそのイメージを参照していると失敗します — 先にコンテナを削除しましょう。history は各レイヤーを作った命令とサイズを表示し、ビルドの最適化に有用です。
# list local images
docker images
docker image ls
# remove an image
docker rmi nginx:latest
docker image rm nginx
# remove all dangling (untagged) images
docker image prune
# remove all unused images
docker image prune -a
# show image history (each layer)
docker history nginx:latestシステム情報
docker info はデーモンの設定(ストレージドライバ、ランタイム、レジストリ、swarm 状態)を表示します。system df は回収可能なスペースを明らかにします — 参照されないイメージや停止中のコンテナがディスクを浪費します。--format フラグは Go テンプレートで構造化出力を行います。
# docker system-wide info
docker info
docker version
# disk usage breakdown (images, containers, volumes)
docker system df
# detailed disk usage with reclaimable space
docker system df -v
# running containers count
docker ps -q | wc -l
# show docker root directory and storage driver
docker info --format '{{.DockerRootDir}} {{.Driver}}'クリーンアップと prune
prune は停止中/参照されないリソースを安全に削除します。system prune -a はどのコンテナからも参照されていないイメージも削除します。--volumes を加えると未使用のボリュームを削除します — データは取り返しがつきません。本番では慎重に使いましょう。
# remove stopped containers
docker container prune
# remove dangling images
docker image prune
# remove unused volumes (CAUTION: data loss)
docker volume prune
# remove unused networks
docker network prune
# remove everything unused at once
docker system prune
# also remove volumes (very aggressive)
docker system prune -a --volumesヘルプの使い方
Docker はコマンドを管理用の名前空間にグループ化します(docker image、docker container、docker network、docker volume)。旧形式(docker rmi)と新形式(docker image rm)のどちらも動きます。サブコマンドの --help でフラグと使用法が表示されます。
# list all commands
docker --help
docker help
# help for a specific command
docker run --help
docker image --help
# list management commands (grouped)
docker image --help
docker container --help
docker network --help
# show daemon config
docker info
# command reference online
# https://docs.docker.com/reference/イメージの管理
イメージの pull
タグは可変のラベルです — 同じタグが時期により異なるイメージを指すことがあります。再現可能なデプロイにはダイジェスト(@sha256:...)で固定しましょう。--platform で pull すると異なるアーキテクチャ用のイメージを取得でき、x86 ホスト上での ARM ビルドに有用です。
# pull latest tag
docker pull nginx
# pull specific tag
docker pull nginx:1.25-alpine
# pull all tags of a repository
docker pull -a alpine
# pull from a different registry
docker pull ghcr.io/user/repo:tag
# pull by digest (immutable, reproducible)
docker pull nginx@sha256:abc123...
# pull multiple platforms (multi-arch)
docker pull --platform linux/arm64 nginxイメージのビルド
最後の . がビルドコンテキストです — デーモンへ送られるファイルです。.dockerignore で小さく保つとビルドが速くなります。デバッグ時には --no-cache で新しいレイヤーを強制します。BuildKit を使うとマルチステージのキャッシュ、SSH マウント、シークレットのマウントが可能になります。
# build from Dockerfile in current dir, tag it
docker build -t myapp:1.0 .
# build with a different Dockerfile name
docker build -f Dockerfile.prod -t myapp:prod .
# build with build args
docker build --build-arg VERSION=1.2.3 -t myapp .
# build with no cache
docker build --no-cache -t myapp .
# build for a different platform
docker build --platform linux/arm64 -t myapp:arm .
# build using BuildKit (advanced features)
DOCKER_BUILDKIT=1 docker build -t myapp .イメージのタグ付け
タグは同じイメージ ID を指す別名です。よくあるワークフローは、バージョンタグでビルドし、latest とメジャーバージョンのタグを加えます。レジストリの URL でタグ付けすると、そのレジストリへの push の準備が整います。
# tag a local image
docker tag myapp:1.0 myapp:latest
# tag for pushing to Docker Hub
docker tag myapp:1.0 username/myapp:1.0
# tag for a private registry
docker tag myapp:1.0 registry.local:5000/myapp:1.0
# tag with multiple tags at once
docker tag myapp:1.0 myapp:stable
docker tag myapp:1.0 myapp:1
# tag by digest reference
docker tag myapp@sha256:abc... myapp:pinnedイメージの push
push の前に、イメージにレジストリの宛先でタグを付ける必要があります。push はレジストリにまだ存在しないレイヤーだけをアップロー ドします。自己署名証明書のプライベートレジストリでは、/etc/docker/daemon.json の insecure-registries に設定しましょう。
# login to Docker Hub
docker login
# login to a private registry
docker login registry.local:5000 -u user -p pass
# push to Docker Hub
docker push username/myapp:1.0
# push all tags in a repository
docker push -a username/myapp
# push to private registry
docker push registry.local:5000/myapp:1.0
# logout when done
docker logoutイメージの検査
inspect は詳細な JSON を返します:アーキテクチャ、OS、レイヤー、env、entrypoint、設定。history は各レイヤーのコマンドとサイズを明らかにします — イメージ最適化の基礎です。manifest inspect は pull せずにリモートレジストリを確認できます。
# low-level image metadata (JSON)
docker inspect nginx:latest
# specific field via Go template
docker inspect --format '{{.Arch}} {{.Os}}' nginx
# show image layers and sizes
docker history nginx:latest
# no-trunc to see full command for each layer
docker history --no-trunc nginx:latest
# inspect an image in a registry (manifest)
docker manifest inspect nginx:latestイメージの保存と読み込み
save/load はイメージのレイヤーと履歴を保持します — イメージをオフラインで転送する正しい選択です。export/import は単一レイヤーへ平坦化し、履歴を失います。オンライン転送には tar ファイルよりレジストリの push/pull を推奨します。
# save an image to a tar file
docker save -o myapp.tar myapp:1.0
# save multiple images
docker save -o bundle.tar myapp:1.0 nginx:latest
# load an image from a tar file
docker load -i myapp.tar
# pipe between hosts (no intermediate file)
docker save myapp:1.0 | gzip | ssh host 'gunzip | docker load'
# export a container filesystem (not an image)
docker export mycontainer | gzip > fs.tar.gzコンテナの管理
コンテナの実行
-it は -i(stdin を開いたまま)と -t(tty を割り当て)を組み合わせ、対話セッションにします。--rm は終了後の後始末をします — 1 回限りのコマンドに最適です。--restart unless-stopped は再起動に耐えつつ、手動の停止は尊重します。
# run in background with a name and port mapping
docker run -d --name web -p 8080:80 nginx
# run interactively with a terminal
docker run -it --name shell alpine sh
# run and auto-remove on exit
docker run --rm alpine echo hello
# run with a volume
docker run -d -v mydata:/data alpine
# run with environment variables
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# run with a restart policy
docker run -d --restart unless-stopped nginxコマンドの実行(exec)
exec は既に稼働中のコンテナ内で新しいプロセスを実行します — 元の entrypoint は動き続けます。デバッグ、管理作業、1 回限りのスクリプト実行に使いましょう。デフォルトのユーザーはイメージの USER です。-u で上書きできます。
# open an interactive shell in a running container
docker exec -it web sh
# run a command and return
docker exec web ls /usr/share/nginx/html
# run as a specific user
docker exec -u root web whoami
# set environment variables for the command
docker exec -e DEBUG=1 web env
# run with a working directory
docker exec -w /tmp web pwd
# run as detached (rarely useful)
docker exec -d web touch /tmp/markerログの表示
logs はコンテナのロギングドライバが取り込んだ stdout/stderr を表示します。docker logs と統合するため、アプリはファイルではなく stdout へログを書くべきです。--since/--until は RFC3339 のタイムスタンプか Go の期間(30m、2h)を受け付けます。