Tutorial Docker DevOps Developer Tools Cheat Sheet

Free Docker Commands Expansion Cheat Sheet Online — 90+ Advanced Docker Commands & Dockerfile Reference

· 18 min read

Most developers know docker run, docker ps, and docker build. These are the gateway commands that get you started with containers. But Docker is a deep tool. Once you move beyond local development into production deployments, CI/CD pipelines, and multi-service architectures, you need more than the basics. You need to understand multi-stage builds, Buildx for cross-platform images, custom networks, named volumes, health checks, and the full spectrum of Dockerfile instructions. Our free Docker Commands Expansion Cheat Sheet is built for exactly this moment. It covers ninety-plus advanced commands, every Dockerfile instruction, Docker Compose orchestration patterns, and production-ready security practices. Everything is interactive, searchable, and copyable. No signup required.

Why Developers Need an Expansion Reference

The Docker CLI has hundreds of commands and thousands of flags. The official documentation is comprehensive but sprawling. When you are in the middle of debugging a production issue or optimizing a CI pipeline, you do not want to read a manual. You want the exact command, the right flag, and a working example.

An expansion cheat sheet serves a different purpose than a beginner reference. A basic cheat sheet answers: "How do I run a container?" An expansion cheat sheet answers: "How do I build a multi-platform image with Buildx?" "What is the difference between CMD and ENTRYPOINT?" "How do I attach a running container to a second network?" These are the questions that separate a developer who can use Docker from one who can wield it effectively in production.

Our Docker Commands Expansion Cheat Sheet is themed "The Container Ship's Cargo Hold" — a deep steel-charcoal interface with industrial grid overlays, warm cargo-manifest parchment cards, and shipping container category colors. Destructive commands are marked with hazard stripe badges. It is designed for long reference sessions, with high-contrast syntax highlighting and a layout that surfaces exactly what you need without scrolling through irrelevant entries.

Container Lifecycle Deep Dive

Container lifecycle management goes far beyond start, stop, and rm. Understanding the full set of lifecycle commands gives you precise control over running containers.

Running Containers with Advanced Flags

The docker run command has dozens of flags. Here are the ones that matter most in production:

docker run -d --name myapp --restart unless-stopped -p 8080:8080 -v app-data:/data --read-only myapp:latest

This command runs a container in detached mode with automatic restart policy, port mapping, a named volume, and a read-only root filesystem. The --restart unless-stopped flag ensures the container restarts after a host reboot unless it was explicitly stopped. The --read-only flag makes the root filesystem read-only, a critical security practice that forces you to explicitly define writable paths with --tmpfs or volumes.

To run with resource limits:

docker run -d --memory="512m" --cpus="1.5" --pids-limit=100 myapp

The --memory flag limits RAM usage. The --cpus flag limits CPU cores. The --pids-limit flag prevents fork bombs by capping the number of processes. These flags are essential for running untrusted code or preventing one container from starving others.

To run with a custom network and DNS settings:

docker run -d --network my-network --dns 8.8.8.8 --hostname app1 myapp

Executing Commands Inside Running Containers

The docker exec command is one of the most powerful debugging tools. It runs a new process inside an existing container's namespaces:

docker exec -it my-container bash

To run as a specific user:

docker exec -u www-data my-container whoami

To set environment variables for the exec session:

docker exec -e DEBUG=1 my-container python debug.py

To run a command in a specific working directory:

docker exec -w /app/tests my-container npm test

Attaching to Container Processes

docker attach connects your terminal to the main process of a running container:

docker attach my-container

Unlike exec, attach does not spawn a new process. It connects to the container's existing stdin, stdout, and stderr. Be careful: pressing Ctrl+C sends SIGINT to the main process, which may terminate the container. To detach without stopping the container, use the escape sequence Ctrl+P followed by Ctrl+Q.

Waiting for Container Exit

The docker wait command blocks until a container stops, then prints its exit code:

docker wait my-container

This is invaluable in shell scripts and CI pipelines where you need to know whether a container completed successfully before proceeding:

docker run --name builder myapp:build && exit_code=$(docker wait builder) && [ "$exit_code" -eq 0 ] || exit 1

Pausing and Unpausing Containers

Docker can freeze a container's processes without stopping them:

