---
title: "Docker cheat sheet"
description: "Docker 29 and Compose v5 commands with one line each: containers, images, BuildKit builds, volumes, networks, Compose, cleanup and the pitfalls that bite."
url: "https://opsfolk.com/cheat-sheets/docker"
category: "DevOps"
tag: "Docker"
checked_on: "Docker Engine 29.9, Compose v5.6, Buildx v0.38"
reviewed: "2026-11-21"
updated: "2026-11-20T23:53:15.087Z"
sections: 11
entries: 121
---

# Docker cheat sheet

The Docker Engine, BuildKit and Compose commands you reach for every day, from running a container to reclaiming disk space, checked on Docker 29.9 and Compose v5.6.

Checked on Docker Engine 29.9, Compose v5.6, Buildx v0.38, reviewed 2026-11-21.

Names such as `web`, `app`, `db` and `myapp` are examples: put your own container, service or image there. Compose is the `docker compose` plugin (v2 and later, now v5), not the old `docker-compose` binary, and it reads `compose.yaml` from the current directory.

## Run containers

Start a container from an image, with the options you set most often.

```bash
docker run -d --name web -p 8080:80 nginx:1.30-alpine
```

Start nginx in the background as `web`, with the host's port 8080 sent to the container's port 80.

- Tip: `-p 127.0.0.1:8080:80` publishes on the loopback only, so nothing outside the machine reaches it.

```bash
docker run -it --rm alpine:3.22 sh
```

Open a shell in a throwaway container: `-it` gives it your terminal, `--rm` removes it when you exit.

```bash
docker run --rm -e APP_ENV=prod --env-file .env myapp:1.4
```

Set environment variables one at a time with `-e`, or read them from a file of `KEY=value` lines with `--env-file`.

- Warning: `docker run --env-file` keeps quotes as part of the value: write `KEY=value`, not `KEY="value"`.

```bash
docker run -d --init --restart unless-stopped --name worker myapp:1.4
```

Run with a small init as PID 1, which forwards signals and reaps zombies, and restart it unless you stopped it yourself.

- Tip: Restart policies: `no` (the default), `on-failure[:N]`, `always` and `unless-stopped`.

```bash
docker run --rm --entrypoint sh myapp:1.4 -c 'ls -la /app'
```

Replace the image's `ENTRYPOINT`; what follows the image name becomes its arguments.

```bash
docker run --rm -v "$PWD":/src -w /src -u "$(id -u):$(id -g)" node:24-alpine npm ci
```

Run a tool on the current directory as your own user, so the files it writes are not owned by root.

```bash
docker run -d --name api -m 512m --cpus 1.5 myapp:1.4
```

Cap the container at 512 MiB of memory and one and a half CPUs.

```bash
docker run --rm --platform linux/amd64 alpine:3.22 uname -m
```

Run an image built for another architecture, through emulation if the host has it.

```bash
docker run -d --read-only --tmpfs /tmp --name api myapp:1.4
```

Make the container's filesystem read-only, with a writable in-memory `/tmp`, so a compromised process cannot change its own binaries.

- Tip: An image that writes elsewhere, as nginx does to `/var/cache/nginx`, needs a `--tmpfs` or a volume for each such path.

## Manage containers

List, stop, start, remove and get inside the containers you have.

```bash
docker ps -a
```

List every container, stopped ones included; without `-a` only running ones are shown.

```bash
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
```

Choose the columns with a Go template: here the name, the status and the published ports.

Example:

```
NAMES     STATUS          PORTS
web       Up 3 minutes    0.0.0.0:8080->80/tcp
worker    Up 10 seconds
```

```bash
docker ps -a --filter status=exited --filter ancestor=myapp:1.4
```

Show only the containers that match: here the stopped ones made from `myapp:1.4`.

```bash
docker stop -t 30 web
```

Send `SIGTERM`, wait up to 30 seconds, then `SIGKILL`. The default wait is 10 seconds.

```bash
docker start -ai web
```

Start a stopped container again, attached to its output and input.

```bash
docker restart web
```

Stop and start a container, keeping its configuration and writable layer.

```bash
docker rm -f web
```

Remove a container, killing it first if it is running.

- Warning: What the container wrote outside a volume is gone with it.

```bash
docker exec -it web sh
```

Open a shell in a running container. Use `bash` where the image has it.

