A comprehensive cheatsheet for Docker that provides quick reference for commonly used commands, Dockerfile instructions, and Docker Compose configurations. Whether you're a beginner or experienced developer, this guide will help you navigate Docker more efficiently.

Table of Contents #
- Docker CLI Commands
- Dockerfile Reference
- Docker Compose Reference
- Docker Swarm Cheatsheet
- Practical Examples
- Troubleshooting
- Best Practices
- Conclusion
Docker CLI Commands #
Container Management #
# Run a container
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
docker run -d --name web -p 8080:80 nginx # Detached, named, port mapped
# Container lifecycle
docker start CONTAINER # Start a stopped container
docker stop CONTAINER # Gracefully stop a container
docker restart CONTAINER # Restart a container
docker pause CONTAINER # Pause processes in a container
docker unpause CONTAINER # Unpause a container
docker kill CONTAINER # Force stop a container
# Container information
docker ps # List running containers
docker ps -a # List all containers
docker inspect CONTAINER # View detailed container info
docker logs CONTAINER # View container logs
docker logs -f CONTAINER # Follow container logs
docker stats [CONTAINER] # View resource usage statistics
# Container interaction
docker exec -it CONTAINER COMMAND # Run a command in a container
docker exec -it web bash # Get a shell in a container
docker cp CONTAINER:SRC_PATH DEST_PATH # Copy files from a container
docker cp SRC_PATH CONTAINER:DEST_PATH # Copy files to a container
# Container cleanup
docker rm CONTAINER # Remove a stopped container
docker rm -f CONTAINER # Force remove a running container
docker container prune # Remove all stopped containers
Image Management #
# Pull and push images
docker pull IMAGE[:TAG] # Pull an image from a registry
docker push IMAGE[:TAG] # Push an image to a registry
docker login [SERVER] # Log in to a registry
# Build images
docker build -t NAME[:TAG] PATH # Build an image from a Dockerfile
docker build -t myapp:1.0 . # Build & tag from current directory
docker build --no-cache -t myapp . # Build without using cache
# Image information
docker images # List images
docker history IMAGE # Show image build history
docker inspect IMAGE # View detailed image info
# Image manipulation
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG] # Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
docker commit CONTAINER IMAGE[:TAG] # Create a new image from container changes
docker save -o filename.tar IMAGE[:TAG] # Save image to a tar archive
docker load -i filename.tar # Load image from a tar archive
# Image cleanup
docker rmi IMAGE # Remove an image
docker rmi $(docker images -q -f dangling=true) # Remove all dangling images
docker image prune # Remove unused images
docker image prune -a # Remove all unused images
Volume Management #
# Create and list volumes
docker volume create VOLUME # Create a volume
docker volume ls # List volumes
docker volume inspect VOLUME # View detailed volume info
# Using volumes with containers
docker run -v VOLUME:/container/path IMAGE # Run with a named volume
docker run -v /host/path:/container/path IMAGE # Run with a bind mount
docker run --mount source=VOLUME,target=/container/path IMAGE # Use --mount syntax
# Volume cleanup
docker volume rm VOLUME # Remove a volume
docker volume prune # Remove all unused volumes
Network Management #
# Create and list networks
docker network create NETWORK # Create a network
docker network create --driver overlay NETWORK # Create an overlay network (Swarm)
docker network ls # List networks
docker network inspect NETWORK # View detailed network info
# Connect containers to networks
docker network connect NETWORK CONTAINER # Connect a container to a network
docker network disconnect NETWORK CONTAINER # Disconnect a container from a network
# Run container with network
docker run --network NETWORK IMAGE # Run a container in a specific network
docker run --network host IMAGE # Run with host networking
docker run --network none IMAGE # Run with no networking
# Network cleanup
docker network rm NETWORK # Remove a network
docker network prune # Remove all unused networks
System Commands #
# System information
docker info # Display system-wide information
docker version # Show Docker version information
docker events # Get real-time events from the server
# Disk usage
docker system df # Show Docker disk usage
docker system df -v # Show detailed Docker disk usage
# System cleanup
docker system prune # Remove unused data
docker system prune -a # Remove unused data including unused images
docker system prune -a --volumes # Remove all unused data including volumes
Dockerfile Reference #
Common Dockerfile Instructions #
Instruction | Description |
---|---|
FROM | Specifies the base image |
WORKDIR | Sets the working directory |
COPY | Copies files from host to image |
ADD | Copies files with additional features (URL support, tar extraction) |
RUN | Executes commands during build |
ENV | Sets environment variables |
EXPOSE | Documents which ports the container listens on |
VOLUME | Creates a mount point for volumes |
CMD | Default command when container starts |
ENTRYPOINT | Configures container to run as executable |
ARG | Defines build-time variables |
LABEL | Adds metadata to the image |
USER | Sets the user for subsequent instructions |
HEALTHCHECK | Defines health check command |
Basic Instructions #
# Base image
FROM [--platform=<platform>] <image>[:<tag>] [AS <name>]
FROM python:3.9-slim
# Set working directory
WORKDIR /app
# Set the author
LABEL maintainer="name@example.com"
LABEL version="1.0"
LABEL description="This is a sample Dockerfile"
Environment and Arguments #
# Build arguments
ARG VERSION=latest
ARG BUILD_DATE
# Environment variables
ENV APP_HOME=/app
ENV LOG_LEVEL=info
# Using ARG in ENV
ARG VERSION
ENV IMAGE_VERSION=$VERSION
File Operations #
# Copy files from build context
COPY source dest
COPY . .
COPY source dest
COPY package*.json ./
# Add files (can download from URLs and extract archives)
ADD source dest
ADD https://example.com/file.tar.gz /tmp/
ADD file.tar.gz /usr/src/
# Create directories or files
RUN mkdir -p /app/logs && \
touch /app/logs/app.log && \
chmod 777 /app/logs/app.log
Runtime Instructions #
# Run commands during build
RUN apt-get update && \
apt-get install -y --no-install-recommends package && \
rm -rf /var/lib/apt/lists/*
# Expose port
EXPOSE 8080/tcp
EXPOSE 8081/udp
# Default command
CMD ["executable", "param1", "param2"]
CMD ["nginx", "-g", "daemon off;"]
CMD ["node", "server.js"]
# Entrypoint
ENTRYPOINT ["executable", "param1", "param2"]
ENTRYPOINT ["java", "-jar"]
CMD ["app.jar"] # Parameters that can be overridden
# Set user
USER username:group
USER 1001:1001
# Health check
HEALTHCHECK \
CMD curl -f http://localhost/ || exit 1
# Volumes
VOLUME /data
VOLUME ["/data", "/logs"]
Multi-stage Builds #
# Build stage
FROM node:14 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM nginx:alpine
COPY /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Docker Compose Reference #
Compose File Structure #
version: "3.8"
services:
service1:
# service configuration
service2:
# service configuration
networks:
network1:
# network configuration
volumes:
volume1:
# volume configuration
configs:
config1:
# config configuration
secrets:
secret1:
# secret configuration
Service Configuration #
services:
web:
image: nginx:alpine # Use this image
build: # Or build from source
context: ./dir # Build context
dockerfile: Dockerfile.dev # Custom Dockerfile
args: # Build arguments
VERSION: "1.0"
ports:
- "8080:80" # Host:container
- "443:443"
expose:
- "3000" # Only expose to other containers
environment:
- NODE_ENV=production # Environment variables
- DEBUG=0
env_file: .env # Load from .env file
volumes:
- ./html:/usr/share/nginx/html # Bind mount
- data:/data # Named volume
networks:
- frontend # Attach to this network
depends_on:
- db # Start after db
restart: always # Restart policy
deploy: # Swarm deployment settings
replicas: 3
update_config:
parallelism: 1
delay: 10s
resources:
limits:
cpus: "0.5"
memory: 256M
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
Network Configuration #
networks:
frontend:
driver: bridge # Network driver (bridge is default)
backend:
driver: bridge
internal: true # No external connectivity
custom:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.28.0.0/16 # Custom subnet
gateway: 172.28.0.1
default:
external: true # Use pre-existing network
name: existing_network_name # Name of the pre-existing network
Volume Configuration #
volumes:
data: # Simple named volume
db-data:
driver: local # Volume driver
driver_opts: # Driver options
type: "none"
o: "bind"
device: "/opt/data/db"
config-vol:
external: true # Use pre-existing volume
name: existing_volume_name # Name of pre-existing volume
Common Compose Commands #
# Start and stop
docker-compose up # Create and start containers
docker-compose up -d # Create and start in detached mode
docker-compose down # Stop and remove containers
docker-compose down -v # Stop and remove containers and volumes
# Service management
docker-compose start # Start existing containers
docker-compose stop # Stop containers
docker-compose restart # Restart containers
docker-compose pause # Pause services
docker-compose unpause # Unpause services
# Information
docker-compose ps # List containers
docker-compose logs # View output from containers
docker-compose logs -f service # Follow logs for a service
docker-compose top # Display running processes
# Building
docker-compose build # Build or rebuild services
docker-compose build --no-cache # Build without cache
# Executing commands
docker-compose exec service command # Execute a command in a running container
docker-compose run service command # Run a one-time command
# Configuration
docker-compose config # Validate and view compose file
docker-compose -f file1.yml -f file2.yml up # Use multiple compose files
Docker Swarm Cheatsheet #
# Initialize a swarm
docker swarm init --advertise-addr <MANAGER-IP>
# Join a swarm as a worker
docker swarm join --token <TOKEN> <MANAGER-IP>:2377
# Join a swarm as a manager
docker swarm join-token manager
docker swarm join --token <MANAGER-TOKEN> <MANAGER-IP>:2377
# Services
docker service create --name web --replicas 3 -p 80:80 nginx
docker service ls
docker service ps web
docker service scale web=5
docker service update --image nginx:1.21 web
docker service rm web
# Stacks
docker stack deploy -c docker-compose.yml mystack
docker stack ls
docker stack services mystack
docker stack ps mystack
docker stack rm mystack
# Secrets
docker secret create my_secret file.txt
docker service create --name web --secret my_secret nginx
Practical Examples #
Web Application with Database #
# docker-compose.yml
version: "3.8"
services:
web:
build: ./web
ports:
- "8080:80"
depends_on:
- api
networks:
- frontend
api:
build: ./api
environment:
DB_HOST: db
DB_USER: postgres
DB_PASSWORD: example
DB_NAME: mydatabase
depends_on:
- db
networks:
- frontend
- backend
db:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
POSTGRES_DB: mydatabase
volumes:
- db-data:/var/lib/postgresql/data
networks:
- backend
networks:
frontend:
backend:
volumes:
db-data:
Optimized Multi-stage Dockerfile #
# Build stage
FROM node:14 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Run stage
FROM nginx:alpine
# Copy built files from build stage
COPY /app/dist /usr/share/nginx/html
# Add custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Switch to non-root user
USER nginx
EXPOSE 80
HEALTHCHECK CMD curl -f http://localhost/ || exit 1
CMD ["nginx", "-g", "daemon off;"]
Development Environment #
# docker-compose.dev.yml
version: "3.8"
services:
app:
build:
context: .
dockerfile: Dockerfile.dev
volumes:
- ./:/app
- /app/node_modules
ports:
- "3000:3000"
environment:
- NODE_ENV=development
command: npm run dev
Troubleshooting #
# Check container logs
docker logs container_name
# Interactive shell in container
docker exec -it container_name sh
# Inspect container
docker inspect container_name
# Check container resource usage
docker stats container_name
# View all containers (including stopped)
docker ps -a
# Check Docker system info
docker info
# Check Docker daemon logs
sudo journalctl -u docker.service
# Clean up system
docker system prune -a --volumes
Best Practices #
- Use specific image tags instead of
latest
- Minimize layers by combining related commands with
&&
- Use .dockerignore to exclude unnecessary files
- Run as non-root user for improved security
- Use multi-stage builds to create smaller images
- Pin specific versions of dependencies
- Clean up in the same layer where packages are installed
- Order instructions from least to most frequently changing
- Use environment variables for configuration
- Include health checks for production services
- Use named volumes for persistent data
- Set resource limits in production environments
- Use networks to isolate container groups
- Add labels for better organization
- Regularly prune unused resources
Conclusion #
This cheatsheet provides a quick reference for the most common Docker commands, Dockerfile instructions, and Docker Compose configurations. By keeping these commands and examples handy, you can streamline your Docker workflow and become more productive with containerization.
Docker's ecosystem continues to evolve, so it's always good to check the official documentation for the most up-to-date information and best practices. With these fundamental commands and patterns, you're well-equipped to build, deploy, and manage containerized applications effectively.
What Docker commands or patterns do you find most useful in your daily workflow? Share your tips in the comments below!