docker pause my-container
docker unpause my-container

Pausing suspends all processes in the container using cgroup freezer. The processes remain in memory and resume exactly where they left off. This is useful for temporarily halting a resource-intensive container without losing its state.

Updating Container Resources on the Fly

The docker update command changes resource limits for running containers without restarting them:

docker update --memory="1g" --cpus="2.0" my-container

You can update memory limits, CPU shares, restart policies, and block IO weights. Not all changes take effect immediately depending on the kernel version and cgroup driver.

Image Management: Build, Buildx, and Optimization

Images are the foundation of Docker. Efficient image management means faster builds, smaller images, and faster deployments.

Building Images with docker build

The standard build command:

docker build -t myapp:v1.0 --build-arg NODE_ENV=production .

The --build-arg flag passes variables available during build time. These differ from ENV variables, which are available at runtime. Build arguments are not persisted in the final image unless explicitly passed to ENV, making them ideal for secrets that should not leak into production images.

To build with a specific Dockerfile:

docker build -f Dockerfile.prod -t myapp:prod .

To build without cache:

docker build --no-cache -t myapp:latest .

To build with compressed build context:

docker build --compress -t myapp:latest .

Multi-Stage Docker Builds

Multi-stage builds are one of Docker's most powerful features for creating production images. They let you use one image for building and a different, smaller image for running:

# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Production stage
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80

The --from=builder syntax copies only the built artifacts from the build stage. The final image contains only Nginx and the static files, not Node.js, npm, or the source code. This can reduce image size from hundreds of megabytes to tens of megabytes.

To build a specific stage:

docker build --target builder -t myapp:builder .

Docker Buildx for Advanced Builds

Buildx is Docker's next-generation build tool with support for multi-platform builds, advanced caching, and BuildKit features.

To create and use a Buildx builder:

docker buildx create --name mybuilder --use
docker buildx inspect --bootstrap

To build a multi-platform image:

docker buildx build --platform linux/amd64,linux/arm64 -t myapp:latest --push .

The --platform flag specifies target architectures. The --push flag pushes the multi-arch manifest directly to the registry. Without --push, multi-platform builds cannot be loaded into the local Docker daemon.

To build with an inline cache:

docker buildx build --cache-to type=inline --cache-from type=registry,ref=myapp:cache -t myapp:latest .

To export build cache to a registry:

docker buildx build --cache-to type=registry,ref=myapp:cache --cache-from type=registry,ref=myapp:cache -t myapp:latest --push .

Image Inspection and Cleanup

To see image layers and creation commands:

docker history myapp:latest

To inspect image metadata:

docker inspect myapp:latest

To remove dangling (untagged) images:

docker image prune

To remove all unused images:

docker image prune -a

To remove images by filter:

docker image prune -a --filter "until=168h"

Docker Compose Orchestration

Docker Compose is the standard tool for defining and running multi-container applications. The expansion cheat sheet covers Compose commands beyond the basics.

Starting and Stopping Services

To start services with dependency ordering:

docker compose up -d --build

The --build flag rebuilds images before starting containers. The -d flag runs in detached mode.

To start only specific services:

docker compose up -d db redis

To stop and remove everything including volumes:

docker compose down -v --remove-orphans

The --remove-orphans flag removes containers for services not defined in the current compose file. The -v flag removes named volumes.

Service Inspection and Debugging

To view the resolved compose configuration:

docker compose config

To view logs for a specific service:

docker compose logs -f --tail 100 web

To execute a command in a service container:

docker compose exec web python manage.py migrate

To run a one-off command in a new container:

docker compose run --rm web npm test

The --rm flag removes the container after the command exits. The run command creates a new container, unlike exec which runs in an existing one.

Docker Compose Watch for Development

Docker Compose Watch automatically rebuilds and restarts services when files change:

docker compose watch

This requires a develop section in your compose file:

services:
  web:
    build: .
    develop:
      watch:
        - action: sync
          path: ./src
          target: /app/src
        - action: rebuild
          path: ./package.json

The sync action copies changed files into the running container. The rebuild action triggers a full image rebuild.

Scaling Services

To scale a service to multiple replicas:

docker compose up -d --scale web=3

To view resource usage across all services:

docker compose top

Networking: Custom Networks and Drivers

