Complete Reference · Free Download

Docker Commands
Quick Guide

Every essential Docker command in one place — containers, images, volumes, networks, Compose, Dockerfile, registries and more. Built for DevOps beginners to production engineers.

Browse Cheat Sheet ↓
10+Topics Covered
150+Commands
6 pagesPDF Download
FreeAlways
Core Commands

Containers

Run, stop, start, restart and remove containers. Understand the container lifecycle and key runtime flags.

▶️
Run Containers
docker run flags and common usage patterns for starting containers.
bash
# Basic run
docker run nginx

# Detached + named + port mapping
docker run -d --name webserver \
  -p 8080:80 nginx

# Interactive shell
docker run -it ubuntu bash

# Remove on exit
docker run --rm alpine echo "hello"

# Set env variable
docker run -e MYSQL_ROOT_PASSWORD=secret \
  mysql:8

# Limit CPU & memory
docker run --cpus="1.5" --memory="512m" \
  nginx
🔄
Lifecycle Commands
Start, stop, restart, pause and remove containers.
bash
# List running containers
docker ps

# List all containers (incl. stopped)
docker ps -a

# Stop / start / restart
docker stop    webserver
docker start   webserver
docker restart webserver

# Pause / unpause
docker pause   webserver
docker unpause webserver

# Remove container
docker rm webserver

# Force-remove running container
docker rm -f webserver

# Remove all stopped containers
docker container prune
💻
Exec & Copy
Run commands inside containers and transfer files.
bash
# Open interactive shell
docker exec -it webserver bash

# Run single command
docker exec webserver ls /var/www

# Copy file TO container
docker cp ./config.json \
  webserver:/app/config.json

# Copy file FROM container
docker cp \
  webserver:/app/logs/app.log ./

# Rename container
docker rename webserver nginx_prod
🏁
Common docker run Flags
Essential flags for runtime configuration.
Flag Description Example
-d Detached (background) mode docker run -d nginx
-it Interactive terminal docker run -it ubuntu bash
--name Assign a container name --name myapp
-p host:ctr Publish port mapping -p 8080:80
-v src:dst Bind mount volume -v /data:/app/data
-e KEY=VAL Set environment variable -e NODE_ENV=production
--rm Remove container on exit docker run --rm alpine sh
--network Connect to network --network mynet
--restart Restart policy --restart unless-stopped
Image Management

Images

Pull, build, tag, push, inspect and remove Docker images. Understand layers and best practices for lean images.

⬇️
Pull & List Images
Download images from a registry and manage local image cache.
bash
# Pull latest tag
docker pull nginx

# Pull specific tag
docker pull node:20-alpine

# List local images
docker images
docker image ls

# Show image history/layers
docker history nginx

# Remove image
docker rmi nginx
docker image rm nginx

# Remove all unused images
docker image prune -a

# Search Docker Hub
docker search postgres
🔨
Build Images
Build images from a Dockerfile with tags and build args.
bash
# Build from current directory
docker build -t myapp:1.0 .

# Build from custom Dockerfile
docker build -f Dockerfile.prod \
  -t myapp:prod .

# Build with build args
docker build \
  --build-arg NODE_ENV=production \
  -t myapp:latest .

# No cache build
docker build --no-cache \
  -t myapp:fresh .

# Multi-platform build (Buildx)
docker buildx build \
  --platform linux/amd64,linux/arm64 \
  -t myapp:multi --push .
🏷️
Tag & Export
Tag images for registries and export/import image tarballs.
bash
# Tag an existing image
docker tag myapp:1.0 \
  myuser/myapp:1.0

# Save image to tar file
docker save -o myapp.tar myapp:1.0

# Load image from tar file
docker load -i myapp.tar

# Export container filesystem
docker export mycontainer > fs.tar

# Import filesystem as image
docker import fs.tar myimage:v1

# Commit container changes
docker commit mycontainer \
  myimage:snapshot
Data Persistence

Volumes

Persist data with named volumes, bind mounts and tmpfs. Volumes survive container restarts and removals.

💾
Volume Commands
Create, list, inspect and remove named Docker volumes.
bash
# Create a named volume
docker volume create pgdata

# List all volumes
docker volume ls

# Inspect a volume
docker volume inspect pgdata

# Remove a volume
docker volume rm pgdata

# Remove all unused volumes
docker volume prune

# Mount named volume to container
docker run -v pgdata:/var/lib/postgresql/data \
  postgres:15

# Bind mount (host path)
docker run -v /home/user/data:/app/data \
  myapp
📂
Volume Types
Named volumes, bind mounts and tmpfs — when to use each.
Type Syntax Best For
Named Volume -v pgdata:/data DB persistence, prod data
Bind Mount -v /host/path:/ctr Dev: live code reload
tmpfs --tmpfs /run Secrets, temp data in RAM
Anonymous -v /data Throwaway data (not recommended)
bash
# tmpfs mount (RAM-only)
docker run --tmpfs /run:rw,size=64m \
  nginx

