Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 111 ยท Practice

Docker Cheat Sheet

One-page Docker cheat sheet: commands grouped by task, Dockerfile instructions, Compose keys, format strings, exit codes and safe clean-up. Tested on Docker 29.

This page is a reference you can keep open next to your terminal. It groups the commands you use every day by the job you are doing, with short notes on the details that trip people up. Every command was run on Docker 29 with Compose v5; where output is shown, it is real. For explanations, follow the links to the lessons.

A tip for reading: most Docker commands exist in two spellings. The management form (docker container ls, docker image ls) is the modern, consistent one. The short legacy form (docker ps, docker images) still works and is what most people type (The Docker CLI).

Run a container

Terminal
docker run IMAGE                     # run a command, then exit when it ends
docker run -d IMAGE                  # detached (background)
docker run -it IMAGE sh              # interactive terminal
docker run --rm IMAGE                # delete the container when it exits
docker run --name web IMAGE          # choose the name (must be unique)
docker run -p 127.0.0.1:8080:80 IMAGE   # publish: host IP : host port : container port
docker run -e KEY=value IMAGE        # environment variable
docker run --env-file .env IMAGE     # many variables from a file
docker run -v mydata:/data IMAGE     # named volume
docker run -v "$PWD":/app IMAGE      # bind mount the current folder
docker run --network mynet IMAGE     # attach to a user-defined network
docker run --restart unless-stopped IMAGE
docker run --memory 256m --cpus 1.5 IMAGE
docker run --read-only --cap-drop ALL --security-opt no-new-privileges IMAGE
docker run --user 1000:1000 IMAGE
docker run --init IMAGE              # tiny init process as PID 1
docker run --entrypoint sh IMAGE     # replace the ENTRYPOINT

Everything after the image name is the command to run inside. Everything before it belongs to Docker, so docker run alpine:3 -d passes -d to the container, not to Docker. See Running Containers, Publishing Ports and Resource Limits.

Publish with -p 127.0.0.1:HOST:CONTAINER for anything that should be reachable from your own machine only. A bare -p 8080:80 listens on every network interface (Publishing Ports).

Inspect and observe

Terminal
docker ps                            # running containers
docker ps -a                         # all containers, including stopped
docker ps -q                         # only IDs (good for scripts)
docker logs -f --tail 100 NAME       # follow the last 100 lines
docker exec -it NAME sh              # shell in a running container
docker exec NAME COMMAND             # run one command
docker top NAME                      # processes inside
docker stats --no-stream             # one snapshot of CPU and memory
docker port NAME                     # published ports
docker diff NAME                     # files changed in the writable layer
docker inspect NAME                  # full JSON
docker events                        # live stream of daemon events

Real output from a container that was started with docker run -d --name web -p 127.0.0.1:18159:80 -e GREETING=hi nginx:alpine:

CONSOLE
$ docker ps --filter name=web --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'
NAMES   IMAGE          STATUS         PORTS
web     nginx:alpine   Up 3 seconds   127.0.0.1:18159->80/tcp
$ docker port web
80/tcp -> 127.0.0.1:18159
$ docker inspect -f '{{.State.Status}} {{.NetworkSettings.Ports}}' web
running map[80/tcp:[{127.0.0.1 18159}]]
$ docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.PIDs}}' web
web 0.00% 7
$ docker exec web nginx -v
nginx version: nginx/1.31.8

(The nginx version is whatever nginx:alpine currently contains.) The --format flag takes a Go template: {{.Names}} for columns, {{json .Config.Labels}} for a JSON value, {{range .Config.Env}}{{println .}}{{end}} to loop. Use table at the start of a template to get a header row. More in Listing and Inspecting.

Copy files and talk to running containers

CONSOLE
$ docker cp note.txt web:/tmp/note.txt
$ docker exec web cat /tmp/note.txt
hello
$ docker cp web:/etc/nginx/nginx.conf ./nginx-copy.conf

docker cp works in both directions and on stopped containers too. docker attach connects to the main process's streams (and Ctrl+P Ctrl+Q detaches without stopping it); prefer logs and exec for most jobs (Logs and exec).

Lifecycle

