Post

Docker Cheatsheet - Quick Reference Guide

A comprehensive Docker cheatsheet covering container management, images, networking, volumes, and common operations

Docker Cheatsheet - Quick Reference Guide

Overview

video grab from Youtube

What is Docker?

Open-source platform for containerization: packages apps + dependencies into lightweight, portable containers; enables consistent “build once, run anywhere”; core = Docker Engine; includes Docker Desktop (local dev), Docker Compose (multi-container), Docker Hub (image registry).

Who created Docker?

Created by Solomon Hykes at dotCloud (now Docker, Inc.) in 2013; open-source core (Moby project) maintained by community + Docker, Inc.; widely used by developers, DevOps, SREs, enterprises (e.g., Google, AWS, Microsoft, Netflix).

Why use Docker?

Solves “it works on my machine” by ensuring identical environments; lightweight vs VMs (shares host kernel); fast startup, high density, portability, reproducibility; accelerates dev/test/deploy cycles; standard for microservices, CI/CD, cloud-native apps.

Where to use Docker?

Runs on Linux natively (Engine); via Docker Desktop on macOS/Windows (uses VM/hypervisor); manages containers on servers, clouds (AWS ECS, Azure ACI, GCP), Kubernetes (via containerd/CRI), laptops, CI/CD pipelines; global adoption across dev, cloud, enterprise.

How to use Docker?

Client-server architecture: Docker CLI talks to Docker daemon → pulls/builds images (layered filesystem) → runs containers (isolated processes with namespaces/cgroups); key commands: docker run, docker build, docker compose up; images from registries like Docker Hub.

Container Management

Basic Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Run a container
docker run <image>
docker run -d <image>                    # Run in detached mode
docker run -it <image> /bin/bash         # Interactive terminal
docker run --name mycontainer <image>    # Name the container

# Start/Stop containers
docker start <container>
docker stop <container>
docker restart <container>
docker pause <container>
docker unpause <container>

# Remove containers
docker rm <container>                     # Remove stopped container
docker rm -f <container>                 # Force remove running container
docker container prune                   # Remove all stopped containers

# List containers
docker ps                                 # Running containers
docker ps -a                              # All containers
docker ps -q                              # Container IDs only
docker ps --format "table \t\t"

Container Information

1
2
3
4
5
6
7
8
9
10
# Inspect container
docker inspect <container>
docker inspect --format='' <container>
docker logs <container>                   # View logs
docker logs -f <container>                # Follow logs
docker logs --tail 100 <container>        # Last 100 lines
docker top <container>                     # Running processes
docker stats <container>                  # Resource usage
docker exec -it <container> /bin/bash     # Execute command in container
docker exec <container> <command>         # Run command in container

Image Management

Image Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# List images
docker images
docker images -a                          # All images including intermediate
docker images --format "table \t\t"

# Pull/Push images
docker pull <image>:<tag>
docker push <image>:<tag>
docker search <term>                      # Search Docker Hub

# Build images
docker build -t <name>:<tag> .
docker build -f Dockerfile.dev -t <name> .
docker build --no-cache -t <name> .       # Build without cache

# Remove images
docker rmi <image>
docker rmi -f <image>                      # Force remove
docker image prune                         # Remove unused images
docker image prune -a                      # Remove all unused images

# Tag images
docker tag <source> <target>
docker tag myapp:latest myapp:v1.0

Image Inspection

1
2
3
docker history <image>                     # Image layers
docker inspect <image>                     # Image details
docker image inspect <image>               # Detailed info

Dockerfile Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FROM <base-image>                          # Base image
FROM python:3.11-slim AS builder           # Multi-stage build

WORKDIR /app                               # Set working directory
COPY . /app                                # Copy files
ADD . /app                                 # Copy with URL/extraction support
RUN apt-get update && apt-get install -y  # Execute commands
ENV VAR=value                              # Environment variable
ARG BUILD_VERSION                          # Build-time variable
EXPOSE 8080                                # Expose port
VOLUME ["/data"]                           # Create volume
USER nonroot                               # Switch user
CMD ["python", "app.py"]                   # Default command
ENTRYPOINT ["python"]                      # Entry point
LABEL key="value"                          # Metadata
HEALTHCHECK CMD curl -f http://localhost/ || exit 1

Networking

Network Management

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# List networks
docker network ls
docker network inspect <network>

# Create networks
docker network create <name>
docker network create --driver bridge <name>
docker network create --subnet=172.20.0.0/16 <name>

# Connect containers to network
docker network connect <network> <container>
docker network disconnect <network> <container>

# Remove networks
docker network rm <network>
docker network prune                       # Remove unused networks

# Run container with network
docker run --network <network> <image>
docker run --network host <image>          # Use host network
docker run -p 8080:80 <image>             # Port mapping
docker run -p 127.0.0.1:8080:80 <image>   # Bind to specific interface

Port Mapping

1
2
3
4
5
# Publish ports
docker run -p 8080:80 <image>              # Map host:container
docker run -p 80:80/tcp <image>            # Specify protocol
docker run -P <image>                      # Publish all exposed ports
docker run -p 8080-8090:80-90 <image>     # Port range

Volumes & Data Management

Volume Operations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# List volumes
docker volume ls
docker volume inspect <volume>

# Create volumes
docker volume create <name>
docker volume create --driver local <name>

# Remove volumes
docker volume rm <volume>
docker volume prune                        # Remove unused volumes

# Mount volumes
docker run -v /host/path:/container/path <image>
docker run -v volume_name:/container/path <image>
docker run --mount type=bind,source=/host,target=/container <image>
docker run --mount type=volume,source=vol,target=/container <image>