# Read-only bind mount
docker run -v /config:/etc/config:ro \
  myapp
Networking

Networks

Create and manage Docker networks. Connect containers so they can talk to each other using service names as DNS.

🌐
Network Commands
Create, list, connect and remove Docker networks.
bash
# Create a bridge network
docker network create mynet

# List all networks
docker network ls

# Inspect a network
docker network inspect mynet

# Connect container to network
docker network connect mynet webserver

# Disconnect container
docker network disconnect mynet webserver

# Remove network
docker network rm mynet

# Remove unused networks
docker network prune
🔗
Network Drivers
Choose the right network driver for your use case.
Driver Use Case
bridge Default; isolated containers on same host
host Share host network stack (Linux only)
overlay Multi-host (Swarm / Kubernetes)
macvlan Assign real MAC addr, appear on LAN
none No networking, fully isolated
📡
Port Publishing
Expose container ports to the host machine.
bash
# Map host 8080 → container 80
docker run -p 8080:80 nginx

# Bind to specific host IP
docker run -p 127.0.0.1:8080:80 nginx

# Map random host port
docker run -P nginx

# Show port mappings
docker port webserver

# Create overlay network (Swarm)
docker network create \
  --driver overlay my_overlay
Image Authoring

Dockerfile

Write efficient Dockerfiles using multi-stage builds, layer caching strategies and best practices for minimal image sizes.

📄
Dockerfile Instructions
All Dockerfile directives explained with examples.
Instruction Description
FROM Base image (must be first instruction)
RUN Execute command in a new layer
COPY Copy files from build context
ADD Like COPY + supports URLs and tar extraction
WORKDIR Set working directory for subsequent instructions
ENV Set environment variable (persists in container)
ARG Build-time variable (not in final image)
EXPOSE Document which port the container uses
CMD Default command (overridable)
ENTRYPOINT Fixed entry command (CMD provides args)
VOLUME Declare a mount point
USER Set running user
LABEL Add metadata key=value
HEALTHCHECK Define container health test
🏗️
Multi-Stage Build Example
Separate build environment from runtime for lean final images.
dockerfile
# ── Stage 1: build ─────────────────
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# ── Stage 2: runtime ───────────────
FROM node:20-alpine
WORKDIR /app

# Copy only build artifacts
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules

USER node
EXPOSE 3000
HEALTHCHECK --interval=30s CMD \
  wget -qO- http://localhost:3000/health

CMD ["node", "dist/index.js"]
Dockerfile Best Practices
Write fast, secure and minimal Dockerfiles.
  • Pin versionsUse FROM node:20-alpine not latest for reproducible builds
  • Order layersPut infrequently-changing instructions (apt installs, COPY package.json) before frequently-changing ones (COPY src)
  • Combine RUNChain commands with && and clean up in same layer: RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
  • .dockerignoreExclude node_modules, .git, build artifacts to keep build context small and fast
  • Non-root USERAlways add a USER app instruction before CMD for security hardening
  • Use COPY not ADDPrefer COPY for local files; ADD is only needed for remote URLs or auto-extracting tarballs
Multi-Container Apps

Docker Compose

Define and run multi-container applications with a single YAML file. Essential for local development and CI environments.

🧩
Compose CLI
Start, stop and manage multi-container stacks.
bash
# Start all services (detached)
docker compose up -d

# Build + start
docker compose up --build

# Stop and remove containers
docker compose down

# Stop + remove volumes too
docker compose down -v

# View running services
docker compose ps

# View logs (follow)
docker compose logs -f

# Scale a service
docker compose up --scale web=3

# Exec into a service
docker compose exec web sh
📝
compose.yaml Example
Full-stack app: Node.js + PostgreSQL + Redis.
yaml
services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      DATABASE_URL: postgres://user:pass@db/app
      REDIS_URL:    redis://cache:6379
    depends_on:
      - db
      - cache

  db:
    image: postgres:15-alpine
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: pass

  cache:
    image: redis:7-alpine

volumes:
  pgdata:
⚙️
Compose Keys Reference
Commonly used service configuration keys.
Key Description
image Image to use for the service
build Path to Dockerfile context
ports Host:container port mappings
volumes Volume mounts
environment Environment variables
env_file Load vars from .env file
depends_on Startup order dependency
networks Networks to join
restart Restart policy
healthcheck Health probe definition
deploy Replicas & resource limits
Image Distribution

Registry & Push

Authenticate with Docker Hub, push and pull images from public and private registries including ECR, GCR and GHCR.

📦
Push to Docker Hub
Login, tag and push images to Docker Hub.
bash
# Login to Docker Hub
docker login

# Login with username
docker login -u myuser

