Docker cheatsheet

This cheat sheet features the most important and commonly used Docker commands for easy reference.

Table of contents

  1. References
  2. Images
    1. Build an image
    2. Build with a specific Dockerfile
    3. Build with build arguments
    4. Build with no cache
    5. Build for a specific platform
    6. Multi-platform build (requires buildx)
    7. List images
    8. List images with filters
    9. Remove an image
    10. Remove all images
    11. Remove all untagged images
    12. Pull an image
    13. Push an image
    14. Tag an image
    15. Save an image to a tar file
    16. Load an image from a tar file
    17. View image history (layers)
    18. Inspect an image
  3. Containers
    1. Run a container
    2. Run a container with environment variables
    3. Run a container with env file
    4. Run a container with a volume mount
    5. Run a container with a read-only volume
    6. Run a container with a named volume
    7. Run a container with a tmpfs mount
    8. Run a container with restart policy
    9. Run a container with resource limits
    10. Run a container with a specific network
    11. Run a container with a hostname
    12. Run a container with a specific user
    13. Run a container in interactive mode
    14. Run a container and remove it after it stops
    15. Run a container with health check
    16. Run a container with PID limit
    17. List running containers
    18. List all containers
    19. List containers with custom format
    20. Stop a container
    21. Stop a container with timeout
    22. Stop all containers
    23. Start a container
    24. Restart a container
    25. Pause a container
    26. Unpause a container
    27. Remove a container
    28. Force remove a running container
    29. Remove all containers
    30. Stop and remove all containers and images
    31. Kill all running containers
    32. Connect to a running container
    33. Execute a command in a running container
    34. Execute a command as a specific user
    35. View container logs
    36. Follow container logs
    37. View logs with timestamps
    38. View last N lines of logs
    39. View logs since a specific time
    40. Copy files from container to host
    41. Copy files from host to container
    42. View container resource usage
    43. View resource usage of all containers
    44. View container processes
    45. View container port mappings
    46. Rename a container
    47. Create an image from a container
    48. Export a container filesystem as a tar archive
    49. View container changes (diff)
    50. Wait for a container to stop and get exit code
  4. Inspect
    1. Get IP address of a running container
    2. Get container environment variables
    3. Get container mount points
    4. Get container restart count
    5. Get container health status
    6. See all space Docker takes up
    7. See detailed space usage
    8. Inspect a container
  5. Volumes
    1. Create a volume
    2. Create a volume with a specific driver
    3. List volumes
    4. Inspect a volume
    5. Remove a volume
    6. Remove all unused volumes
    7. Backup a volume
    8. Restore a volume
  6. Networks
    1. Create a network
    2. Create a network with a specific subnet
    3. Create a network with a specific driver
    4. List networks
    5. Inspect a network
    6. Connect a container to a network
    7. Connect a container to a network with a specific IP
    8. Disconnect a container from a network
    9. Remove a network
    10. Remove all unused networks
  7. Registry & Login
    1. Login to Docker Hub
    2. Login to a private registry
    3. Logout from a registry
    4. Login to AWS ECR
    5. Tag and push to a private registry
    6. Search Docker Hub
  8. Cleanup
    1. Remove all unused objects (containers, networks, images, cache)
    2. Remove all unused objects including volumes
    3. Remove all unused objects (force, no confirmation)
    4. Remove all unused images (not just dangling)
    5. Remove stopped containers
    6. Remove build cache
    7. Remove all build cache (force)
  9. Dockerfile Instructions
    1. Common Dockerfile instructions reference
    2. Multi-stage build example
    3. Java Spring Boot example
    4. Node.js example
  10. Docker Compose
    1. Start services
    2. Start a specific service
    3. Stop services
    4. Stop services and remove volumes
    5. Stop services and remove images
    6. View logs
    7. View logs for a specific service
    8. Rebuild and start services
    9. Rebuild a specific service
    10. Force recreate containers
    11. Scale a service
    12. List running services
    13. List all services (including stopped)
    14. Execute a command in a service
    15. Run a one-off command in a service
    16. Pull latest images
    17. View service configuration
    18. Validate compose file
    19. View service resource usage
    20. Restart a specific service
    21. Pause/unpause services
    22. Docker Compose file example
  11. Docker Context (Remote Management)
    1. List contexts
    2. Create a context for a remote host
    3. Switch context
    4. Remove a context
  12. Security Best Practices
    1. Run a container as non-root
    2. Run a container with read-only filesystem
    3. Run a container with no new privileges
    4. Drop all capabilities and add only needed ones
    5. Scan an image for vulnerabilities
    6. View image SBOM (Software Bill of Materials)
  13. Useful Tips
    1. View Docker version
    2. View Docker system info
    3. View Docker events in real-time
    4. Format output as JSON
    5. Update container restart policy
    6. Update container resource limits