Docker networking determines how containers communicate. The default bridge network is fine for simple cases, but custom networks give you DNS resolution, isolation, and fine-grained control.

Creating and Managing Networks

To create a custom bridge network:

docker network create --driver bridge --subnet 172.20.0.0/16 --gateway 172.20.0.1 my-network

To create an overlay network for Docker Swarm:

docker network create --driver overlay --attachable my-overlay

To create a Macvlan network for containers that need their own MAC address:

docker network create -d macvlan --subnet 192.168.1.0/24 --gateway 192.168.1.1 -o parent=eth0 my-macvlan

Connecting Containers to Networks

To connect a running container to a network:

docker network connect my-network my-container

To connect with a specific IP address:

docker network connect --ip 172.20.0.50 my-network my-container

To disconnect a container from a network:

docker network disconnect my-network my-container

To inspect a network and see connected containers:

docker network inspect my-network

Custom bridge networks provide automatic DNS resolution. A container named web on my-network can reach a container named db using the hostname db. The default bridge network does not support this.

Cleaning Up Networks

docker network prune
docker network rm my-network

Volumes and Storage

Containers are ephemeral. Volumes and bind mounts provide persistent storage.

Named Volumes

Named volumes are managed by Docker and are the preferred way to persist data:

docker volume create --driver local --label env=production pg-data

To list volumes:

docker volume ls

To inspect a volume:

docker volume inspect pg-data

To remove a volume:

docker volume rm pg-data

To back up a volume to a tar archive:

docker run --rm -v pg-data:/data -v $(pwd):/backup alpine tar czf /backup/pg-data.tar.gz -C /data .

To restore a volume from a backup:

docker run --rm -v pg-data:/data -v $(pwd):/backup alpine sh -c "cd /data && tar xzf /backup/pg-data.tar.gz"

Bind Mounts and the --mount Syntax

The modern --mount syntax is more explicit than -v:

docker run -d --mount type=bind,source=$(pwd)/src,target=/app/src,readonly myapp

The --mount syntax supports three types: bind, volume, and tmpfs. It is self-documenting and prevents common mistakes like creating anonymous volumes when you meant to create a bind mount.

To mount a tmpfs for temporary data:

docker run -d --mount type=tmpfs,destination=/tmp,size=100m myapp

Tmpfs mounts store data in memory only. The data is lost when the container stops, making tmpfs ideal for sensitive temporary files.

System and Monitoring

Docker provides commands for monitoring resource usage and cleaning up accumulated artifacts.

Disk Usage Analysis

To see disk usage by Docker objects:

docker system df

To see verbose output with reclaimable space:

docker system df -v

System Cleanup

The docker system prune command is the nuclear option for reclaiming disk space:

docker system prune

This removes stopped containers, unused networks, and dangling images. To also remove all unused images:

docker system prune -a

To remove volumes as well:

docker system prune -a --volumes

To prune with a filter:

docker system prune -a --filter "until=24h"

Real-Time Resource Monitoring

To monitor all containers in real time:

docker stats

To monitor specific containers:

docker stats web db redis

To get a single snapshot without streaming:

docker stats --no-stream --format "table {{.Name}}	{{.CPUPerc}}	{{.MemUsage}}"

Event Streaming

To stream Docker daemon events:

docker events

To filter events by type:

docker events --filter event=stop --filter event=die

To see events since a specific time:

docker events --since 1h

Event streaming is powerful for building custom monitoring and audit tools. You can watch for container stops, image pulls, volume creations, and more.

Registry and Distribution

Docker images are distributed through registries. Understanding registry commands is essential for CI/CD and multi-environment workflows.

Authentication

To log in to a registry:

docker login registry.example.com

To log in with a password from stdin:

echo "$PASSWORD" | docker login --username myuser --password-stdin registry.example.com

Using --password-stdin prevents your password from appearing in shell history or process listings.

To log out:

docker logout registry.example.com

Image Distribution

To push an image:

docker push myregistry.com/myapp:v1.0

To pull a specific platform image:

docker pull --platform linux/arm64 myapp:latest

To inspect a manifest without pulling:

docker manifest inspect myapp:latest

To create and push a multi-arch manifest:

docker manifest create myapp:latest myapp:amd64 myapp:arm64
docker manifest push myapp:latest

Exporting and Importing Images

To save an image to a tar archive:

docker save -o myapp.tar myapp:latest

To save multiple images:

docker save -o bundle.tar myapp:latest nginx:alpine redis:7

To load images from a tar archive:

docker load -i myapp.tar

These commands are essential for air-gapped environments, offline transfers, and backup strategies.

Dockerfile Instructions Reference

A Dockerfile is a text document containing instructions for building an image. Every instruction has specific behavior and performance implications.

Base Image and Metadata

FROM initializes a new build stage and sets the base image:

FROM node:20-alpine AS builder

LABEL adds metadata to the image:

LABEL maintainer="team@example.com" version="1.0" description="My application"

Adding Files

COPY copies files from the build context into the image:

COPY package.json package-lock.json ./
COPY src/ ./src/

ADD has additional features: it can extract tar archives and download URLs:

ADD https://example.com/file.tar.gz /tmp/
ADD archive.tar.gz /app/

Prefer COPY unless you specifically need ADD's extra features. COPY is more predictable and its behavior is easier to understand.

Running Commands

RUN executes commands in a new layer:

RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

Chain commands with && to reduce layers. Clean up temporary files in the same RUN statement to keep the layer small.

For npm/yarn, use:

RUN npm ci --only=production

Environment and Arguments

ENV sets environment variables available at runtime:

ENV NODE_ENV=production PORT=3000

ARG defines build-time variables:

ARG NODE_VERSION=20
FROM node:${NODE_VERSION}-alpine

ARG values are not available at runtime unless passed to ENV. This makes ARG ideal for secrets that should not be baked into the final image.

Working Directory and User

WORKDIR sets the working directory for subsequent instructions:

WORKDIR /app

USER sets the user for running the container:

RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
USER nodejs

Running containers as non-root is a fundamental security practice. Always create a dedicated user instead of running as root.

Container Startup

CMD provides default arguments for the container:

CMD ["node", "server.js"]

ENTRYPOINT configures the container to run as an executable:

ENTRYPOINT ["node", "server.js"]

The key difference: CMD can be overridden with docker run arguments, while ENTRYPOINT cannot (unless using --entrypoint). The most flexible pattern is to use ENTRYPOINT for the executable and CMD for default arguments:

ENTRYPOINT ["node"]
CMD ["server.js"]

This allows docker run myapp index.js to override the default script while keeping node as the executable.

Exposing Ports and Volumes

EXPOSE documents which ports the container listens on:

EXPOSE 8080/tcp

EXPOSE does not actually publish the port. It is documentation. Use -p with docker run to publish.

VOLUME creates a mount point for externally mounted volumes:

VOLUME ["/data"]

Health Checks

HEALTHCHECK tells Docker how to test whether a container is healthy:

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3   CMD curl -f http://localhost:8080/health || exit 1

The options are: interval (how often to check), timeout (how long to wait for a response), start-period (grace period before counting failures), and retries (consecutive failures to mark unhealthy). A healthy container can be used with Docker's restart policies and orchestrators like Swarm and Kubernetes.

Signal Handling

STOPSIGNAL sets the system call signal that will be sent to the container to exit:

STOPSIGNAL SIGTERM

SHELL overrides the default shell used for RUN, CMD, and ENTRYPOINT:

SHELL ["/bin/bash", "-c"]

Security and Context

Security in Docker spans image scanning, runtime hardening, and access control.

Image Scanning

To scan an image for vulnerabilities:

docker scan myapp:latest

To scan with a specific severity threshold:

docker scan --severity high myapp:latest

Content Trust

Docker Content Trust ensures image integrity using digital signatures:

export DOCKER_CONTENT_TRUST=1
docker pull myapp:signed

When DCT is enabled, Docker only pulls and runs signed images.

Docker Context

Docker Context lets you switch between different Docker hosts:

docker context create remote --docker "host=ssh://user@remote-host"
docker context use remote

To list contexts:

docker context ls

To use a context for a single command:

docker --context remote ps

Contexts are essential for managing multiple environments (local, staging, production) without changing environment variables.

Runtime Security Flags

To drop all capabilities and add only what is needed:

docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE myapp

To run with a read-only root filesystem:

docker run --read-only --tmpfs /tmp --tmpfs /var/run myapp

To disable privilege escalation:

docker run --security-opt=no-new-privileges:true myapp

To run with a custom seccomp profile:

docker run --security-opt seccomp=custom-profile.json myapp

Advanced Patterns

These patterns represent best practices from production Docker deployments.

Multi-Stage Builds for Minimal Images

The ultimate multi-stage pattern separates build, test, and runtime:

# Dependencies
FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

# Builder
FROM node:20-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# Test
FROM node:20-alpine AS tester
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm test

# Production
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=builder /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

This Dockerfile has four stages. Only the final stage becomes the production image. The test stage runs in CI but its results do not bloat the final image.

ENTRYPOINT + CMD Pattern

The combination of ENTRYPOINT and CMD creates flexible, reusable images:

# Dockerfile
FROM alpine
ENTRYPOINT ["echo"]
CMD ["Hello, World"]

Running docker run myimage outputs "Hello, World". Running docker run myimage "Custom message" outputs "Custom message". The ENTRYPOINT stays fixed while CMD provides defaults that can be overridden.

Sidecar Pattern

The sidecar pattern runs a helper container alongside your main application:

# docker-compose.yml
services:
  app:
    image: myapp
    volumes:
      - logs:/var/log/app
  log-shipper:
    image: fluentd
    volumes:
      - logs:/var/log/app
    command: fluentd -c /fluentd/etc/fluent.conf

volumes:
  logs:

The log-shipper sidecar reads logs from the shared volume and forwards them to a centralized logging system. The main application does not need to know about log shipping.

Read-Only Root Filesystem

Running with --read-only prevents attackers from modifying the container's filesystem:

docker run -d --read-only   --tmpfs /tmp:noexec,nosuid,size=100m   --tmpfs /var/cache:size=10m   -v app-data:/data   myapp

Writable paths are explicitly defined: /tmp and /var/cache as tmpfs mounts, and /data as a persistent volume. Everything else is read-only.

Host Network Mode

The host network mode removes network isolation, giving the container direct access to the host's network stack:

docker run -d --network host myapp

This eliminates port mapping overhead and is useful for high-performance networking applications. However, it reduces isolation and is not available on Docker Desktop for Mac or Windows.

How to Use the Interactive Cheat Sheet

Our Docker Commands Expansion Cheat Sheet is designed for developers who need fast access to advanced Docker knowledge. When you open the tool, you see ninety-plus commands organized into ten color-coded categories that match shipping container colors: red for Container Lifecycle, blue for Image Management, green for Docker Compose, orange for Networking, brown for Volumes, safety green for System, purple for Registry, gold for Dockerfile Instructions, teal for Security, and steel gray for Advanced Patterns.

Click any category tab to filter commands by domain. Type in the search box to find commands by name, description, or example. Click the copy icon on any card to copy the example command to your clipboard. Destructive commands that remove data are marked with hazard stripe badges so you know before you paste.

The cargo-hold aesthetic uses a deep steel-charcoal background with an industrial grid overlay. Cards have a warm parchment texture evoking cargo manifests. Code blocks use JetBrains Mono for clarity. The interface is optimized for long reference sessions with high-contrast syntax highlighting that reduces eye strain.

Everything runs client-side in your browser. No data is sent to any server. The tool works offline once loaded, making it perfect for air-gapped environments or working on trains and planes.

Related Tools

DevToolkit offers a growing collection of interactive developer references. Explore these related cheat sheets and tools:

Conclusion

Docker is a tool that rewards depth. The difference between a developer who knows docker run and one who understands multi-stage builds, Buildx, custom networks, and Dockerfile health checks is the difference between someone who uses Docker and someone who masters it. Our free Docker Commands Expansion Cheat Sheet is built to bridge that gap. It covers the ninety-plus commands, Dockerfile instructions, and advanced patterns you need for production containerization. It is interactive, searchable, and copyable. It requires no signup and works offline. Bookmark the Docker Commands Expansion Cheat Sheet and keep it open during your next build, deployment, or debugging session. Your future self will thank you when you need the exact docker buildx flag or the correct HEALTHCHECK syntax at 2 AM.

Found this useful? Check out our free developer tools or browse more articles.