# Tag for Docker Hub
docker tag myapp:1.0 myuser/myapp:1.0
docker tag myapp:1.0 myuser/myapp:latest

# Push to Docker Hub
docker push myuser/myapp:1.0
docker push myuser/myapp:latest

# Pull from Docker Hub
docker pull myuser/myapp:1.0

# Logout
docker logout
☁️
Cloud Registries
Push to AWS ECR, Google GCR and GitHub GHCR.
bash
# AWS ECR login
aws ecr get-login-password \
  --region us-east-1 | \
  docker login --username AWS \
  --password-stdin \
  123456789.dkr.ecr.us-east-1.amazonaws.com

# Push to ECR
docker push \
  123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:latest

# GitHub Container Registry (GHCR)
docker login ghcr.io \
  -u USERNAME -p $GITHUB_TOKEN

docker tag myapp:1.0 \
  ghcr.io/myuser/myapp:1.0
docker push ghcr.io/myuser/myapp:1.0
Debugging

Inspect & Logs

Read container logs, inspect configuration, monitor resource usage and debug running workloads.

📋
Logs
Stream and filter container log output.
bash
# Show all logs
docker logs webserver

# Follow (tail -f)
docker logs -f webserver

# Last 50 lines
docker logs --tail 50 webserver

# Logs since timestamp
docker logs --since "2024-01-01T10:00" \
  webserver

# Include timestamps
docker logs -t webserver

# Show stderr only
docker logs --stderr webserver
🔬
Inspect
Query container metadata with JSON output and Go templates.
bash
# Full JSON metadata
docker inspect webserver

# Get container IP address
docker inspect -f \
  '{{.NetworkSettings.IPAddress}}' \
  webserver

# Get mount info
docker inspect -f \
  '{{json .Mounts}}' webserver

# Get all env vars
docker inspect -f \
  '{{.Config.Env}}' webserver

# Inspect an image
docker inspect nginx:latest
📊
Stats & Top
Monitor live CPU, memory and network usage.
bash
# Live resource usage (all)
docker stats

# Stats for one container
docker stats webserver

# One-shot stats (no stream)
docker stats --no-stream

# Show running processes
docker top webserver

# List changed files
docker diff webserver

# Get container exit code
docker inspect -f \
  '{{.State.ExitCode}}' webserver

# Wait for container to stop
docker wait webserver
Housekeeping

System & Cleanup

Free disk space, manage Docker daemon settings and view system-wide information.

🧹
Prune Commands
Remove all unused Docker objects to reclaim disk space.
bash
# Remove stopped containers
docker container prune

# Remove dangling images
docker image prune

# Remove ALL unused images
docker image prune -a

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# ⚠️ Remove ALL unused objects
docker system prune

# ⚠️ Prune including volumes
docker system prune -a --volumes

# Skip confirmation prompt
docker system prune -f
ℹ️
System Info
View Docker daemon info, disk usage and version details.
bash
# Docker version
docker version
docker --version

# Daemon info (storage, OS, etc.)
docker info

# Disk usage breakdown
docker system df

# Verbose disk usage
docker system df -v

# View system events (live)
docker events

# Events in time range
docker events \
  --since "1h" --until "0h"
Orchestration

Docker Swarm

Cluster multiple Docker hosts, deploy services with replicas and perform rolling updates with zero downtime.

🐝
Swarm Init & Nodes
Initialize a swarm, add worker and manager nodes.
bash
# Initialize swarm on manager
docker swarm init \
  --advertise-addr 192.168.1.10

# Get join token for workers
docker swarm join-token worker

# Get join token for managers
docker swarm join-token manager

# Join as worker (run on worker node)
docker swarm join \
  --token SWMTKN-... \
  192.168.1.10:2377

# List nodes in swarm
docker node ls

# Leave swarm
docker swarm leave --force
⚙️
Services
Deploy, scale, update and remove swarm services.
bash
# Create a service
docker service create \
  --name web --replicas 3 \
  -p 80:80 nginx

# List services
docker service ls

# Service tasks (pods)
docker service ps web

# Scale a service
docker service scale web=5

# Rolling update
docker service update \
  --image nginx:1.25 web

# Remove service
docker service rm web
📦
Stacks
Deploy compose files to a swarm as a stack.
bash
# Deploy a stack
docker stack deploy \
  -c compose.yaml mystack

# List stacks
docker stack ls

# List stack services
docker stack services mystack

# List stack tasks
docker stack ps mystack

# Remove stack
docker stack rm mystack

# Swarm secrets
echo "s3cr3t" | \
  docker secret create db_pass -
docker secret ls

Get the Full Docker Cheat Sheet as PDF

Download the beautifully formatted PDF for offline reference — free forever. Perfect for your desk or second monitor.

More Cheat Sheets

Explore Other Guides

Expand your DevOps & developer toolkit with our free reference sheets.

Join WhatsApp Channel