References


Images

Build an image

docker build -t <image_name>:<tag> .

Build with a specific Dockerfile

docker build -f <Dockerfile> -t <image_name>:<tag> .

Build with build arguments

docker build --build-arg <ARG_NAME>=<value> -t <image_name>:<tag> .

Build with no cache

docker build --no-cache -t <image_name>:<tag> .

Build for a specific platform

docker build --platform linux/amd64 -t <image_name>:<tag> .

Multi-platform build (requires buildx)

docker buildx build --platform linux/amd64,linux/arm64 -t <image_name>:<tag> --push .

List images

docker images

List images with filters

docker images --filter "dangling=true"
docker images --filter "reference=<image_name>:*"

Remove an image

docker rmi <image_id>

Remove all images

docker rmi $(docker images -q)

Remove all untagged images

docker rmi $(docker images | grep '^<none>' | awk '{print $3}')

Pull an image

docker pull <image_name>:<tag>

Push an image

docker push <image_name>:<tag>

Tag an image

docker tag <image_id> <image_name>:<tag>

Save an image to a tar file

docker save -o <file_name>.tar <image_name>:<tag>

Load an image from a tar file

docker load -i <file_name>.tar

View image history (layers)

docker history <image_name>:<tag>

Inspect an image

docker inspect <image_name>:<tag>

Containers

Run a container

docker run -d --name <container_name> -p <host_port>:<container_port> <image_name>:<tag>

Run a container with environment variables

docker run -d --name <container_name> -e KEY=VALUE <image_name>:<tag>

Run a container with env file

docker run -d --name <container_name> --env-file .env <image_name>:<tag>

Run a container with a volume mount

docker run -d --name <container_name> -v <host_path>:<container_path> <image_name>:<tag>

Run a container with a read-only volume

docker run -d --name <container_name> -v <host_path>:<container_path>:ro <image_name>:<tag>

Run a container with a named volume

docker run -d --name <container_name> -v <volume_name>:<container_path> <image_name>:<tag>

Run a container with a tmpfs mount

docker run -d --name <container_name> --tmpfs /tmp <image_name>:<tag>

Run a container with restart policy

docker run -d --name <container_name> --restart=always <image_name>:<tag>
# Options: no, on-failure, on-failure:5, always, unless-stopped

Run a container with resource limits

docker run -d --name <container_name> --memory=512m --cpus=1.5 <image_name>:<tag>

Run a container with a specific network

docker run -d --name <container_name> --network <network_name> <image_name>:<tag>

Run a container with a hostname

docker run -d --name <container_name> --hostname <hostname> <image_name>:<tag>

Run a container with a specific user

docker run -d --name <container_name> --user <uid>:<gid> <image_name>:<tag>

Run a container in interactive mode

docker run -it --name <container_name> <image_name>:<tag> /bin/bash

Run a container and remove it after it stops

docker run --rm <image_name>:<tag>

Run a container with health check

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

Run a container with PID limit

docker run -d --name <container_name> --pids-limit=100 <image_name>:<tag>

List running containers

docker ps

List all containers

docker ps -a

List containers with custom format

docker ps --format "table \t\t\t"

Stop a container

docker stop <container_id>

Stop a container with timeout

docker stop -t 30 <container_id>

Stop all containers

NOTE: This will stop ALL your containers.

docker stop $(docker ps -aq)

Start a container

docker start <container_id>

Restart a container

docker restart <container_id>

Pause a container

docker pause <container_id>

Unpause a container

docker unpause <container_id>

Remove a container

docker rm <container_id>

Force remove a running container

docker rm -f <container_id>

Remove all containers

NOTE: This will remove ALL your containers.

docker rm $(docker ps -aq)

Stop and remove all containers and images

NOTE: This will remove ALL your images and containers.

