Docker & Containers

Cheatsheet

Dense command and config reference for daily use and interview prep. Docker Engine 26+, Compose v2, BuildKit.

Contents

Run and manage · Inspect and debug · Images · Build · Dockerfile · Networking · Storage · Compose · Registry · Security · Trivy · Cleanup · Exit codes · Top 15


Run and manage containers

TaskCommand
Run detached with name and portdocker run -d --name web -p 8080:80 nginx:alpine
Bind only to localhostdocker run -d -p 127.0.0.1:5432:5432 postgres:16-alpine
Interactive shell, auto-removedocker run --rm -it alpine sh
Environment variablesdocker run -e KEY=val --env-file app.env img
Restart policy--restart unless-stopped (no, on-failure:5, always)
Override entrypointdocker run --rm -it --entrypoint sh img
Run as specific userdocker run --user 10001:10001 img
Proper PID 1 (reaps zombies)docker run --init img
Set hostname / workdir--hostname h1 -w /app
Stop gracefully (custom timeout)docker stop -t 30 web
Kill with signaldocker kill -s HUP web
Start / restart / pausedocker start web, docker restart web, docker pause web
Renamedocker rename old new
List running / alldocker ps, docker ps -a
Custom ps formatdocker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
Wait for exit codedocker wait web
Copy filesdocker cp web:/etc/nginx/nginx.conf . and docker cp ./f web:/tmp/
Update limits livedocker update --memory 512m --cpus 1 web

Inspect and debug

TaskCommand
Logs, follow, last 100, with timedocker logs -f --tail 100 -t web
Logs sincedocker logs --since 10m web
Shell into running containerdocker exec -it web sh
Run one commanddocker exec web cat /etc/resolv.conf
Full JSONdocker inspect web
Exit code, OOM, restartsdocker inspect -f '{{.State.ExitCode}} {{.State.OOMKilled}} {{.RestartCount}}' web
IP addressdocker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' web
Health historydocker inspect -f '{{json .State.Health}}' web
Host PIDdocker inspect -f '{{.State.Pid}}' web
Processes in containerdocker top web
Live resource usagedocker stats --no-stream
Filesystem changesdocker diff web
Daemon eventsdocker events --since 10m --filter type=container
Port mappingsdocker port web
Debug shell-less containerdocker debug web or docker run --rm -it --pid container:web --net container:web nicolaka/netshoot
Disk usage by typedocker system df -v
Daemon info and storage driverdocker info

Images

TaskCommand
Pull specific tag or digestdocker pull nginx:1.27-alpine, docker pull nginx@sha256:<digest>
List with digestsdocker images --digests
Layers and sizesdocker history --no-trunc img
Config as JSONdocker inspect --format '{{json .Config}}' img | jq
Tagdocker tag img:dev reg.io/team/img:1.0.0
Save / load tarballdocker save -o img.tar img:1.0, docker load -i img.tar
Export / import filesystemdocker export web > fs.tar, docker import fs.tar img:flat
Removedocker rmi img, docker image prune -a --filter until=168h
Commit (debugging only)docker commit web img:debug
Search layers interactivelydive img

Build and buildx

TaskCommand
Basic builddocker build -t app:dev .
Different Dockerfile / contextdocker build -f docker/Dockerfile.prod -t app ./svc
Build a stagedocker build --target test .
Build argsdocker build --build-arg VERSION=1.2.3 .
No cache, fresh basedocker build --no-cache --pull .
Plain progress logsdocker build --progress=plain .
Secret mountdocker build --secret id=npm,src=./token.txt .
SSH mountdocker build --ssh default .
Create builderdocker buildx create --name multi --driver docker-container --use
Multi-arch pushdocker buildx build --platform linux/amd64,linux/arm64 -t reg/app:1.0 --push .
Registry cache--cache-from type=registry,ref=reg/app:cache --cache-to type=registry,ref=reg/app:cache,mode=max
GitHub Actions cache--cache-from type=gha --cache-to type=gha,mode=max
Load multi-platform locallydocker buildx build --platform linux/arm64 --load . (one platform at a time)
SBOM + provenancedocker buildx build --sbom=true --provenance=mode=max --push .
Inspect manifest listdocker buildx imagetools inspect reg/app:1.0
Copy/retag without rebuilddocker buildx imagetools create -t reg/app:prod reg/app:sha-abc1234
Prune build cachedocker builder prune --keep-storage 5GB