Terminal
docker create IMAGE         # create but do not start
docker start NAME           # start a stopped container
docker stop NAME            # SIGTERM, then SIGKILL after 10 s
docker stop -t 30 NAME      # wait up to 30 s
docker kill NAME            # SIGKILL immediately
docker restart NAME
docker pause NAME           # freeze all processes
docker unpause NAME
docker rename OLD NEW
docker rm NAME              # remove a stopped container
docker rm -f NAME           # stop and remove
docker rm -fv NAME          # ...and its anonymous volumes
docker wait NAME            # block until it exits, print the exit code

See The Container Lifecycle and Signals, PID 1 and --init.

Exit codes

When a container ends, its exit code tells you why. Check it with docker inspect -f '{{.State.ExitCode}}' NAME.

Code Meaning Seen when
0 Success The program finished normally
1 to 125 The program's own error code sh -c 'exit 3' gave 3
125 Docker itself failed An unknown flag such as docker run --bogus
126 Command found but not executable docker run alpine:3 /etc/passwd (permission denied)
127 Command not found docker run alpine:3 nosuchcmd
137 Killed by SIGKILL (128 + 9) docker kill, a stop that timed out, or the out-of-memory killer
139 Segmentation fault (128 + 11) A crash in native code
143 Ended by SIGTERM (128 + 15) A program that exits on docker stop without its own exit code

We checked these on Docker 29: 3, 125, 126 and 127 came from the commands in the table, docker kill gave 137, and a container limited to 8 MB that tried to allocate more also ended with 137. A plain sleep as PID 1 ignores SIGTERM, so docker stop waited for the timeout and also reported 137 (Debugging Containers).

Images

Terminal
docker pull nginx:alpine             # download
docker image ls                      # list (also: docker images)
docker image ls --filter dangling=true
docker image inspect IMAGE
docker history IMAGE                 # layers and their sizes
docker tag SOURCE TARGET[:TAG]       # add a name
docker rmi IMAGE                     # remove a tag/image
docker search nginx                  # search Docker Hub
docker save IMAGE -o image.tar       # image to a tar archive
docker load -i image.tar             # tar archive to image
docker export NAME -o fs.tar         # a container's filesystem
docker import fs.tar NEWIMAGE

We confirmed the save/load round trip:

CONSOLE
$ docker tag alpine:3 myalpine:v1
$ docker save myalpine:v1 -o a.tar
$ docker rmi myalpine:v1
$ docker load -i a.tar
Loaded image: myalpine:v1

Notes: a tag is just a movable label; the same image can carry many. latest is a convention, not "the newest" (Tags and Registries). To refer to an exact image forever, use its digest: nginx@sha256:... (Understanding Images, Save, Load, Export, Import).

Build

Terminal
docker build -t myapp:1.0 .                 # build from ./Dockerfile
docker build -f Dockerfile.prod -t myapp .  # another Dockerfile
docker build --build-arg VERSION=1.4 .      # set an ARG
docker build --target test .                # stop at a named stage
docker build --no-cache .                   # ignore the layer cache
docker build --progress=plain .             # show full step output
docker buildx build --platform linux/amd64,linux/arm64 -t user/app --push .
docker buildx imagetools inspect IMAGE      # manifest list, platforms
docker buildx imagetools create -t REPO:stable REPO:1.4.1   # add a tag in the registry

The last argument is the build context, the folder sent to the builder. Keep it small with a .dockerignore (Build Context and .dockerignore, The Build Cache, BuildKit and buildx).

Dockerfile instructions

Instruction Purpose Remember
FROM image AS name Start a stage from a base image scratch is empty; use several FROM lines for multi-stage builds
RUN cmd Run a command at build time Chain related commands, clean caches in the same layer
COPY src dest Copy files from the context (or --from=stage) Prefer it over ADD; --chown, --chmod available
ADD src dest Like COPY, plus URLs and tar extraction Only when you need those extras
WORKDIR /dir Set the working directory (creates it) Use instead of RUN cd
ENV KEY=value Variable at build and run time Not for secrets
ARG NAME=default Build-time variable Redeclare in each stage that uses it
USER name_or_uid Run later steps and the container as this user Use numeric IDs on minimal images
EXPOSE 8080 Document a port Does not publish anything
VOLUME /data Declare a mount point Creates an anonymous volume if none is given
LABEL k=v Metadata, such as OCI labels Visible with docker image inspect
HEALTHCHECK CMD ... A command that reports health Shows (healthy) in docker ps
ENTRYPOINT ["x"] The fixed executable Exec form (JSON array) so signals reach it
CMD ["a","b"] Default arguments or command Replaced by anything after the image in docker run
STOPSIGNAL SIGTERM Signal used by docker stop Match what your program handles
SHELL [...] Shell used by shell-form instructions Rarely needed on Linux

