On this page

Docker Cheat Sheet

Quick reference for Docker commands, Dockerfile best practices, Docker Compose patterns, and container debugging.

Deep dive: Docker Section | Docker Security


Container Lifecycle

CommandDescription
docker run -d --name app imgRun container in background
docker run -it img /bin/shRun container interactively
docker run --rm imgRun and auto-remove on exit
docker run -p 8080:3000 imgMap host port 8080 to container 3000
docker run -v /host:/cont imgBind mount host directory
docker run --env-file .env imgLoad environment variables from file
docker run -e KEY=val imgSet one environment variable
docker run --network mynet imgAttach to a network
docker run --restart unless-stopped imgRestart policy (no, on-failure[:N], always, unless-stopped)
docker run --init imgRun a tiny init as PID 1 (forwards signals, reaps zombies)
docker run -u 1000:1000 -w /app imgRun as user, set working dir
docker run --platform linux/amd64 imgRun a specific architecture (emulated if needed)
docker run --mount type=bind,src=.,dst=/app imgExplicit mount syntax (errors if src is missing)
docker run --add-host host.docker.internal:host-gateway imgReach the host from the container on Linux
docker run --gpus all imgExpose GPUs (needs NVIDIA Container Toolkit)
docker create imgCreate without starting
docker start containerStart a stopped container
docker start -ai containerStart and attach interactively
docker stop containerGraceful stop (SIGTERM, then SIGKILL after 10s; -t 30 to change)
docker kill containerImmediate stop (SIGKILL)
docker restart containerStop and start
docker rm containerRemove stopped container
docker rm -f containerForce remove running container
docker container pruneRemove all stopped containers
docker rename old newRename a container
docker update --memory 1g --restart always containerChange limits/restart policy of a running container
docker wait containerBlock until it exits, print exit code

Image Management

CommandDescription
docker build -t name:tag .Build image from Dockerfile
docker build -f Dockerfile.prod .Build from specific Dockerfile
docker build --no-cache .Build without layer cache
docker build --target build .Stop at a named stage
docker build --build-arg VERSION=1.2 .Pass an ARG
docker build --pull .Always pull a newer base image
docker build --progress=plain .Full, uncollapsed build output
docker imagesList local images (docker image ls)
docker image inspect imgImage metadata (env, entrypoint, layers)
docker rmi imgRemove an image (docker image rm)
docker image pruneRemove dangling images
docker image prune -aRemove all unused images
docker tag img:v1 registry/img:v1Tag image for registry
docker push registry/img:v1Push to registry
docker pull img:tagPull from registry
docker save img > img.tarExport image to tarball (-o img.tar also works)
docker load < img.tarImport image from tarball (-i img.tar also works)
docker history imgShow image layer history
docker login ghcr.ioLog in to a registry (Docker Hub if omitted)
docker logoutLog out
docker initGenerate Dockerfile, compose.yaml and .dockerignore for the project in the current dir

BuildKit & Buildx

BuildKit is the default builder. docker buildx exposes all of its features.

CommandDescription
docker buildx lsList builders and the platforms they support
docker buildx create --name multi --useCreate a builder that can do multi-platform builds
docker buildx build --platform linux/amd64,linux/arm64 -t reg/img:1.0 --push .Multi-arch build, push the manifest list
docker buildx build --load -t img .Build and load the result into local images
docker buildx build --cache-to type=registry,ref=reg/img:cache,mode=max --cache-from type=registry,ref=reg/img:cache .Share cache via a registry
docker buildx build --cache-to type=gha,mode=max --cache-from type=gha .Cache in GitHub Actions
docker buildx build --secret id=npmrc,src=$HOME/.npmrc .Pass a secret without baking it into a layer
docker buildx build --ssh default .Forward your SSH agent (private git deps)
docker buildx build -o type=local,dest=out .Export build output files instead of an image
docker buildx imagetools inspect imgShow a remote image's manifest list (platforms)
docker buildx bakeBuild targets defined in docker-bake.hcl / compose file
docker builder pruneClear build cache

Container Inspection