Dockerfile reference

InstructionNotes
FROM image:tag AS namePin versions; FROM --platform=$BUILDPLATFORM for cross-compiles
ARG NAME=defaultBuild-time only; before first FROM to parametrize the base
ENV KEY=valuePersists into runtime
WORKDIR /appCreates the directory; prefer over RUN cd
COPY --chown=u:g src dstPrefer over ADD; COPY --from=stage for multi-stage
RUN cmdOne layer per instruction; chain with && and clean up in the same RUN
RUN --mount=type=cache,target=/root/.cachePersistent package cache across builds
RUN --mount=type=secret,id=xSecret available at /run/secrets/x for that step only
USER 10001:10001Use a numeric UID so Kubernetes runAsNonRoot can verify it
EXPOSE 8080Documentation only; does not publish
ENTRYPOINT ["app"] / CMD ["--flag"]Exec form always; CMD gives default args
HEALTHCHECK --interval=15s --timeout=3s --start-period=10s --retries=3 CMD cmdExit 0 healthy, 1 unhealthy
STOPSIGNAL SIGTERMSignal for docker stop
LABEL org.opencontainers.image.source=URLOCI standard metadata
VOLUME /dataDeclares anonymous volume; use sparingly

Production skeleton:

dockerfile
# syntax=docker/dockerfile:1.7
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

FROM node:22-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node . .
USER node
EXPOSE 3000
HEALTHCHECK CMD node -e "fetch('http://127.0.0.1:3000/healthz').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server.js"]

Networking

TaskCommand
Create user-defined bridgedocker network create appnet
Internal-only networkdocker network create --internal backend
Custom subnetdocker network create --subnet 172.30.0.0/24 appnet
Run on networkdocker run -d --network appnet --name api img
Add network alias--network-alias api-v2
Connect / disconnect runningdocker network connect appnet web, docker network disconnect appnet web
Inspect membersdocker network inspect appnet
Share another container's networkdocker run --network container:web nicolaka/netshoot
Host networkingdocker run --network host img (Linux only, no isolation)
No networkingdocker run --network none img
Add host entry--add-host db.local:10.0.0.5
Reach host from container--add-host host.docker.internal:host-gateway
Custom DNS--dns 1.1.1.1
DriverUse
bridgeSingle host, default; user-defined adds DNS
hostNo NAT, max performance, no isolation
noneFully isolated
overlayMulti-host (Swarm)
macvlan / ipvlanContainer gets its own L2 address on the LAN

Embedded DNS is at 127.0.0.11 on user-defined networks. Published ports use iptables DNAT: sudo iptables -t nat -L DOCKER -n.

Volumes and mounts

TaskCommand
Create / list / inspectdocker volume create pgdata, docker volume ls, docker volume inspect pgdata
Named volume-v pgdata:/var/lib/postgresql/data
Bind mount (read-only)-v "$PWD/conf:/etc/app:ro"
Explicit syntax--mount type=bind,src=$PWD/conf,dst=/etc/app,readonly
tmpfs--tmpfs /tmp:rw,size=64m
Read-only root + tmp--read-only --tmpfs /tmp
Back up a volumedocker run --rm -v pgdata:/data -v "$PWD":/b alpine tar czf /b/pgdata.tgz -C /data .
Restore a volumedocker run --rm -v pgdata:/data -v "$PWD":/b alpine tar xzf /b/pgdata.tgz -C /data
Postgres logical dumpdocker exec db pg_dump -U user -Fc dbname > db.dump
Remove unused volumesdocker volume prune

Bind mount -v creates a missing host directory as root; --mount errors instead. Prefer --mount in scripts.

Docker Compose

