Docker Cheatsheet

Docker is a platform for developing, shipping, and running applications inside containers. Containers allow you to package your application with all its dependencies, ensuring consistency across multiple environments.

Table of Contents

  1. Installation
  2. Basic Commands
  3. Images
  4. Containers
  5. Volumes
  6. Networks
  7. Docker Compose
  8. Dockerfile
  9. Registry Operations
  10. System Management
  11. Debugging & Monitoring
  12. Multi-Stage Builds
  13. Environment Variables
  14. Port Mapping
  15. Health Checks
  16. Security
  17. Performance Optimization
  18. Best Practices
  19. Common Use Cases
  20. Tips and Tricks

Installation

Install Docker on Various Platforms

Post-Installation Setup (Linux)

# Add user to docker group to run without sudo
sudo usermod -aG docker $USER
newgrp docker

# Enable Docker to start on boot
sudo systemctl enable docker

Verify Installation

docker --version
docker-compose --version
docker info

Basic Commands

Help

docker --help
docker <command> --help

Docker Daemon Management

# Start Docker
sudo systemctl start docker

# Stop Docker
sudo systemctl stop docker

# Restart Docker
sudo systemctl restart docker

# Check Docker Status
sudo systemctl status docker

# View Docker info
docker info

Images

List and Search Images

# List local images
docker images
docker image ls

# Search images on Docker Hub
docker search <image_name>

# Show image history
docker history <image_name>

# Inspect image details
docker inspect <image_name>

Pull and Push Images

# Pull an image
docker pull <image_name>
docker pull <image_name>:<tag>

# Pull all tags of an image
docker pull -a <image_name>

# Push an image
docker push <image_name>:<tag>

Build Images

# Build an image from Dockerfile
docker build -t <image_name> .
docker build -t <image_name>:<tag> .

# Build with build arguments
docker build --build-arg ARG_NAME=value -t <image_name> .

# Build without cache
docker build --no-cache -t <image_name> .

# Build from specific Dockerfile
docker build -f /path/to/Dockerfile -t <image_name> .

Manage Images

# Remove an image
docker rmi <image_name>
docker image rm <image_name>

# Remove multiple images
docker rmi <image1> <image2>

# Remove dangling images
docker image prune

# Remove all unused images
docker image prune -a

# Tag an image
docker tag <source_image> <target_image>:<tag>

# Save image to tar file
docker save -o <filename>.tar <image_name>

# Load image from tar file
docker load -i <filename>.tar

Containers

List Containers

# List running containers
docker ps
docker container ls

# List all containers (including stopped)
docker ps -a
docker container ls -a

# List container IDs only
docker ps -q

# List with custom format
docker ps --format "table {{.ID}}\t{{.Image}}\t{{.Status}}"

Run Containers

# Basic run
docker run <image_name>

# Run with custom name
docker run --name <container_name> <image_name>

# Run in interactive mode
docker run -it <image_name>

# Run in detached mode (background)
docker run -d <image_name>

# Run with port mapping
docker run -p <host_port>:<container_port> <image_name>

# Run with environment variables
docker run -e ENV_VAR=value <image_name>

# Run with volume mount
docker run -v <host_path>:<container_path> <image_name>

# Run with working directory
docker run -w /app <image_name>

# Run with user specification
docker run -u <user_id> <image_name>

# Run with restart policy
docker run --restart=always <image_name>

# Run with memory limit
docker run -m 512m <image_name>

# Run with CPU limit
docker run --cpus="1.5" <image_name>

Manage Containers

# Start a stopped container
docker start <container_id>

# Stop a running container
docker stop <container_id>

# Restart a container
docker restart <container_id>

# Pause a container
docker pause <container_id>

# Unpause a container
docker unpause <container_id>

# Kill a container
docker kill <container_id>

# Remove a container
docker rm <container_id>

# Remove a running container (force)
docker rm -f <container_id>

# Remove all stopped containers
docker container prune

Container Information

# View container logs
docker logs <container_id>
docker logs -f <container_id>  # Follow logs
docker logs --tail 50 <container_id>  # Last 50 lines

# Inspect container details
docker inspect <container_id>

# View container resource usage
docker stats <container_id>

# View processes in container
docker top <container_id>

# View container port mappings
docker port <container_id>

Execute Commands in Containers

# Execute command in running container
docker exec -it <container_id> /bin/bash
docker exec -it <container_id> /bin/sh

# Execute command without interactive mode
docker exec <container_id> <command>

# Execute as specific user
docker exec -u root -it <container_id> /bin/bash

Copy Files

# Copy from container to host
docker cp <container_id>:/path/in/container /path/on/host

# Copy from host to container
docker cp /path/on/host <container_id>:/path/in/container

Volumes

Manage Volumes

# List volumes
docker volume ls

# Create a volume
docker volume create <volume_name>

# Inspect volume details
docker volume inspect <volume_name>