CommandDescription
docker psList running containers
docker ps -aList all containers
docker logs containerView container logs
docker logs -f containerFollow container logs
docker logs --tail 100 containerLast 100 log lines
docker logs --since 10m -t containerLogs from the last 10 minutes, with timestamps
docker inspect containerFull container JSON metadata
docker inspect -f '<go-template>' containerExtract one field (examples under Debugging)
docker eventsStream daemon events (start, die, oom...)
docker statsLive resource usage
docker top containerRunning processes in container
docker diff containerFilesystem changes since start
docker port containerPort mappings

Exec & Copy

CommandDescription
docker exec -it container shShell into running container
docker exec container cmdRun command in container
docker exec -u root -it container shShell as root
docker exec -e DEBUG=1 container cmdRun with an extra env var
docker debug containerDebug shell with tools, even for distroless/scratch images (Docker Desktop)
docker cp container:/path ./localCopy from container to host
docker cp ./local container:/pathCopy from host to container

Dockerfile Patterns

Production Node.js Dockerfile

# syntax=docker/dockerfile:1

# Stage 1: Install dependencies
FROM node:26-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev

# Stage 2: Build
FROM node:26-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .
RUN npm run build

# Stage 3: Production
FROM node:26-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup -g 1001 -S app && \
    adduser -S -u 1001 -G app app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY package.json ./
USER app
EXPOSE 3000
CMD ["node", "dist/main.js"]

Production Go Dockerfile

FROM golang:1.27-alpine AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server

FROM scratch
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=build /server /server
USER 65534:65534
EXPOSE 8080
ENTRYPOINT ["/server"]

gcr.io/distroless/static-debian12:nonroot is an alternative to scratch that already has CA certs, /etc/passwd and tzdata.

Multi-Stage Build Tricks

PatternExample
Name a stageFROM node:26-alpine AS build
Copy from a stageCOPY --from=build /app/dist ./dist
Copy from any imageCOPY --from=nginx:alpine /etc/nginx/nginx.conf .
Build only up to a stagedocker build --target build .
Base a stage on another stageFROM build AS test
Cross-compile without emulationFROM --platform=$BUILDPLATFORM golang:1.27 AS build then ARG TARGETOS TARGETARCH and GOOS=$TARGETOS GOARCH=$TARGETARCH go build

BuildKit Dockerfile Features

# syntax=docker/dockerfile:1

# Cache package manager downloads across builds
RUN --mount=type=cache,target=/root/.cache/go-build go build ./...

# Use a secret at build time without leaving it in a layer
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci

# Use the SSH agent for private git repos (build with --ssh default)
RUN --mount=type=ssh git clone git@github.com:org/private.git

# Bind-mount files from the context without copying them into a layer
RUN --mount=type=bind,source=package.json,target=package.json npm ci