TaskCommand
Up detached with builddocker compose up -d --build
Up without buildingdocker compose up -d --no-build
Recreate only changeddocker compose up -d
Force recreatedocker compose up -d --force-recreate
Down (keep volumes)docker compose down
Down + volumes + orphansdocker compose down -v --remove-orphans
Statusdocker compose ps -a
Logs of one servicedocker compose logs -f --tail 100 api
Exec / one-off rundocker compose exec api sh, docker compose run --rm api npm test
Scaledocker compose up -d --scale worker=3
Pull / build / pushdocker compose pull, docker compose build --pull, docker compose push
Validate and show merged configdocker compose config (use --quiet in CI)
Several filesdocker compose -f compose.yaml -f compose.prod.yaml up -d
Profiledocker compose --profile debug up -d
Watch mode (dev)docker compose watch
Wait for healthydocker compose up -d --wait
yaml
name: myapp
services:
  api:
    build: ./api
    image: ${REGISTRY}/api:${TAG:-dev}
    env_file: [./env/api.env]
    environment:
      DB_PASSWORD: ${DB_PASSWORD:?DB_PASSWORD is required}
    depends_on:
      db: { condition: service_healthy }
    healthcheck:
      test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/healthz"]
      interval: 15s
      timeout: 3s
      retries: 3
      start_period: 10s
    restart: unless-stopped
    read_only: true
    tmpfs: [/tmp]
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
    deploy:
      resources:
        limits: { cpus: "0.5", memory: 256M }
    networks: [frontend, backend]
  db:
    image: postgres:16-alpine
    volumes: [pgdata:/var/lib/postgresql/data]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]
    networks: [backend]
networks:
  frontend:
  backend:
    internal: true
volumes:
  pgdata:

Variable rules: .env feeds ${VAR} interpolation in compose.yaml; env_file: and environment: feed the container. Escape a literal $ as $$. Precedence (high to low): docker compose run -e, environment:, env_file:, image ENV.

Registry and tagging

TaskCommand
Login (token via stdin)echo "$TOKEN" | docker login ghcr.io -u USER --password-stdin
Logoutdocker logout ghcr.io
Push all tagsdocker push --all-tags ghcr.io/user/app
Get digestdocker inspect --format '{{index .RepoDigests 0}}' ghcr.io/user/app:1.0.0
Pull by digestdocker pull ghcr.io/user/app@sha256:<digest>
List remote tagscrane ls ghcr.io/user/app
Copy between registriescrane copy src dst
Local registrydocker run -d -p 5000:5000 --name registry registry:2

Reference format: [registry[:port]/]namespace/name[:tag][@sha256:digest].

Tag scheme we use in production: 1.4.2 (immutable release), 1.4 (moving minor), sha-abc1234 (traceability, unique per commit), main or edge (moving, non-prod only). No latest in deploy manifests. Deploy by digest when you need a guarantee.

Security hardening

ControlFlag or setting
Non-rootUSER 10001:10001 or --user 10001:10001
Read-only root FS--read-only --tmpfs /tmp
Drop all capabilities--cap-drop ALL (add back, e.g. --cap-add NET_BIND_SERVICE)
Block privilege escalation--security-opt no-new-privileges:true
Default seccomp profileon by default; custom: --security-opt seccomp=profile.json
Resource limits--memory 256m --cpus 0.5 --pids-limit 200
Never--privileged, mounting /var/run/docker.sock, --network host unless required
SecretsBuildKit --mount=type=secret; at runtime Compose secrets: or a secret manager, not ENV
Pin basesFROM node:22.11-alpine3.20 (or @sha256:)
User namespace remap"userns-remap": "default" in /etc/docker/daemon.json
Rootless Dockerdockerd-rootless-setuptool.sh install
Image trustcosign sign, cosign verify, deploy by digest

Trivy

TaskCommand
Scan image, gate for CItrivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 app:1.0
Scan with secrets and misconfigtrivy image --scanners vuln,secret,misconfig app:1.0
Scan Dockerfile / Compose / IaCtrivy config .
Scan source dependenciestrivy fs --scanners vuln,secret .
SBOM (CycloneDX / SPDX)trivy image --format cyclonedx -o sbom.json app:1.0 and --format spdx-json
Scan an SBOM latertrivy sbom sbom.json
JSON reporttrivy image -f json -o report.json app:1.0
Ignore file.trivyignore with one CVE per line, reason in a comment
Refresh DBtrivy image --download-db-only
Run as containerdocker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v trivy-cache:/root/.cache aquasec/trivy image app:1.0

