Lesson 4 of 24Containers
Docker CLI Essentials
Build, run, inspect, and clean up containers with the flags you will use daily, and debug one that keeps crashing.
You will spend more time typing docker commands than writing Dockerfiles. A handful of flags cover nearly everything, and knowing how to read an exit code and logs turns "the container just dies" into a two-minute fix instead of an afternoon.
Building with tags
docker build turns a Dockerfile and a build context into an image. The -t flag names it; you can pass it more than once.
docker build -t myapi:1.0 -t myapi:latest . # two tags, same imagedocker build -f Dockerfile.dev -t myapi:dev . # a different Dockerfiledocker build --build-arg PYTHON_VERSION=3.14 -t myapi:py314 .docker build --no-cache -t myapi:1.0 . # ignore the layer cachedocker build --platform linux/amd64 -t myapi:1.0 . # build for x86 serversThe last one matters more than it looks. A MacBook with Apple Silicon builds linux/arm64 images by default. Push that to an x86 server and the container fails with exec format error. Either build for the server's platform or build a multi-platform image with docker buildx build --platform linux/amd64,linux/arm64.
exec format error. What is the fix?Running: the flags that matter
docker run \ -d \ --name api \ --rm \ -p 8080:8000 \ -e LOG_LEVEL=debug \ --env-file .env \ -v ./data:/app/data \ myapi:1.0| Flag | Meaning |
|---|---|
-d | Detached: run in the background and print the container ID. |
--name api | A fixed name, so you can type docker logs api instead of an ID. |
--rm | Delete the container automatically when it exits. Great for one-off runs. |
-p 8080:8000 | Publish: host port 8080 forwards to container port 8000. |
-e KEY=value | Set one environment variable. |
--env-file .env | Load many variables from a file on your machine (not baked into the image). |
-v ./data:/app/data | Mount a host folder into the container (next lesson). |
-it | Interactive with a terminal, for shells and REPLs. |
--restart unless-stopped | Restart the container if it crashes or the host reboots. |
Flags go before the image name. Anything after the image name is passed to the container as its command, so docker run myapi:1.0 -d does not detach; it hands -d to your app.
Publishing ports
A container has its own network namespace, so its port 8000 is not your machine's port 8000. Publishing with -p HOST:CONTAINER asks Docker to forward traffic from a port on the host into the container. The order is always host first, container second.
Two containers both listen on port 80. No conflict: each has its own network namespace.
Run this model of the host's port table. It shows why host ports must be unique and container ports need not be.
Press Run (⌘ Enter) to see what happens.docker run -d -p 3000:8000 myapi:1.0. Uvicorn inside listens on 8000. Which URL works from your browser?-p 8000:8000 is set, but the browser gets connection reset. The container's CMD is uvicorn app.main:app --port 8000. What is wrong?Looking inside
docker ps # running containers, ports, statusdocker logs api # everything written to stdout/stderrdocker logs -f --tail 50 api # follow live, starting from the last 50 linesdocker exec -it api sh # a shell inside the running containerdocker exec api env # run one command and exitdocker inspect api # full JSON: config, mounts, network, statedocker inspect -f '{{.State.ExitCode}}' apidocker stats # live CPU and memory per containerdocker exec starts an extra process inside an existing container; it does not restart anything. Slim images often have sh but not bash. Distroless images have no shell at all, which is why the debugging trick below exists.
Output you can script
The default tables are for eyes. When you want one field, a narrower table, or input for a script, ask for it.
--format takes a Go template: text with {{.Field}} placeholders. Most listing commands accept it, and a table prefix keeps the header row and aligns the columns.
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'docker ps -a --filter status=exited --format '{{.Names}} {{.Status}}'docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}'docker ps -q # IDs only, one per linedocker ps --format json # one JSON object per line--filter narrows the list before formatting: status=exited, label=team=payments, ancestor=myapi:1.0 (containers started from that image), name=api. Combine filters by repeating the flag.
For anything deeper than one level, JSON plus a query tool is easier to read than a long template. docker inspect always prints a JSON array, even for one container, which is why the query starts with .[0]. jq is the usual tool on macOS and Linux; PowerShell has JSON parsing built in.
docker inspect api | jq '.[0].State | {Status, ExitCode, OOMKilled}'docker inspect api | jq -r '.[0].Config.Env[]'docker ps --format json | jq -r 'select(.Status | startswith("Exited")) | .Names'Debugging Containers lists the inspect fields worth knowing (.State.Error, .Config.Env, StartedAt). This section is about the habit: never scrape the human table with awk. Column widths change between versions, and a script that worked last year breaks quietly.
docker inspect api | jq ".State.ExitCode" fails with an error about indexing an array. Why?Cleaning up
Images and stopped containers pile up quickly. A few gigabytes a week is normal on an active laptop.
docker system df # what is using diskdocker container prune # remove all stopped containersdocker image prune # remove dangling (untagged) imagesdocker image prune -a # remove every image not used by a containerdocker builder prune # clear the build cachedocker system prune # stopped containers, unused networks, dangling images, cachePruning without regret
The commands above are blunt. On a shared build server or a laptop full of side projects, you want to remove old things and keep the ones that matter. Start by finding out what is actually big:
docker system df -v # per image, per container, per volume, per cache entryThen prune with filters. until takes a duration or a timestamp, and label (or label!=) matches labels set with LABEL in a Dockerfile or --label on docker run:
docker image prune -a --filter "until=168h" # unused and older than 7 daysdocker image prune -a --filter "until=168h" --filter "label!=keep" # ...except images labelled keepdocker container prune --filter "until=24h"docker builder prune --filter "until=72h"Run this model of the second command. The image in use, the recent one, and the labelled one survive.
Press Run (⌘ Enter) to see what happens.Volumes deserve their own rule, because volumes hold data, not rebuildable artefacts:
docker system prunedoes not touch volumes unless you add--volumes.- Since Docker Engine 23,
docker volume pruneremoves only anonymous volumes by default. Named volumes, like your Postgrespgdata, need-a. Older guides that say "volume prune deletes everything unused" describe the old behaviour. - Before you delete a named volume,
docker volume inspectshows its labels, and Compose-created volumes carrycom.docker.compose.project, which tells you whose data it is.
For the build cache, newer CLIs can cap its size instead of clearing it. The flag names have changed across releases, so check docker builder prune --help on your version.
docker volume prune and confirm. Your Compose project's named volume shop_pgdata is not attached to any container. What happens to it?Talking to another engine: docker context
The docker command is a client. It sends API calls to an engine, which is usually the one on your laptop but does not have to be. A context is a saved pointer to an engine, and SSH is the simplest transport because it needs nothing beyond the SSH access you already have.
docker context create prod --docker "host=ssh://deploy@prod.example.com"docker context ls # the active one has a *docker --context prod ps # one command against proddocker context use prod # switch every later commanddocker context use default # back to your machineEverything works through it: ps, logs, exec, compose up, even build, which sends the build context over the connection, so a large context is slow on a remote engine. The remote user must be allowed to use Docker there, usually by being in the docker group.
Two warnings from experience:
- Know where you are. After
docker context use prod, adocker system prune -ayou meant for your laptop runs on production. Prefer--context prodfor single commands, and show the context in your shell prompt if you switch often. - Docker access is root access. Anyone who can talk to an engine can start a container that mounts the host's
/. Granting someone an SSH context to a server is granting them root on it.
The DOCKER_HOST environment variable overrides the active context, and DOCKER_CONTEXT selects one by name. If commands go somewhere unexpected, check both. A CI job that sets DOCKER_HOST for a build service and a developer who forgot it in their shell profile is a classic mix-up.
The containerd image store
Docker can keep images in two different ways. The classic store holds one image per tag, for one platform. The containerd image store keeps images the way registries do: an index that can list several platforms, with each layer stored as content-addressed blobs. It is the default on Docker Desktop and on fresh installs of Docker Engine 29 or later. An engine upgraded from an older version may still use the classic store. Check with:
docker info -f '{{.DriverStatus}}' # mentions io.containerd.snapshotter on the containerd storeWhat changes in daily use:
- Multi-platform images live locally.
docker pull --platformand a multi-platformbuildx --loadwork, and one tag can hold bothlinux/amd64andlinux/arm64. Multi-Architecture Images, later in this track, explains the index itself. - Listings show more. Newer CLIs can show each platform variant under a tag (
docker image ls --treeon recent versions), and sizes may appear as two numbers: the unpacked size on disk and the compressed content size. The exact columns vary by version. - Disk use goes up. The store keeps both the compressed blobs and the unpacked layers, so the same set of images takes more space than under the classic store. Image Layers and the Build Cache covers why.
If a teammate's docker images looks different from yours, this is usually the reason, not a broken install.
Cheat sheet
| Task | Command |
|---|---|
| Build and tag | docker build -t name:tag . |
| Run in background, published | docker run -d --name n -p 8080:80 image |
| One-off run, auto-delete | docker run --rm -it image sh |
| List running / all | docker ps / docker ps -a |
| Follow logs | docker logs -f n |
| Shell in a running container | docker exec -it n sh |
| Stop / start / remove | docker stop n / docker start n / docker rm n |
| Tag for a registry and push | docker tag image ghcr.io/me/app:1.0 then docker push ghcr.io/me/app:1.0 |
| Free disk space | docker system prune |
Debugging a crashing container
The container starts and immediately exits. docker ps shows nothing. Here is the routine.
docker ps -a # STATUS: Exited (1) 3 seconds agodocker logs api # the traceback is almost always heredocker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}}' apidocker run --rm -it --entrypoint sh myapi:1.0 # same image, but a shell instead of the appThe last command is the key trick. --entrypoint sh replaces the start command, so the container does not crash and you can look around: is app/main.py really there? Is the env var set? Does python -c "import app.main" fail?
The exit code tells you what kind of death it was.
Match the exit code to its usual meaning.
Put the debugging steps in a sensible order.
- Tap the steps below in the right order.
Parse a port mapping
docker run -p and the ports: list in Compose use short strings like "8080:80". Write a function that parses one into an object with four keys: ip, host, container, protocol.
Formats to support:
"80" → { ip: null, host: null, container: 80, protocol: "tcp" }
"8080:80" → { ip: null, host: 8080, container: 80, protocol: "tcp" }
"127.0.0.1:5432:5432" → { ip: "127.0.0.1", host: 5432, container: 5432, protocol: "tcp" }
"53:53/udp" → { ip: null, host: 53, container: 53, protocol: "udp" }The protocol defaults to "tcp". Ports are integers. The container port is always the last number.
- publish (-p)
- Forward a host port to a container port:
-p HOST:CONTAINER. - detached (-d)
- Run the container in the background and return immediately.
- docker exec
- Start an extra process (like a shell) inside a running container.
- docker inspect
- Print a container's or image's full configuration and state as JSON.
- exit code 137
- 128 + 9: the process got SIGKILL, often from the out-of-memory killer.
- prune
- Commands that delete unused containers, images, networks, or build cache.
- Go template
- The
{{.Field}}syntax that--formatuses to pick and lay out fields. - docker context
- A saved connection to a Docker engine, local or remote over SSH, that the CLI sends commands to.
- containerd image store
- An image store that keeps registry-style indexes and blobs, so one tag can hold several platforms locally.