```bash
docker exec -u root -w /etc web cat os-release
```

Run one command in a running container, as another user and from another directory.

```bash
docker cp web:/etc/nginx/nginx.conf ./nginx.conf
```

Copy a file out of a container to the host. The container does not have to be running.

```bash
docker cp ./site/. web:/usr/share/nginx/html/
```

Copy a directory's contents from the host into a container; the trailing `/.` copies what is inside, not the directory.

```bash
docker rename web web-old
```

Give a container a new name.

```bash
docker update --restart unless-stopped -m 1g web
```

Change a running container's restart policy and memory limit without recreating it.

## Inspect and debug

Logs, configuration, resource use and what changed inside a container.

```bash
docker logs -f -n 100 web
```

Show the last 100 lines of a container's output and keep following it.

```bash
docker logs --since 15m -t web
```

Show the last 15 minutes of output, each line with its timestamp. `--since` also takes a date.

```bash
docker inspect web
```

Print a container's whole configuration and state as JSON. It works on images, volumes and networks too.

```bash
docker inspect -f '{{.State.Status}} {{.State.ExitCode}} {{.RestartCount}}' web
```

Pick fields out of the JSON with a Go template: here the state, the last exit code and the restart count.

```bash
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' web
```

Print the container's address on each network it is attached to.

```bash
docker inspect -f '{{json .State.Health}}' web
```

Show a container's health status and the output of its last checks, as JSON.

```bash
docker stats --no-stream
```

Print each running container's CPU, memory, network and disk use once, instead of a live view.

```bash
docker top web
```

List the processes running in a container, as `ps` on the host sees them.

```bash
docker port web
```

Show which host ports a container's ports are published on.

```bash
docker diff web
```

List the files a container added (`A`), changed (`C`) or deleted (`D`) since it started from its image.

```bash
docker events --filter container=web --since 1h
```

Show what the daemon did to a container in the last hour (create, start, die, kill), then keep watching.

```bash
docker wait web
```

Block until a container stops, then print its exit code. Handy in a script.

## Images

List, pull, tag, push, export and look inside images.

```bash
docker image ls
```

List local images with their tag, ID, age and size. `docker images` is the same command.

```bash
docker image ls --tree
```

List multi-platform images as a tree of the platforms each one holds locally.

- Warning: Marked experimental in Docker 29: its output can change between releases.

```bash
docker image ls --filter dangling=true -q
```

Print only the IDs of untagged images, the leftovers of rebuilds.

```bash
docker pull postgres:18
```

Download an image, or update the local copy of a tag that moved.

```bash
docker pull --platform linux/arm64 postgres:18
```

Download the variant of an image for another platform than the host's.

```bash
docker tag myapp:1.4 registry.example.com/team/myapp:1.4
```

Give an image a second name, here the one a push to a private registry needs. Nothing is copied.

```bash
docker push registry.example.com/team/myapp:1.4
```

Upload an image to the registry its name points at.

```bash
echo "$REGISTRY_TOKEN" | docker login registry.example.com -u ci --password-stdin
```

Log in to a registry with a token read from standard input, so it is not in your shell's history.

- Tip: `docker logout registry.example.com` removes the stored credentials.

```bash
docker image rm myapp:1.3
```

Remove a tag, and the image once no tag or container uses it. `docker rmi` is the same command.

```bash
docker image history --no-trunc myapp:1.4
```

Show the layers of an image and the instruction that made each one, with their sizes.

```bash
docker save -o myapp.tar myapp:1.4
```

Write an image, with its layers and tags, to a tar file to move it without a registry.

```bash
docker load -i myapp.tar
```

Read an image back from a tar file written by `docker save`.

```bash
docker buildx imagetools inspect nginx:1.30-alpine
```

Show the platforms and digests behind a tag in its registry, without pulling it.

## Build

Build images with BuildKit, including multi-stage and multi-platform builds.

```bash
docker build -t myapp:1.4 .
```

Build the `Dockerfile` in the current directory, with that directory as the build context, and tag the result.

```bash
docker build -f docker/Dockerfile.prod -t myapp:1.4-prod .
```

Build from a Dockerfile elsewhere; the context is still the last argument.

```bash
docker build --target test -t myapp:test .
```

Build a multi-stage Dockerfile only up to the stage named `test`.