Read the details in Writing a Dockerfile, CMD and ENTRYPOINT, COPY and ADD and Dockerfile Best Practices.

Volumes, bind mounts and tmpfs

Terminal
docker volume create data
docker volume ls
docker volume inspect data
docker volume rm data
docker run -v data:/var/lib/x IMAGE                  # named volume
docker run -v "$PWD/conf":/etc/x:ro IMAGE            # read-only bind mount
docker run --mount type=bind,source="$PWD",target=/app IMAGE
docker run --tmpfs /tmp:rw,size=64m IMAGE            # in-memory, gone on stop
CONSOLE
$ docker volume create --label project=demo data
data
$ docker volume ls --filter name=data --format '{{.Driver}} {{.Name}}'
local data

Use named volumes for data that must outlive the container (databases), bind mounts for source code during development, and tmpfs for scratch data that should never touch disk (Container Storage, Volumes, Bind Mounts, Backup and Restore).

Networks

Terminal
docker network create mynet
docker network ls
docker network inspect mynet
docker network connect mynet NAME
docker network disconnect mynet NAME
docker network rm mynet
docker run --network host IMAGE      # share the host's network (Linux)
docker run --network none IMAGE      # no networking at all

On a user-defined network containers reach each other by name (http://db:5432); on the default bridge they do not (User-Defined Bridge Networks, Containers Talking to Each Other, Troubleshooting Networks).

Docker Compose

Terminal
docker compose up -d                 # create and start in the background
docker compose up -d --build         # rebuild images first
docker compose up -d --wait          # return when services are healthy
docker compose up -d --scale web=3   # three containers of one service
docker compose down                  # remove containers and networks
docker compose down -v               # ...and named volumes (data loss!)
docker compose ps                    # list this project's containers
docker compose logs -f --tail 50 web
docker compose exec web sh
docker compose run --rm web COMMAND  # one-off container
docker compose stop | start | restart [SERVICE]
docker compose pull                  # update images
docker compose build [SERVICE]
docker compose config                # validated, merged file
docker compose config --quiet        # exit code only
docker compose cp web:/path ./path
docker compose top
docker compose watch                 # sync/rebuild on file changes
docker compose -f a.yaml -f b.yaml up
docker compose --profile debug up

With a two-service file (web with nginx, cache with Redis) these gave:

CONSOLE
$ docker compose ps --format 'table {{.Service}}\t{{.Status}}\t{{.Ports}}'
SERVICE   STATUS         PORTS
cache     Up 3 seconds   6379/tcp
web       Up 4 seconds   127.0.0.1:18160->80/tcp
$ docker compose ps --services
cache
web
$ docker compose exec cache redis-cli ping
PONG
$ docker compose config --images
nginx:alpine
redis:alpine

docker compose (a space) is the current tool; the old docker-compose with a hyphen is gone. The file is compose.yaml and has no version: key (Introduction to Docker Compose, Compose Commands).

Compose file keys

Key (under a service) Meaning
image Image to run, or the name to give a built image
build Build context (a path) or a map with context, dockerfile, target, args
command, entrypoint Override the image's CMD / ENTRYPOINT
ports "127.0.0.1:8080:80" publishes a port
environment, env_file Variables inline or from files
volumes Named volumes and bind mounts
networks Networks to join (and aliases)
depends_on Start order; add condition: service_healthy to wait for health
healthcheck test, interval, timeout, retries, start_period
restart no, always, on-failure, unless-stopped
deploy.replicas How many containers up creates
profiles Start the service only when the profile is selected
user, read_only, cap_drop Hardening options
secrets, configs Files mounted into the container

Top-level keys are name, services, networks, volumes, secrets, configs. See Services in Compose, Networks and Volumes in Compose and Environment, Variables and Secrets.

Registries

Terminal
docker login                         # prompts for credentials
docker login ghcr.io
docker tag app:1.0 registry.example.com/team/app:1.0
docker push registry.example.com/team/app:1.0
docker pull registry.example.com/team/app:1.0
docker logout

An image name has the shape [registry/][namespace/]name[:tag|@digest]. Without a registry host, Docker Hub is assumed (Working with Registries, Running a Private Registry).

Clean up safely

Terminal
docker system df                     # where the disk space went
docker container prune               # remove ALL stopped containers
docker image prune                   # remove dangling images only
docker image prune -a                # remove all images no container uses
docker volume prune                  # remove anonymous unused volumes
docker volume prune -a               # ...and named unused volumes (data loss!)
docker network prune
docker builder prune                 # build cache
docker system prune                  # containers + networks + dangling images + cache

Prune commands delete things for everyone who uses the same Docker daemon, so on a shared machine limit them with a filter. These forms were checked:

CONSOLE
$ docker container prune -f --filter label=project=demo
Total reclaimed space: 0B
$ docker volume prune -f --filter label=project=demo
Total reclaimed space: 0B
$ docker volume prune -a -f --filter label=project=demo
Deleted Volumes:
data

On current Docker Engines (we used 29), docker volume prune removes only anonymous volumes. A named volume stays until you add -a, which is also the form that can delete a database. Always check docker volume ls first, and prefer docker compose down (no -v) for everyday work. The other prune commands (image, builder, system) were not run here because they act on the whole daemon; their options are described in Cleaning Up.

Handy one-liners

Terminal
docker rm -f $(docker ps -aq)                         # remove EVERY container (careful on shared hosts)
docker ps -aq --filter status=exited                  # IDs of exited containers
docker inspect -f '{{.State.ExitCode}}' NAME          # why did it stop?
docker inspect -f '{{.NetworkSettings.Networks}}' NAME
docker run --rm -v "$PWD":/work -w /work alpine:3 ls  # run a tool against the current folder
docker run --rm -it --entrypoint sh IMAGE             # poke around inside an image
docker exec NAME env                                  # see the environment inside
docker image ls --format '{{.Repository}}:{{.Tag}} {{.Size}}'
docker compose down --rmi local -v                    # tear a project down completely

Docker 29 removed the old .NetworkSettings.IPAddress field; the addresses are under .NetworkSettings.Networks, one entry per network.

Which command do I need?

I want to... Command
See why a container exited docker logs NAME, then docker inspect -f '{{.State.ExitCode}}' NAME
Get a shell in a running container docker exec -it NAME sh
Get a shell in a container that keeps crashing docker run --rm -it --entrypoint sh IMAGE
Find out what is using my disk docker system df
Make a build start from scratch docker build --no-cache .
Test a Compose file for mistakes docker compose config --quiet
Update one service of a Compose project docker compose pull web && docker compose up -d web
Run a database migration docker compose run --rm api COMMAND
Stop a project but keep its data docker compose down
See which ports a project published docker compose ps or docker port NAME

If an error message baffles you, look it up in the next lesson, Common Docker Errors.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does docker run alpine:3 /etc/passwd end with?

    126 means the command was found but is not executable (permission denied). 127 means it was not found at all, as with nosuchcmd.
  2. 2. A container ends with exit code 137. Which statement is the most accurate?

    137 is 128 + 9, the signal number of SIGKILL. Check docker inspect for OOMKilled and compare the memory limit if it happened without your intervention.
  3. 3. Which command removes a project's containers and networks but keeps its named volumes?

    down leaves named volumes in place. The other three commands can delete volumes (and, with -a, unused images too).
  4. 4. You run docker volume prune on Docker 29 and your named database volume is still there. Why?

    On current Engines a plain docker volume prune removes anonymous volumes only. That is a safety net, and -a removes the named ones too.
  5. 5. What is the right way to publish a port so that only your own machine can reach it?

    A bare -p 8080:80 listens on all interfaces. Adding 127.0.0.1: restricts it to the loopback interface. --expose and EXPOSE publish nothing.

Summary

  • Learn the management form (docker container ..., docker image ...) and the short aliases; use --format with Go templates for scripts.
  • docker run options go before the image name, and the command to run goes after it.
  • Exit codes: 0 success, 125 Docker failure, 126 not executable, 127 not found, 137 killed (often out of memory), 143 terminated.
  • COPY over ADD, exec form for ENTRYPOINT and CMD, numeric USER, EXPOSE only documents.
  • Compose: up -d --wait, down keeps data, down -v deletes it, config --quiet validates.
  • Prune carefully: scope it with filters on shared machines, and remember that volume prune -a can delete a database.

Next: Common Docker Errors