# Heredocs
RUN <<EOF
apt-get update
apt-get install -y --no-install-recommends curl
rm -rf /var/lib/apt/lists/*
EOF

# Set owner/permissions while copying (no extra chown layer)
COPY --chown=app:app --chmod=755 entrypoint.sh /usr/local/bin/

Key Dockerfile Instructions

InstructionPurposeExample
FROMBase imageFROM node:26-alpine
WORKDIRSet working directoryWORKDIR /app
COPYCopy files (respects .dockerignore)COPY . .
ADDCopy + extract archives + URLsADD app.tar.gz /app
RUNExecute command during buildRUN npm ci
CMDDefault command (overridable)CMD ["node", "app.js"]
ENTRYPOINTFixed command (args appended)ENTRYPOINT ["/server"]
ENVSet environment variableENV NODE_ENV=production
ARGBuild-time variableARG VERSION=latest
EXPOSEDocument port (does not publish)EXPOSE 3000
VOLUMECreate mount pointVOLUME /data
USERSet runtime userUSER app
HEALTHCHECKContainer health checkSee below
LABELImage metadataLABEL org.opencontainers.image.source=https://github.com/org/repo
SHELLChange shell for shell-form commandsSHELL ["/bin/bash", "-o", "pipefail", "-c"]
STOPSIGNALSignal sent by docker stopSTOPSIGNAL SIGQUIT

ARG before the first FROM is only visible to FROM lines; redeclare it (ARG VERSION) inside a stage to use it there. ENV persists into the running container, ARG does not.

Healthcheck

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

Layer Optimization

Order matters -- put rarely-changing layers first:

# 1. System deps (rarely change)
RUN apk add --no-cache curl

# 2. App deps (change sometimes)
COPY package.json package-lock.json ./
RUN npm ci

# 3. App code (changes often)
COPY . .
RUN npm run build

Reduce layers -- combine related RUN commands:

# Bad: 3 layers
RUN apt-get update
RUN apt-get install -y curl
RUN rm -rf /var/lib/apt/lists/*

# Good: 1 layer
RUN apt-get update && \
    apt-get install -y curl && \
    rm -rf /var/lib/apt/lists/*

Docker Compose

Full reference: Docker Compose Cheat Sheet.

Basic Compose File

services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DATABASE_URL=postgres://user:pass@db:5432/mydb
      - REDIS_URL=redis://cache:6379
    depends_on:
      db:
        condition: service_healthy
      cache:
        condition: service_started
    volumes:
      - .:/app
      - /app/node_modules

  db:
    image: postgres:18-alpine
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
      POSTGRES_DB: mydb
    volumes:
      - pgdata:/var/lib/postgresql   # postgres 18+ images; use /var/lib/postgresql/data for 17 and older
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U user"]
      interval: 5s
      timeout: 5s
      retries: 5

  cache:
    image: redis:8-alpine
    ports:
      - "6379:6379"

volumes:
  pgdata:

Compose Commands

CommandDescription
docker compose upStart all services
docker compose up -dStart in background
docker compose up --buildRebuild and start
docker compose downStop and remove
docker compose down -vStop, remove, and delete volumes
docker compose logs -f appFollow logs for one service
docker compose exec app shShell into service
docker compose psList service status
docker compose restart appRestart one service
docker compose pullPull latest images
docker compose configValidate and view merged config
docker compose watchSync/rebuild on file changes (needs develop.watch)
docker compose run --rm app npm testOne-off command in a new container

Networking

CommandDescription
docker network lsList networks
docker network create mynetCreate network
docker network inspect mynetInspect network details
docker network connect mynet containerConnect container to network
docker network disconnect mynet containerDisconnect from network

Network Types

TypeUse Case
bridgeDefault. Single host. Containers resolve each other by name only on a user-defined bridge (docker network create); the built-in bridge network has no DNS
hostContainer shares host network. No port mapping needed (Linux; opt-in on Docker Desktop)
noneNo networking. Complete isolation
overlayMulti-host networking (Swarm)
macvlan / ipvlanContainer gets its own address on the physical LAN

-p 8080:3000 binds on all host interfaces (0.0.0.0) and bypasses ufw/firewalld rules. Use -p 127.0.0.1:8080:3000 for local-only.


Volumes

CommandDescription
docker volume lsList volumes
docker volume create myvolCreate named volume
docker volume inspect myvolVolume details
docker volume rm myvolDelete volume
docker volume pruneRemove unused anonymous volumes
docker volume prune -aRemove all unused volumes, named ones too

Back up a named volume:

docker run --rm -v myvol:/data -v "$PWD":/backup alpine tar czf /backup/myvol.tgz -C /data .

Volume Types

# Named volume (Docker manages storage)
docker run -v myvol:/data img

# Bind mount (host path)
docker run -v /host/path:/container/path img

# tmpfs mount (in-memory, Linux only)
docker run --tmpfs /tmp img

# Read-only mount
docker run -v /host/path:/data:ro img

Debugging Containers

Container Will Not Start

# Check logs
docker logs container

# Inspect exit code (137 = SIGKILL, often OOM; 143 = SIGTERM)
docker inspect container --format='Exit: {{.State.ExitCode}} OOMKilled: {{.State.OOMKilled}}'

# Run interactively to debug
docker run -it --entrypoint sh img

# Check resource limits
docker stats container

Container Is Slow

# Check resource usage
docker stats container

# Check process list
docker top container

# Profile with strace (if available)
docker exec container strace -p 1 -c

Networking Issues

# Check container IP
docker inspect container | grep '"IPAddress"'
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}' container

# Debug with a full network toolbox in the container's network namespace
docker run --rm -it --network container:<name> nicolaka/netshoot

# Test DNS resolution
docker exec container nslookup other-service

# Test connectivity
docker exec container wget -qO- http://other-service:3000/health

# Check port bindings
docker port container

Disk Space Issues

# Check Docker disk usage
docker system df

# Detailed breakdown
docker system df -v

# Clean everything unused
docker system prune -a --volumes

# Build cache is often the biggest item
docker builder prune --keep-storage 10GB

Contexts (Remote Daemons)

CommandDescription
docker context lsList contexts
docker context create prod --docker host=ssh://user@hostDaemon over SSH
docker context use prodSwitch default context
docker --context prod psUse a context for one command
DOCKER_HOST=ssh://user@host docker psSame, via env var

Security Quick Reference

PracticeCommand / Pattern
Run as non-rootUSER 1001 in Dockerfile
Read-only filesystemdocker run --read-only img
Drop capabilitiesdocker run --cap-drop ALL img
No new privilegesdocker run --security-opt no-new-privileges img
Resource limitsdocker run -m 512m --cpus 1 img
Scan for vulnerabilitiesdocker scout cves img (docker scout quickview img for a summary)
Build-time secretsRUN --mount=type=secret,id=..., never ARG/ENV
Use minimal base imageFROM alpine or FROM scratch
Pin image digestsFROM node@sha256:abc123...

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
Base imagealpinedebian-slimSize matters, no glibc depsNeed glibc, broad package support
Base imagenode:alpinescratchNeed runtime (Node, Python)Compiled binary (Go, Rust)
Mount typeNamed volumeBind mountPersistent data (DB, uploads)Development hot-reload
CMD formatExec form ["cmd"]Shell form cmdProduction (signal handling)Need shell expansion
Multi-stageYesNoProduction imagesSimple dev Dockerfiles
ComposeYesNoMulti-container local devSingle container, CI/CD

.dockerignore Template

node_modules
.git
.gitignore
.env*
*.md
dist
coverage
.vscode
.idea
docker-compose*.yml
Dockerfile*
.dockerignore

Test Yourself
  1. What flag auto-removes a container when it exits? docker run --rm

  2. How do you map host port 8080 to container port 3000? docker run -p 8080:3000 img

  3. What command shows live resource usage of running containers? docker stats

  4. How do you build an image without using the layer cache? docker build --no-cache .

  5. What command gets a shell into an already-running container? docker exec -it container sh

  6. What Dockerfile instruction sets the default command that can be overridden at runtime? CMD

  7. How do you stop and remove all containers, networks, and volumes created by Compose? docker compose down -v

  8. What command scans an image for known vulnerabilities? docker scout cves img

  9. How do you copy a file from a container to the host? docker cp container:/path ./local

  10. What is the purpose of EXPOSE in a Dockerfile? It documents the port the container listens on but does NOT actually publish it.

Common Gotchas

  • Running as root inside containers. Always add a USER instruction in production Dockerfiles -- running as root means a container escape grants root on the host.
  • Using latest tag in production. The latest tag is mutable and can change without warning. Pin image versions or use digests (node@sha256:...).
  • Forgetting .dockerignore. Without it, COPY . . sends your entire directory (including node_modules, .git, .env) to the build context, bloating images and leaking secrets.
  • Putting COPY . . before RUN npm install. This busts the dependency cache on every code change. Copy package.json and lock file first, install, then copy the rest.
  • Shell-form CMD/ENTRYPOINT swallow signals. CMD node app.js runs under /bin/sh -c, so SIGTERM never reaches node and docker stop waits 10s then kills. Use exec form ["node", "app.js"], and --init or tini if your process does not reap children.
  • Secrets in ARG/ENV end up in the image. They are visible in docker history and docker inspect. Use BuildKit secret mounts.
  • apt-get update in its own RUN layer goes stale. The cached layer is reused while the install line changes. Always apt-get update && apt-get install in one RUN.
  • Published ports skip the host firewall. Docker writes its own iptables rules, so ufw does not block -p 5432:5432. Bind to 127.0.0.1 for local-only services.
  • Images built on Apple Silicon are arm64. They fail with exec format error on amd64 servers. Build with --platform linux/amd64 or multi-arch via buildx.

One-Liner Summary

Docker packages your app and its dependencies into an isolated, portable container that runs the same everywhere -- master the Dockerfile layer cache and multi-stage builds to keep images small and builds fast.