docker stop $(docker ps -aq) && docker rm $(docker ps -aq) && docker rmi $(docker images -q)

Kill all running containers

docker kill $(docker ps -q)

Connect to a running container

docker exec -it <container_id> /bin/bash

Execute a command in a running container

docker exec <container_id> <command>

Execute a command as a specific user

docker exec -u <user> <container_id> <command>

View container logs

docker logs <container_id>

Follow container logs

docker logs -f <container_id>

View logs with timestamps

docker logs -t <container_id>

View last N lines of logs

docker logs --tail 100 <container_id>

View logs since a specific time

docker logs --since 2024-01-01T00:00:00 <container_id>

Copy files from container to host

docker cp <container_id>:<container_path> <host_path>

Copy files from host to container

docker cp <host_path> <container_id>:<container_path>

View container resource usage

docker stats <container_id>

View resource usage of all containers

docker stats

View container processes

docker top <container_id>

View container port mappings

docker port <container_id>

Rename a container

docker rename <old_name> <new_name>

Create an image from a container

docker commit <container_id> <image_name>:<tag>

Export a container filesystem as a tar archive

docker export <container_id> > <file_name>.tar

View container changes (diff)

docker diff <container_id>

Wait for a container to stop and get exit code

docker wait <container_id>

Inspect

Get IP address of a running container

docker inspect -f '' <container_id>

Get container environment variables

docker inspect -f '' <container_id>

Get container mount points

docker inspect -f ' -> ' <container_id>

Get container restart count

docker inspect -f '' <container_id>

Get container health status

docker inspect -f '' <container_id>

See all space Docker takes up

docker system df

See detailed space usage

docker system df -v

Inspect a container

docker inspect <container_id>

Volumes

Create a volume

docker volume create <volume_name>

Create a volume with a specific driver

docker volume create --driver <driver_name> <volume_name>

List volumes

docker volume ls

Inspect a volume

docker volume inspect <volume_name>

Remove a volume

docker volume rm <volume_name>

Remove all unused volumes

docker volume prune

Backup a volume

docker run --rm -v <volume_name>:/data -v $(pwd):/backup alpine tar czf /backup/<backup_name>.tar.gz -C /data .

Restore a volume

docker run --rm -v <volume_name>:/data -v $(pwd):/backup alpine tar xzf /backup/<backup_name>.tar.gz -C /data

Networks

Create a network

docker network create <network_name>

Create a network with a specific subnet

docker network create --subnet=172.18.0.0/16 <network_name>

Create a network with a specific driver

docker network create --driver bridge <network_name>
# Drivers: bridge, host, overlay, macvlan, none

List networks

docker network ls

Inspect a network

docker network inspect <network_name>

Connect a container to a network

docker network connect <network_name> <container_id>

Connect a container to a network with a specific IP

docker network connect --ip 172.18.0.10 <network_name> <container_id>

Disconnect a container from a network

docker network disconnect <network_name> <container_id>

Remove a network

docker network rm <network_name>

Remove all unused networks

docker network prune

Registry & Login

Login to Docker Hub

docker login

Login to a private registry

docker login <registry_url>

Logout from a registry

docker logout <registry_url>

Login to AWS ECR

aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <account_id>.dkr.ecr.<region>.amazonaws.com

Tag and push to a private registry

docker tag <image_name>:<tag> <registry_url>/<image_name>:<tag>
docker push <registry_url>/<image_name>:<tag>

Search Docker Hub

docker search <term>

Cleanup

Remove all unused objects (containers, networks, images, cache)

docker system prune

Remove all unused objects including volumes

docker system prune --volumes

Remove all unused objects (force, no confirmation)

docker system prune -af --volumes

Remove all unused images (not just dangling)

docker image prune -a

Remove stopped containers

docker container prune

Remove build cache

docker builder prune

Remove all build cache (force)

docker builder prune -af

Dockerfile Instructions

Common Dockerfile instructions reference

# Base image
FROM <image_name>:<tag>

# Multi-stage build
FROM <image_name>:<tag> AS builder

# Set metadata
LABEL maintainer="<name>"
LABEL version="1.0"

# Set environment variables
ENV <KEY>=<VALUE>

# Set build-time variables
ARG <ARG_NAME>=<default_value>

# Set working directory
WORKDIR /app

# Copy files from host to image
COPY <src> <dest>