```bash
docker build --build-arg NODE_VERSION=24 -t myapp:1.4 .
```

Set an `ARG` the Dockerfile declares, for this build.

- Warning: A build argument is kept in the image's history: never pass a password or a token this way.

```bash
docker build --secret id=npm_token,env=NPM_TOKEN -t myapp:1.4 .
```

Hand the build a secret from an environment variable; a `RUN --mount=type=secret` reads it and no layer keeps it.

```bash
docker build --pull --no-cache -t myapp:1.4 .
```

Fetch a fresh base image and rebuild every step, ignoring the cache.

```bash
docker build --progress plain -t myapp:1.4 . 2>&1 | tee build.log
```

Print every step's full output as plain text instead of the collapsing view, here also into a file.

```bash
docker build --platform linux/amd64,linux/arm64 -t registry.example.com/team/myapp:1.4 --push .
```

Build one image for two architectures and push both under one tag.

- Tip: This needs a builder that can store multi-platform images: the containerd image store, or a `docker-container` builder from `docker buildx create`.

```bash
docker buildx ls
```

List the builders and the platforms each can build for; the one marked `*` is in use.

### Dockerfile

```dockerfile
# syntax=docker/dockerfile:1
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm \
    --mount=type=secret,id=npm_token,env=NPM_TOKEN \
    npm ci --omit=dev

FROM node:24-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
USER node
EXPOSE 3000
CMD ["node", "server.js"]
```

A multi-stage build for a Node app: dependencies cached between builds, a secret that no layer keeps, and a final image that runs as a non-root user.

- Tip: Copy the lock file before the rest of the source, so a code change does not throw away the cached `npm ci` layer.
- Tip: Keep a `.dockerignore` with `node_modules` and `.git`, or the build context carries them to the builder.

## Volumes and mounts

Keep data outside a container's writable layer.

```bash
docker volume create pgdata
```

Make a named volume, managed by Docker, which outlives any container that uses it.

```bash
docker volume ls
```

List volumes. `--filter dangling=true` shows those no container uses.

```bash
docker volume inspect pgdata
```

Show a volume's driver, labels and where its data lives on the host.

```bash
docker run -d --name db -e POSTGRES_PASSWORD=dev -v pgdata:/var/lib/postgresql postgres:18
```

Mount a named volume at a path in the container. A name that does not exist yet is created.

- Warning: From `postgres:18` the image keeps its data under `/var/lib/postgresql`: a volume on the older `.../data` path is not the one it writes to.

```bash
docker run --rm -v "$PWD"/config:/etc/app:ro myapp:1.4
```

Bind-mount a host directory, read-only with `:ro`. A path that starts with `/` or `.` is a bind mount, a bare name a volume.

```bash
docker run --rm --mount type=bind,src="$PWD"/config,dst=/etc/app,readonly myapp:1.4
```

The same bind mount, written as `--mount`: longer, and it refuses a host path that does not exist instead of creating it.

```bash
docker run --rm --tmpfs /app/cache:size=64m myapp:1.4
```

Mount an in-memory filesystem, gone when the container stops, capped at 64 MiB.

```bash
docker run --rm -v pgdata:/data:ro -v "$PWD":/backup alpine:3.22 tar czf /backup/pgdata.tgz -C /data .
```

Back a volume up to a tarball in the current directory, with a throwaway container that mounts both.

- Warning: Stop the database first, or the copy may not be consistent.

```bash
docker volume rm pgdata
```

Remove a volume and its data. It is refused while a container, even a stopped one, uses it.

## Networks

Let containers find each other by name, and keep others apart.

```bash
docker network create appnet
```

Make a user-defined bridge network. Containers on it reach each other by name, which the default bridge does not do.

```bash
docker run -d --name db --network appnet -e POSTGRES_PASSWORD=dev postgres:18
```

Start a container on a network. Another container there reaches it as `db`, here on port 5432.

- Tip: Ports do not need `-p` for containers on the same network: publish only what the host must reach.

```bash
docker run --rm --network appnet alpine:3.22 nslookup db
```

Check that a name resolves from inside the network, through Docker's embedded DNS.

```bash
docker network connect --alias cache appnet redis
```

Attach a running container to another network, under an extra name there.

```bash
docker network disconnect appnet redis
```

Detach a container from a network without stopping it.

```bash
docker network ls
```

List networks: `bridge`, `host` and `none` are always there.

