Skip to content

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.

24 min read0/7 questions

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 servers

The 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.

Quick check
You built an image on an M-series Mac and pushed it. On the x86 production server, the container exits immediately with exec format error. What is the fix?
Need a nudge? A hint rules out a wrong answer.

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
FlagMeaning
-dDetached: run in the background and print the container ID.
--name apiA fixed name, so you can type docker logs api instead of an ID.
--rmDelete the container automatically when it exits. Great for one-off runs.
-p 8080:8000Publish: host port 8080 forwards to container port 8000.
-e KEY=valueSet one environment variable.
--env-file .envLoad many variables from a file on your machine (not baked into the image).
-v ./data:/app/dataMount a host folder into the container (next lesson).
-itInteractive with a terminal, for shells and REPLs.
--restart unless-stoppedRestart 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.

-p HOST:CONTAINER
Docker hostBrowser: localhostBrowserlocalhostHost :8080: -p 8080:80Host :8080-p 8080:80Host :8081: -p 8081:80Host :8081-p 8081:80web-a: listens :80web-alistens :80web-b: listens :80web-blistens :80:8080:8081→ :80→ :80

Two containers both listen on port 80. No conflict: each has its own network namespace.

1/4

Run this model of the host's port table. It shows why host ports must be unique and container ports need not be.

Pythonports.py
published: dict[int, tuple[str, int]] = {} def run(name: str, mapping: str) -> None: host, container = (int(p) for p in mapping.split(":")) if host in published: print(f"{name}: Bind for 0.0.0.0:{host} failed: port is already allocated") return published[host] = (name, container) print(f"{name}: started, host :{host} -> container :{container}") def request(host_port: int) -> None: target = published.get(host_port) print(f"GET localhost:{host_port} ->", f"{target[0]}:{target[1]}" if target else "connection refused") run("web-a", "8080:80")run("web-b", "8081:80")run("web-c", "8080:3000")request(8080)request(8081)request(9000)
Output
Press Run (⌘ Enter) to see what happens.
Quick check
You ran docker run -d -p 3000:8000 myapi:1.0. Uvicorn inside listens on 8000. Which URL works from your browser?
Need a nudge? A hint rules out a wrong answer.
Quick check
-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?
Need a nudge? A hint rules out a wrong answer.

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 container

docker 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.

Quick check
docker inspect api | jq ".State.ExitCode" fails with an error about indexing an array. Why?
Need a nudge? A hint rules out a wrong answer.

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, cache

Pruning 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 entry

Then 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.

Pythonprune_filters.py
images = [ # name, age in hours, labels, used by a container? {"name": "api:dev", "age": 2, "labels": {}, "in_use": True}, {"name": "api:old-branch", "age": 400, "labels": {}, "in_use": False}, {"name": "postgres:17", "age": 900, "labels": {"keep": "true"}, "in_use": False}, {"name": "ci-cache:main", "age": 30, "labels": {"team": "ci"}, "in_use": False}, {"name": "<none>:<none>", "age": 200, "labels": {}, "in_use": False},] def prune_all(until_hours: int, skip_label: str) -> None: print(f"docker image prune -a --filter until={until_hours}h --filter label!={skip_label}") for img in images: if img["in_use"]: reason = "kept: a container uses it" elif img["age"] < until_hours: reason = "kept: newer than the cutoff" elif skip_label in img["labels"]: reason = f"kept: has label {skip_label}" else: reason = "DELETED" print(f" {img['name']:<16} {reason}") prune_all(168, "keep")
Output
Press Run (⌘ Enter) to see what happens.

Volumes deserve their own rule, because volumes hold data, not rebuildable artefacts:

  • docker system prune does not touch volumes unless you add --volumes.
  • Since Docker Engine 23, docker volume prune removes only anonymous volumes by default. Named volumes, like your Postgres pgdata, need -a. Older guides that say "volume prune deletes everything unused" describe the old behaviour.
  • Before you delete a named volume, docker volume inspect shows its labels, and Compose-created volumes carry com.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.

Quick check
On Docker Engine 28, you run docker volume prune and confirm. Your Compose project's named volume shop_pgdata is not attached to any container. What happens to it?
Need a nudge? A hint rules out a wrong answer.

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 machine

Everything 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, a docker system prune -a you meant for your laptop runs on production. Prefer --context prod for 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 store

What changes in daily use:

  • Multi-platform images live locally. docker pull --platform and a multi-platform buildx --load work, and one tag can hold both linux/amd64 and linux/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 --tree on 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

TaskCommand
Build and tagdocker build -t name:tag .
Run in background, publisheddocker run -d --name n -p 8080:80 image
One-off run, auto-deletedocker run --rm -it image sh
List running / alldocker ps / docker ps -a
Follow logsdocker logs -f n
Shell in a running containerdocker exec -it n sh
Stop / start / removedocker stop n / docker start n / docker rm n
Tag for a registry and pushdocker tag image ghcr.io/me/app:1.0 then docker push ghcr.io/me/app:1.0
Free disk spacedocker 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 app

The 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 pairs0/5 matched

Match the exit code to its usual meaning.

Choose an item, then its match on the other side.
Put it in order4 steps

Put the debugging steps in a sensible order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeEasy

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.

def parse_port(spec: str) -> dict: # Split off an optional /protocol, then split the rest on ':'. pass
Key terms
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 --format uses 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.