Cleanup

TaskCommand
Remove stopped containersdocker container prune -f
Remove dangling imagesdocker image prune -f
Remove all unused imagesdocker image prune -a -f
Remove unused networksdocker network prune -f
Remove unused volumesdocker volume prune -f
Everything unused (no volumes)docker system prune -f
Everything incl. volumesdocker system prune -a --volumes -f (destructive)
Remove all containersdocker rm -f $(docker ps -aq)
Disk usagedocker system df
Log rotation--log-opt max-size=10m --log-opt max-file=3

Exit codes

CodeMeaning
0Clean exit
1Application error (read the logs)
125docker run itself failed (bad flag, daemon error)
126Command found but not executable (permissions)
127Command not found (wrong CMD or missing binary)
137SIGKILL: OOM kill, docker kill, or stop timeout exceeded
139SIGSEGV: segmentation fault
143SIGTERM: graceful stop

Frequent error messages

MessageMeaning and quick fix
Cannot connect to the Docker daemon at unix:///var/run/docker.sockDaemon down or no permission: systemctl status docker, add user to docker group
permission denied while trying to connect to the Docker daemon socketNot in docker group; sudo usermod -aG docker $USER and re-login
Bind for 0.0.0.0:80 failed: port is already allocatedHost port taken: ss -ltnp | grep :80
exec format errorWrong CPU architecture or missing shebang: build with --platform
no space left on devicedocker system df, then prune; check /var/lib/docker
pull access denied / manifest unknownWrong name or tag, or not logged in
OCI runtime create failed ... executable file not found in $PATHBad CMD/ENTRYPOINT or distroless without shell
network ... not found / Pool overlaps with other oneStale network or subnet clash: docker network prune, choose another subnet

Top 15 interview one-liners

  1. Container vs VM: a container is an isolated process sharing the host kernel (namespaces plus cgroups); a VM runs its own kernel on virtualized hardware.
  2. Image vs container: an image is an immutable stack of layers plus config; a container is an image plus a writable layer plus a running process.
  3. CMD vs ENTRYPOINT: ENTRYPOINT is the executable, CMD is its default arguments; docker run img args replaces CMD and appends to ENTRYPOINT.
  4. COPY vs ADD: use COPY; ADD also fetches URLs and auto-extracts archives, which is surprising and less auditable.
  5. Shrinking an image: multi-stage build, small base (alpine, slim, distroless), .dockerignore, no package caches, combine and clean up inside one RUN.
  6. Why order matters: cache is invalidated at the first changed layer, so copy dependency manifests and install before copying source.
  7. Data persistence: use named volumes for databases, bind mounts for dev, tmpfs for scratch; container filesystem is ephemeral.
  8. Container-to-container communication: put them on a user-defined network and use service names, because Docker's embedded DNS only exists there.
  9. EXPOSE vs -p: EXPOSE is documentation; -p host:container actually publishes the port through iptables DNAT.
  10. Run as non-root: set a numeric USER, drop capabilities, no-new-privileges, read-only root filesystem, ports above 1024.
  11. Secrets: never in ENV, ARG or COPY; they stay in docker history. Use BuildKit secret mounts at build time and secret managers or Compose secrets at runtime.
  12. Exit code 137: SIGKILL, usually the OOM killer; confirm with docker inspect -f '{{.State.OOMKilled}}' and raise the limit or fix the leak.
  13. depends_on pitfall: it orders start, not readiness; add a healthcheck and condition: service_healthy.
  14. Tagging in production: immutable semver plus git SHA tag, deploy by version or digest, never latest; scan with Trivy and fail on fixable HIGH/CRITICAL.
  15. Why docker stop is slow: the app is ignoring SIGTERM (often because a shell is PID 1); use exec-form CMD, handle the signal, or add --init.

Feedback