# Remove a volume
docker volume rm <volume_name>

# Remove all unused volumes
docker volume prune

Use Volumes

# Named volume
docker run -v <volume_name>:/path/in/container <image_name>

# Bind mount (host directory)
docker run -v /host/path:/container/path <image_name>

# Anonymous volume
docker run -v /container/path <image_name>

# Read-only volume
docker run -v <volume_name>:/path/in/container:ro <image_name>

Networks

Manage Networks

# List networks
docker network ls

# Create a network
docker network create <network_name>

# Create network with specific driver
docker network create -d bridge <network_name>

# Inspect network details
docker network inspect <network_name>

# Remove a network
docker network rm <network_name>

# Remove all unused networks
docker network prune

Connect Containers to Networks

# Connect container to network
docker network connect <network_name> <container_id>

# Disconnect container from network
docker network disconnect <network_name> <container_id>

# Run container with specific network
docker run --network=<network_name> <image_name>

Docker Compose

Basic Commands

# Start services
docker-compose up

# Start services in background
docker-compose up -d

# Start specific service
docker-compose up <service_name>

# Stop services
docker-compose down

# Stop and remove volumes
docker-compose down -v

# Restart services
docker-compose restart

# View service status
docker-compose ps

Build and Logs

# Build services
docker-compose build

# Build without cache
docker-compose build --no-cache

# View service logs
docker-compose logs

# Follow logs for specific service
docker-compose logs -f <service_name>

# View logs with timestamps
docker-compose logs -t

Execute Commands

# Execute command in service
docker-compose exec <service_name> <command>

# Run one-off command
docker-compose run <service_name> <command>

# Scale services
docker-compose up --scale <service_name>=3

Sample docker-compose.yml

version: '3.8'
services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/code
    environment:
      - FLASK_ENV=development
    depends_on:
      - redis

  redis:
    image: redis:alpine
    volumes:
      - redis_data:/data

volumes:
  redis_data:

networks:
  default:
    driver: bridge

Dockerfile

Basic Instructions

# Base image
FROM ubuntu:20.04

# Maintainer info
LABEL maintainer="[email protected]"

# Set working directory
WORKDIR /app

# Copy files
COPY . /app
ADD archive.tar.gz /app

# Run commands
RUN apt-get update && apt-get install -y python3

# Set environment variables
ENV NODE_ENV=production
ENV PATH="/app/bin:${PATH}"

# Expose ports
EXPOSE 80 443

# Set user
USER 1000

# Volume mount points
VOLUME ["/data"]

# Entry point
ENTRYPOINT ["python3"]

# Default command
CMD ["app.py"]

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD curl -f http://localhost/ || exit 1

Advanced Dockerfile Example

# Multi-stage build
FROM node:16 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:16-alpine AS runtime
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

WORKDIR /app
COPY --from=build --chown=nextjs:nodejs /app/node_modules ./node_modules
COPY --chown=nextjs:nodejs . .

USER nextjs
EXPOSE 3000
ENV PORT 3000

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

Registry Operations

Docker Hub

# Login to Docker Hub
docker login

# Login to specific registry
docker login <registry_url>

# Logout
docker logout

# Push image
docker push <username>/<image_name>:<tag>

# Pull private image
docker pull <username>/<private_image>

Private Registry

# Run local registry
docker run -d -p 5000:5000 --name registry registry:2

# Tag for private registry
docker tag <image_name> localhost:5000/<image_name>

# Push to private registry
docker push localhost:5000/<image_name>

# Pull from private registry
docker pull localhost:5000/<image_name>

System Management

Clean Up

# Remove all stopped containers, unused networks, images, and cache
docker system prune

# Remove everything including volumes
docker system prune -a --volumes

# Show Docker disk usage
docker system df

# Show detailed disk usage
docker system df -v

Resource Management

# View system events
docker system events

# Show system information
docker system info

# Monitor container resource usage
docker stats

# Monitor specific containers
docker stats <container1> <container2>

Debugging & Monitoring

Logging

# View logs with timestamps
docker logs -t <container_id>

# Follow logs
docker logs -f <container_id>

# View specific number of lines
docker logs --tail 100 <container_id>

# View logs since specific time
docker logs --since "2023-01-01T00:00:00" <container_id>

Debugging

# Inspect container
docker inspect <container_id>

# View container processes
docker top <container_id>

# View container changes
docker diff <container_id>

# Export container as tar
docker export <container_id> > container.tar

# Import container from tar
docker import container.tar <image_name>

Health Monitoring

# Check container health
docker inspect --format='{{.State.Health.Status}}' <container_id>

# View health check logs
docker inspect --format='{{range .State.Health.Log}}{{.Output}}{{end}}' <container_id>

Multi-Stage Builds

Example Multi-Stage Dockerfile

# Build stage
FROM golang:1.19 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o main .

# Runtime stage
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/main .
CMD ["./main"]