```bash
docker network inspect appnet -f '{{range .Containers}}{{.Name}} {{.IPv4Address}}{{println}}{{end}}'
```

List the containers on a network and their addresses.

```bash
docker network create --internal backend
```

Make a network with no route out: containers on it talk to each other and not to the internet.

```bash
docker run --rm --network host nginx:1.30-alpine
```

Share the host's network stack: no port mapping, the container listens on the host's own ports.

- Warning: Docker Desktop supports it only once host networking is turned on in its settings; on Linux it always works.

```bash
docker network rm appnet
```

Remove a network. It is refused while a container is attached to it.

## Docker Compose

Run a project of several services from one compose.yaml.

> Every command here runs against `compose.yaml` in the current directory, as a project named after the directory, unless `-f` or `-p` says otherwise.

```bash
docker compose up -d
```

Create and start every service in the background, recreating only those whose configuration changed.

```bash
docker compose up -d --build --wait
```

Rebuild the images that have a `build:`, start everything, and return only once each service is running or healthy.

- Tip: `--wait-timeout 120` gives up after two minutes, with a failing exit code: what a CI job wants.

```bash
docker compose up -d --no-deps --force-recreate web
```

Recreate one service without touching the services it depends on.

```bash
docker compose down
```

Stop and remove the project's containers and networks. Volumes and images are kept.

```bash
docker compose down -v --remove-orphans
```

Also remove the project's volumes, and containers of services no longer in the file.

- Warning: `-v` deletes the named volumes the file declares: a database's data goes with it.

```bash
docker compose ps -a
```

List the project's containers, with their state, health and ports; `-a` includes stopped ones.

```bash
docker compose logs -f -n 50 web worker
```

Follow the output of some services, each line prefixed by its container's name.

```bash
docker compose exec db psql -U postgres
```

Run a command in a service's running container. Add `-T` in a script with no terminal.

```bash
docker compose run --rm web npm run migrate
```

Run a one-off command in a new container of a service, with its configuration, and remove it after.

```bash
docker compose pull
```

Fetch newer images for every service that names one; `up -d` then recreates those that changed.

```bash
docker compose config
```

Print the configuration as Compose resolves it: files merged, variables substituted, paths made absolute.

- Tip: `docker compose config -q` only validates, and `--services` lists the service names.

```bash
docker compose -f compose.yaml -f compose.prod.yaml up -d
```

Merge several files in order, each later one overriding the earlier ones.

```bash
docker compose --profile debug up -d
```

Also start the services that list `debug` under `profiles:`; services without a profile always start.

```bash
docker compose watch
```

Start the project and sync or rebuild services as files change, by the `develop.watch` rules in the file.

```bash
docker compose up -d --scale worker=3
```

Run three containers of one service. A service with a fixed host port or `container_name` cannot be scaled.

### compose.yaml

```yaml
services:
  web:
    build: .
    ports:
      - "127.0.0.1:3000:3000"
    environment:
      DATABASE_URL: postgres://postgres:dev@db:5432/app
    depends_on:
      db:
        condition: service_healthy
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: package.json

  db:
    image: postgres:18
    environment:
      POSTGRES_PASSWORD: dev
      POSTGRES_DB: app
    volumes:
      - pgdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d app"]
      interval: 5s
      timeout: 3s
      retries: 10
      start_period: 10s

volumes:
  pgdata:
```

A web service that waits for its database to be healthy, with the database's data in a named volume and only the web port published.

- Tip: The file needs no `version:` line: Compose v2 and later ignore it, with a warning.

## Clean up and disk use

See what takes space and remove what nothing uses.

```bash
docker system df
```

Show how much space images, containers, local volumes and the build cache take, and how much of it could be reclaimed.

- Tip: `-v` breaks it down per image, container and volume.

```bash
docker container prune
```

Remove every stopped container, after asking. `-f` skips the question.

```bash
docker image prune
```

Remove dangling images: those with no tag and no container using them.

```bash
docker image prune -a --filter until=168h
```

Remove every image no container uses, tagged or not, if it was created more than a week ago.

```bash
docker builder prune
```

Empty the build cache of the builder in use. It is often the largest line in `docker system df`.

- Tip: `--max-used-space 10gb` trims the cache down to that size instead of emptying it.

```bash
docker volume prune
```