Bind Mounts vs Volumes

1
2
3
4
5
6
7
8
9
10
11
# Bind mount (host path)
docker run -v /host/data:/app/data <image>

# Named volume
docker run -v mydata:/app/data <image>

# Anonymous volume
docker run -v /app/data <image>

# tmpfs mount (in-memory)
docker run --tmpfs /tmp <image>

Docker Compose

Basic Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Start services
docker-compose up
docker-compose up -d                       # Detached mode
docker-compose up --build                  # Rebuild images
docker-compose up <service>                # Start specific service

# Stop services
docker-compose down
docker-compose down -v                     # Remove volumes
docker-compose stop
docker-compose restart

# View logs
docker-compose logs
docker-compose logs -f                     # Follow logs
docker-compose logs <service>              # Service-specific logs

# Execute commands
docker-compose exec <service> <command>
docker-compose exec web bash
docker-compose run <service> <command>     # Run one-off command

# Other commands
docker-compose ps                          # List services
docker-compose top                         # Running processes
docker-compose config                      # Validate config
docker-compose pull                        # Pull images
docker-compose build                       # Build images

docker-compose.yml Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
version: '3.8'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    volumes:
      - .:/app
    environment:
      - FLASK_ENV=development
    depends_on:
      - db
    networks:
      - app-network

  db:
    image: postgres:15
    environment:
      POSTGRES_DB: myapp
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - app-network

volumes:
  db-data:

networks:
  app-network:
    driver: bridge

Advanced Operations

Multi-stage Builds

1
2
3
4
5
6
7
8
9
10
11
12
13
# Stage 1: Build
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Stage 2: Production
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Health Checks

1
2
3
4
5
6
7
# In Dockerfile
HEALTHCHECK --interval=30s --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

# In docker run
docker run --health-cmd="curl -f http://localhost || exit 1" \
  --health-interval=30s <image>

Resource Limits

1
2
3
4
5
6
7
8
9
10
# Memory limits
docker run -m 512m <image>                 # 512MB limit
docker run --memory-swap=1g <image>        # Swap limit

# CPU limits
docker run --cpus="1.5" <image>            # 1.5 CPUs
docker run --cpuset-cpus="0,1" <image>     # Specific CPUs

# I/O limits
docker run --device-read-bps /dev/sda:1mb <image>

Debugging & Troubleshooting

Debug Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Container debugging
docker exec -it <container> /bin/sh         # Shell access
docker exec -it <container> /bin/bash       # Bash access
docker attach <container>                   # Attach to running container

# Network debugging
docker network inspect bridge
docker port <container>                    # Port mappings
docker run --network none <image>          # No network

# Image debugging
docker build --progress=plain .            # Verbose build
docker build --no-cache .                  # Fresh build
docker history <image>                     # Layer history

Logs & Events

1
2
3
4
5
6
7
8
9
# View logs
docker logs <container>
docker logs --since 10m <container>        # Last 10 minutes
docker logs --until 10m <container>        # Until 10 minutes ago
docker logs --tail 50 <container>          # Last 50 lines

# Events
docker events                              # Real-time events
docker events --filter container=<name>

Cleanup Commands

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Remove stopped containers
docker container prune

# Remove unused images
docker image prune
docker image prune -a                      # All unused images

# Remove unused volumes
docker volume prune

# Remove unused networks
docker network prune

# Remove everything (DANGER!)
docker system prune                        # Unused resources
docker system prune -a                     # Everything including images
docker system prune -a --volumes           # Including volumes

Dockerfile Best Practices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Use specific tags, not 'latest'
FROM python:3.11-slim

# Use multi-stage builds for smaller images
FROM node:18 AS builder
# ... build steps
FROM node:18-alpine
COPY --from=builder /app/dist /app

# Order commands by change frequency
# Install dependencies first (cached)
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy application code last
COPY . .

# Use .dockerignore
# node_modules/
# .git/
# *.log

# Run as non-root user
RUN useradd -m appuser
USER appuser

# Use exec form for CMD/ENTRYPOINT
CMD ["python", "app.py"]                   # Good
CMD python app.py                          # Bad (shell form)

Security Best Practices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Scan images for vulnerabilities
docker scan <image>

# Run as non-root
docker run --user 1000:1000 <image>

# Limit capabilities
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE <image>

# Read-only filesystem
docker run --read-only <image>

# Security options
docker run --security-opt no-new-privileges <image>
docker run --security-opt apparmor=profile <image>

Useful Aliases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Add to ~/.bashrc or ~/.zshrc
alias dps='docker ps'
alias dpsa='docker ps -a'
alias di='docker images'
alias dex='docker exec -it'
alias drm='docker rm'
alias drmi='docker rmi'
alias dlog='docker logs'
alias dstop='docker stop'
alias dstart='docker start'
alias drestart='docker restart'
alias dclean='docker system prune -a'
alias dcu='docker-compose up'
alias dcd='docker-compose down'
alias dcl='docker-compose logs'

Quick Reference

CommandDescription
docker psList running containers
docker ps -aList all containers
docker imagesList images
docker run <img>Run container
docker exec -it <cnt> bashShell into container
docker logs <cnt>View logs
docker stop <cnt>Stop container
docker rm <cnt>Remove container
docker build -t <name> .Build image
docker pull <img>Pull image
docker push <img>Push image
docker-compose upStart services
docker-compose downStop services

Resources

This post is licensed under CC BY 4.0 by the author.