# Copy files with ownership
COPY --chown=<user>:<group> <src> <dest>

# Copy from a build stage
COPY --from=builder /app/build /app

# Add files (supports URLs and auto-extraction of tar files)
ADD <src> <dest>

# Run a command during build
RUN <command>

# Run multiple commands in a single layer
RUN apt-get update && \
    apt-get install -y <package> && \
    rm -rf /var/lib/apt/lists/*

# Set the default command
CMD ["executable", "param1", "param2"]

# Set the entrypoint
ENTRYPOINT ["executable"]

# Expose a port
EXPOSE <port>

# Define a volume
VOLUME ["/data"]

# Set the user
USER <user>:<group>

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

# Disable health check
HEALTHCHECK NONE

# Signal to stop the container
STOPSIGNAL SIGTERM

# Set shell
SHELL ["/bin/bash", "-c"]

Multi-stage build example

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

# Production stage
FROM alpine:3.19
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=builder /app/main .
EXPOSE 8080
USER nobody:nobody
ENTRYPOINT ["./main"]

Java Spring Boot example

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY target/*.jar app.jar
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=10s --retries=3 \
  CMD wget --quiet --tries=1 --spider http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "-jar", "app.jar"]

Node.js example

FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
USER node
CMD ["node", "index.js"]

Docker Compose

Start services

docker compose up -d

Start a specific service

docker compose up -d <service_name>

Stop services

docker compose down

Stop services and remove volumes

docker compose down -v

Stop services and remove images

docker compose down --rmi all

View logs

docker compose logs -f

View logs for a specific service

docker compose logs -f <service_name>

Rebuild and start services

docker compose up -d --build

Rebuild a specific service

docker compose up -d --build <service_name>

Force recreate containers

docker compose up -d --force-recreate

Scale a service

docker compose up -d --scale <service_name>=3

List running services

docker compose ps

List all services (including stopped)

docker compose ps -a

Execute a command in a service

docker compose exec <service_name> <command>

Run a one-off command in a service

docker compose run --rm <service_name> <command>

Pull latest images

docker compose pull

View service configuration

docker compose config

Validate compose file

docker compose config --quiet

View service resource usage

docker compose top

Restart a specific service

docker compose restart <service_name>

Pause/unpause services

docker compose pause
docker compose unpause

Docker Compose file example

version: "3.9"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        - APP_ENV=production
    image: <image_name>:<tag>
    container_name: <container_name>
    ports:
      - "8080:8080"
    environment:
      - DATABASE_URL=postgresql://<user>:<password>@db:5432/<db_name>
    env_file:
      - .env
    volumes:
      - app-data:/app/data
    networks:
      - app-network
    depends_on:
      db:
        condition: service_healthy
    restart: unless-stopped
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 512M
        reservations:
          cpus: "0.5"
          memory: 256M
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 40s

  db:
    image: postgres:16-alpine
    container_name: db
    ports:
      - "5432:5432"
    environment:
      - POSTGRES_USER=<user>
      - POSTGRES_PASSWORD=<password>
      - POSTGRES_DB=<db_name>
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - app-network
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U <user>"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  app-data:
  db-data:

networks:
  app-network:
    driver: bridge

Docker Context (Remote Management)

List contexts

docker context ls

Create a context for a remote host

docker context create <context_name> --docker "host=ssh://<user>@<host>"

Switch context

docker context use <context_name>

Remove a context

docker context rm <context_name>

Security Best Practices

Run a container as non-root

docker run -d --user 1000:1000 <image_name>:<tag>

Run a container with read-only filesystem

docker run -d --read-only <image_name>:<tag>

Run a container with no new privileges

docker run -d --security-opt=no-new-privileges <image_name>:<tag>

Drop all capabilities and add only needed ones

docker run -d --cap-drop ALL --cap-add NET_BIND_SERVICE <image_name>:<tag>

Scan an image for vulnerabilities

docker scout cves <image_name>:<tag>

View image SBOM (Software Bill of Materials)

docker sbom <image_name>:<tag>

Useful Tips

View Docker version

docker version

View Docker system info

docker info

View Docker events in real-time

docker events

Format output as JSON

docker ps --format ''

Update container restart policy

docker update --restart=always <container_id>

Update container resource limits

docker update --memory=1g --cpus=2 <container_id>