Remove anonymous volumes that no container uses. Named volumes are kept.

```bash
docker volume prune -a
```

Remove every volume no container uses, named ones included.

- Warning: A database whose container you removed loses its data here, with no undo.

```bash
docker network prune
```

Remove user-defined networks that no container is attached to.

```bash
docker system prune
```

Remove stopped containers, unused networks, dangling images and the dangling build cache in one go.

```bash
docker system prune -a --volumes
```

Also remove every unused image and the anonymous volumes no container uses: the closest to starting over.

- Warning: Every image must be pulled or built again afterwards. Named volumes stay: `docker volume prune -a` removes those.

## Contexts and system

Which daemon you talk to, and what it reports about itself.

```bash
docker version
```

Show the versions of the client and of the daemon it talks to, which may differ.

```bash
docker info
```

Show the daemon's configuration: storage driver, image store, counts of containers and images, registries, warnings.

```bash
docker info -f '{{.ServerVersion}} {{.OperatingSystem}} {{.Architecture}}'
```

Pick a few fields out of `docker info` with a Go template.

```bash
docker context ls
```

List the daemons this client knows; the one marked `*` receives every command.

```bash
docker context create staging --docker host=ssh://deploy@staging.example.com
```

Add a context for a remote daemon reached over SSH, with no port opened on it.

```bash
docker context use staging
```

Send every later command to that daemon, until you switch back with `docker context use default`.

```bash
docker --context staging ps
```

Send one command to another context without switching. `DOCKER_CONTEXT=staging` does the same for a shell.

```bash
docker compose version
```

Show the Compose plugin's version; `docker buildx version` does the same for Buildx.

## Pitfalls

What goes wrong, what it looks like, and how to get out of it.

**Problem:** `docker stop` takes ten seconds every time, and the app never logs a clean shutdown.

**Fix:** PID 1 ignores `SIGTERM` unless it handles it. Use the exec form, `CMD ["node", "server.js"]`, not the shell form, so your process is PID 1 and gets the signal; or run with `--init` (Compose: `init: true`).

**Problem:** A container exits at once with `exec format error`.

**Fix:** The image was built for another CPU architecture, such as `arm64` on an `amd64` server. Build for the target with `--platform linux/amd64`, or for both platforms at once, and check with `docker buildx imagetools inspect`.

**Problem:** A token passed to the build can be read back with `docker image history` or from a layer.

**Fix:** Build arguments and copied files stay in the image. Pass it with `--secret` and read it in `RUN --mount=type=secret`, which mounts it for that step only; then rotate the token that leaked.

**Problem:** After editing `compose.yaml`, `docker compose restart` runs the old configuration.

**Fix:** `restart` only stops and starts the existing containers. Run `docker compose up -d`, which recreates the services whose configuration changed.

**Problem:** The app starts before its database accepts connections and crashes, though it `depends_on` it.

**Fix:** A bare `depends_on` waits for the container to start, not to be ready. Give the database a `healthcheck` and write `depends_on: { db: { condition: service_healthy } }`.

**Problem:** Files the image put in a directory are gone once a host directory is mounted there.

**Fix:** A bind mount hides what the image had at that path. Mount somewhere else, or use a named volume, which an empty volume fills from the image's files the first time.

**Problem:** A port published with `-p 5432:5432` is reachable from the internet despite the host's firewall rules.

**Fix:** Docker writes its own rules ahead of a firewall such as `ufw`, for `0.0.0.0`. Publish on the loopback, `-p 127.0.0.1:5432:5432`, or do not publish a port that only other containers need.

**Problem:** The app cannot reach a service on `localhost:5432`, though it runs.

**Fix:** Inside a container `localhost` is the container itself. Use the other container's name on a shared network (`db:5432`), or `host.docker.internal` for a service on the host (Linux: `--add-host host.docker.internal:host-gateway`).

**Problem:** A changed `POSTGRES_PASSWORD` (or a MySQL root password) is ignored.

**Fix:** The image only reads it when its data directory is empty, on the first start. Change the password inside the database, or remove the volume to start from nothing, losing its data.

**Problem:** The disk fills up though `docker ps -a` shows few containers.

**Fix:** The build cache, old images and unused volumes add up. Run `docker system df` to see which, then `docker builder prune` or `docker image prune -a`; a container's own logs can grow too, so set `--log-opt max-size=10m`.