Environment Variables

Setting Environment Variables

# Single variable
docker run -e VAR_NAME=value <image_name>

# Multiple variables
docker run -e VAR1=value1 -e VAR2=value2 <image_name>

# From file
docker run --env-file .env <image_name>

Environment File Example (.env)

NODE_ENV=production
DATABASE_URL=postgresql://user:pass@localhost/db
API_KEY=your-secret-key
DEBUG=false

Port Mapping

Port Mapping Options

# Map specific port
docker run -p 8080:80 <image_name>

# Map to random host port
docker run -P <image_name>

# Map multiple ports
docker run -p 8080:80 -p 8443:443 <image_name>

# Map to specific interface
docker run -p 127.0.0.1:8080:80 <image_name>

# Map UDP port
docker run -p 8080:80/udp <image_name>

Health Checks

Dockerfile Health Check

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

Runtime Health Check

# Run with health check
docker run -d --name web \
  --health-cmd="curl -f http://localhost || exit 1" \
  --health-interval=30s \
  --health-timeout=10s \
  --health-retries=3 \
  <image_name>

Security

Security Best Practices

# Use non-root user
FROM alpine:latest
RUN adduser -D -s /bin/sh appuser
USER appuser

# Use specific tags, not latest
FROM node:16.14.2-alpine

# Minimize attack surface
RUN apk --no-cache add curl && \
    rm -rf /var/cache/apk/*

Scanning Images

# Scan image for vulnerabilities (if available)
docker scan <image_name>

# Run with security options
docker run --security-opt no-new-privileges <image_name>

# Run with read-only filesystem
docker run --read-only <image_name>

# Drop capabilities
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE <image_name>

Performance Optimization

Resource Limits

# Memory limit
docker run -m 512m <image_name>

# CPU limit
docker run --cpus="1.5" <image_name>

# CPU shares (relative weight)
docker run --cpu-shares=512 <image_name>

# Block IO weight
docker run --blkio-weight=300 <image_name>

Storage Optimization

# Multi-stage to reduce image size
FROM node:16 AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:16-alpine
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY . .
CMD ["node", "app.js"]

Best Practices

Dockerfile Best Practices

  1. Use official base images
  2. Use specific tags, not latest
  3. Minimize the number of layers
  4. Don’t install unnecessary packages
  5. Use multi-stage builds
  6. Use .dockerignore file
  7. Run as non-root user
  8. Use COPY instead of ADD
  9. Leverage build cache
  10. Keep images small

Example .dockerignore

node_modules
npm-debug.log
Dockerfile
.dockerignore
.git
.gitignore
README.md
.env
.nyc_output
coverage
.nyc_output

Common Use Cases

Web Application Stack

version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - app

  app:
    build: .
    environment:
      - DATABASE_URL=postgresql://user:pass@db:5432/myapp
    depends_on:
      - db

  db:
    image: postgres:13
    environment:
      - POSTGRES_DB=myapp
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
    volumes:
      - postgres_data:/var/lib/postgresql/data

volumes:
  postgres_data:

Development Environment

version: '3.8'
services:
  app:
    build:
      context: .
      target: development
    volumes:
      - .:/app
      - /app/node_modules
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=development
    command: npm run dev

Tips and Tricks

Useful Commands

# Enter a running container
docker exec -it <container_id> /bin/bash

# View container filesystem changes
docker diff <container_id>

# Create image from container
docker commit <container_id> <new_image_name>

# Stream container stats
docker stats --no-stream

# Format output
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

# Filter containers
docker ps --filter "status=running"
docker ps --filter "ancestor=nginx"

# Remove containers by filter
docker container prune --filter "until=24h"

Debugging Tips

# Debug failed container
docker logs <container_id>
docker exec -it <container_id> /bin/sh

# Run container with debug shell
docker run -it --entrypoint /bin/sh <image_name>

# Override entrypoint
docker run -it --entrypoint="" <image_name> /bin/bash

# Inspect image layers
docker history <image_name>

Performance Tips

# Build with BuildKit (faster builds)
DOCKER_BUILDKIT=1 docker build .

# Use build cache from registry
docker build --cache-from <image_name> .

# Parallel downloads
docker pull --parallel <image_name>

Troubleshooting

Common Issues

# Permission denied
sudo usermod -aG docker $USER
newgrp docker

# Port already in use
docker ps  # Find conflicting container
docker stop <container_id>

# Out of disk space
docker system prune -a --volumes

# Container exits immediately
docker logs <container_id>
docker run -it <image_name> /bin/sh  # Debug interactively

System Information

# Docker version info
docker version

# System information
docker info

# Check Docker daemon
sudo systemctl status docker

# View Docker daemon logs
sudo journalctl -u docker

Conclusion

This comprehensive cheatsheet covers the essential Docker commands and concepts for both beginners and advanced users. For more detailed information, consult the official Docker documentation.