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-alpineStart 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:80publishes on the loopback only, so nothing outside the machine reaches it.docker run -it --rm alpine:3.22 shOpen a shell in a throwaway container:
-itgives it your terminal,--rmremoves it when you exit.docker run --rm -e APP_ENV=prod --env-file .env myapp:1.4Set environment variables one at a time with
-e, or read them from a file ofKEY=valuelines with--env-file.Warning:
docker run --env-filekeeps quotes as part of the value: writeKEY=value, notKEY="value".docker run -d --init --restart unless-stopped --name worker myapp:1.4Run 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],alwaysandunless-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 ciRun 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.4Cap the container at 512 MiB of memory and one and a half CPUs.
docker run --rm --platform linux/amd64 alpine:3.22 uname -mRun an image built for another architecture, through emulation if the host has it.
docker run -d --read-only --tmpfs /tmp --name api myapp:1.4Make 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--tmpfsor a volume for each such path.
Manage containers
List, stop, start, remove and get inside the containers you have.
docker ps -aList every container, stopped ones included; without
-aonly 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.4Show only the containers that match: here the stopped ones made from
myapp:1.4.docker stop -t 30 webSend
SIGTERM, wait up to 30 seconds, thenSIGKILL. The default wait is 10 seconds.docker start -ai webStart a stopped container again, attached to its output and input.
docker restart webStop and start a container, keeping its configuration and writable layer.
docker rm -f webRemove 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 shOpen a shell in a running container. Use
bashwhere the image has it.docker exec -u root -w /etc web cat os-releaseRun one command in a running container, as another user and from another directory.
docker cp web:/etc/nginx/nginx.conf ./nginx.confCopy 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-oldGive a container a new name.
docker update --restart unless-stopped -m 1g webChange 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 webShow the last 100 lines of a container's output and keep following it.
docker logs --since 15m -t webShow the last 15 minutes of output, each line with its timestamp.
--sincealso takes a date.docker inspect webPrint 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}}' webPick 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}}' webPrint the container's address on each network it is attached to.
docker inspect -f '{{json .State.Health}}' webShow a container's health status and the output of its last checks, as JSON.
docker stats --no-streamPrint each running container's CPU, memory, network and disk use once, instead of a live view.
docker top webList the processes running in a container, as
pson the host sees them.docker port webShow which host ports a container's ports are published on.
docker diff webList the files a container added (
A), changed (C) or deleted (D) since it started from its image.docker events --filter container=web --since 1hShow what the daemon did to a container in the last hour (create, start, die, kill), then keep watching.
docker wait webBlock 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 lsList local images with their tag, ID, age and size.
docker imagesis the same command.docker image ls --treeList 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 -qPrint only the IDs of untagged images, the leftovers of rebuilds.
docker pull postgres:18Download an image, or update the local copy of a tag that moved.
docker pull --platform linux/arm64 postgres:18Download the variant of an image for another platform than the host's.
docker tag myapp:1.4 registry.example.com/team/myapp:1.4Give 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.4Upload an image to the registry its name points at.
echo "$REGISTRY_TOKEN" | docker login registry.example.com -u ci --password-stdinLog 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.comremoves the stored credentials.docker image rm myapp:1.3Remove a tag, and the image once no tag or container uses it.
docker rmiis the same command.docker image history --no-trunc myapp:1.4Show the layers of an image and the instruction that made each one, with their sizes.
docker save -o myapp.tar myapp:1.4Write an image, with its layers and tags, to a tar file to move it without a registry.
docker load -i myapp.tarRead an image back from a tar file written by
docker save.docker buildx imagetools inspect nginx:1.30-alpineShow 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
Dockerfilein 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
ARGthe 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=secretreads 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.logPrint 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-containerbuilder fromdocker buildx create.docker buildx lsList 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 cilayer.Tip: Keep a
.dockerignorewithnode_modulesand.git, or the build context carries them to the builder.
Volumes and mounts
Keep data outside a container's writable layer.
docker volume create pgdataMake a named volume, managed by Docker, which outlives any container that uses it.
docker volume lsList volumes.
--filter dangling=trueshows those no container uses.docker volume inspect pgdataShow 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:18Mount a named volume at a path in the container. A name that does not exist yet is created.
Warning: From
postgres:18the image keeps its data under/var/lib/postgresql: a volume on the older.../datapath is not the one it writes to.docker run --rm -v "$PWD"/config:/etc/app:ro myapp:1.4Bind-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.4The 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.4Mount 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 pgdataRemove 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 appnetMake 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:18Start a container on a network. Another container there reaches it as
db, here on port 5432.Tip: Ports do not need
-pfor containers on the same network: publish only what the host must reach.docker run --rm --network appnet alpine:3.22 nslookup dbCheck that a name resolves from inside the network, through Docker's embedded DNS.
docker network connect --alias cache appnet redisAttach a running container to another network, under an extra name there.
docker network disconnect appnet redisDetach a container from a network without stopping it.
docker network lsList networks:
bridge,hostandnoneare 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 backendMake 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-alpineShare 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 appnetRemove 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.yamlin the current directory, as a project named after the directory, unless-for-psays otherwise.docker compose up -dCreate and start every service in the background, recreating only those whose configuration changed.
docker compose up -d --build --waitRebuild the images that have a
build:, start everything, and return only once each service is running or healthy.Tip:
--wait-timeout 120gives up after two minutes, with a failing exit code: what a CI job wants.docker compose up -d --no-deps --force-recreate webRecreate one service without touching the services it depends on.
docker compose downStop and remove the project's containers and networks. Volumes and images are kept.
docker compose down -v --remove-orphansAlso remove the project's volumes, and containers of services no longer in the file.
Warning:
-vdeletes the named volumes the file declares: a database's data goes with it.docker compose ps -aList the project's containers, with their state, health and ports;
-aincludes stopped ones.docker compose logs -f -n 50 web workerFollow the output of some services, each line prefixed by its container's name.
docker compose exec db psql -U postgresRun a command in a service's running container. Add
-Tin a script with no terminal.docker compose run --rm web npm run migrateRun a one-off command in a new container of a service, with its configuration, and remove it after.
docker compose pullFetch newer images for every service that names one;
up -dthen recreates those that changed.docker compose configPrint the configuration as Compose resolves it: files merged, variables substituted, paths made absolute.
Tip:
docker compose config -qonly validates, and--serviceslists the service names.docker compose -f compose.yaml -f compose.prod.yaml up -dMerge several files in order, each later one overriding the earlier ones.
docker compose --profile debug up -dAlso start the services that list
debugunderprofiles:; services without a profile always start.docker compose watchStart the project and sync or rebuild services as files change, by the
develop.watchrules in the file.docker compose up -d --scale worker=3Run three containers of one service. A service with a fixed host port or
container_namecannot 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 dfShow how much space images, containers, local volumes and the build cache take, and how much of it could be reclaimed.
Tip:
-vbreaks it down per image, container and volume.docker container pruneRemove every stopped container, after asking.
-fskips the question.docker image pruneRemove dangling images: those with no tag and no container using them.
docker image prune -a --filter until=168hRemove every image no container uses, tagged or not, if it was created more than a week ago.
docker builder pruneEmpty the build cache of the builder in use. It is often the largest line in
docker system df.Tip:
--max-used-space 10gbtrims the cache down to that size instead of emptying it.docker volume pruneRemove anonymous volumes that no container uses. Named volumes are kept.
docker volume prune -aRemove every volume no container uses, named ones included.
Warning: A database whose container you removed loses its data here, with no undo.
docker network pruneRemove user-defined networks that no container is attached to.
docker system pruneRemove stopped containers, unused networks, dangling images and the dangling build cache in one go.
docker system prune -a --volumesAlso 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 -aremoves those.
Contexts and system
Which daemon you talk to, and what it reports about itself.
docker versionShow the versions of the client and of the daemon it talks to, which may differ.
docker infoShow 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 infowith a Go template.docker context lsList the daemons this client knows; the one marked
*receives every command.docker context create staging --docker host=ssh://deploy@staging.example.comAdd a context for a remote daemon reached over SSH, with no port opened on it.
docker context use stagingSend every later command to that daemon, until you switch back with
docker context use default.docker --context staging psSend one command to another context without switching.
DOCKER_CONTEXT=stagingdoes the same for a shell.docker compose versionShow the Compose plugin's version;
docker buildx versiondoes the same for Buildx.
Pitfalls
What goes wrong, what it looks like, and how to get out of it.
docker stoptakes ten seconds every time, and the app never logs a clean shutdown.Fix: PID 1 ignores
SIGTERMunless 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
arm64on anamd64server. Build for the target with--platform linux/amd64, or for both platforms at once, and check withdocker buildx imagetools inspect.A token passed to the build can be read back with
docker image historyor from a layer.Fix: Build arguments and copied files stay in the image. Pass it with
--secretand read it inRUN --mount=type=secret, which mounts it for that step only; then rotate the token that leaked.After editing
compose.yaml,docker compose restartruns the old configuration.Fix:
restartonly stops and starts the existing containers. Rundocker compose up -d, which recreates the services whose configuration changed.The app starts before its database accepts connections and crashes, though it
depends_onit.Fix: A bare
depends_onwaits for the container to start, not to be ready. Give the database ahealthcheckand writedepends_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:5432is reachable from the internet despite the host's firewall rules.Fix: Docker writes its own rules ahead of a firewall such as
ufw, for0.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
localhostis the container itself. Use the other container's name on a shared network (db:5432), orhost.docker.internalfor 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 -ashows few containers.Fix: The build cache, old images and unused volumes add up. Run
docker system dfto see which, thendocker builder pruneordocker image prune -a; a container's own logs can grow too, so set--log-opt max-size=10m.