Skip to content
Opsfolk
DevOps

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.

121 entries11 sectionsChecked on Docker Engine 29.9, Compose v5.6, Buildx v0.38Reviewed

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.

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

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

  • 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".

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

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

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

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

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

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

  • docker ps -a

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

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

  • docker stop -t 30 web

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

  • docker start -ai web

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

  • docker restart web

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

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

  • docker exec -it web sh

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

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

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

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

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

  • docker rename web web-old

    Give a container a new name.

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

  • docker logs -f -n 100 web

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

  • docker logs --since 15m -t web

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

  • docker inspect web

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

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

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

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

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

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

  • docker stats --no-stream

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

  • docker top web

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

  • docker port web

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

  • docker diff web

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

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

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

  • docker image ls

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

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

  • docker image ls --filter dangling=true -q

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

  • docker pull postgres:18

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

  • docker pull --platform linux/arm64 postgres:18

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

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

  • docker push registry.example.com/team/myapp:1.4

    Upload an image to the registry its name points at.

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

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

  • docker image history --no-trunc myapp:1.4

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

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

  • docker load -i myapp.tar

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

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

  • docker build -t myapp:1.4 .

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

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

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

  • docker build --target test -t myapp:test .

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

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

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

  • docker build --pull --no-cache -t myapp:1.4 .

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

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

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

  • docker buildx ls

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

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

  • docker volume create pgdata

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

  • docker volume ls

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

  • docker volume inspect pgdata

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

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

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

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

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

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

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

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

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

  • docker run --rm --network appnet alpine:3.22 nslookup db

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

  • docker network connect --alias cache appnet redis

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

  • docker network disconnect appnet redis

    Detach a container from a network without stopping it.

  • docker network ls

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

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

    List the containers on a network and their addresses.

  • docker network create --internal backend

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

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

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

  • docker compose up -d

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

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

  • docker compose up -d --no-deps --force-recreate web

    Recreate one service without touching the services it depends on.

  • docker compose down

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

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

  • docker compose ps -a

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

  • docker compose logs -f -n 50 web worker

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

  • docker compose exec db psql -U postgres

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

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

  • docker compose pull

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

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

  • docker compose -f compose.yaml -f compose.prod.yaml up -d

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

  • docker compose --profile debug up -d

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

  • docker compose watch

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

  • 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

    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.

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

  • docker container prune

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

  • docker image prune

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

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

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

  • docker volume prune

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

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

  • docker network prune

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

  • docker system prune

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

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

  • docker version

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

  • docker info

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

  • docker info -f '{{.ServerVersion}} {{.OperatingSystem}} {{.Architecture}}'

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

  • docker context ls

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

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

  • docker context use staging

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

  • docker --context staging ps

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

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

  • 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).

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

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

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

  • 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 } }.

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

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

  • 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).

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

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

Every cheat sheet