Containers9 min read666 lines

Learning state

Track this guide

Saved in this browser only. No account required.

Docker Commands Master Class

Engineering-Grade Reference Manual for Docker
A comprehensive guide to Docker commands with real-world examples and production patterns


Table of Contents

  1. Core Commands
  2. Intermediate & Advanced Commands
  3. Docker Compose Mastery
  4. Troubleshooting & Best Practices

Core Commands

๐Ÿ”น Command: docker run

โœ”๏ธ What It Does
Creates and starts a new container from an image. This is the most fundamental Docker command that combines image pulling, container creation, and startup into one operation.

โœ”๏ธ Syntax Examples

# Basic: Run a simple container
docker run nginx

# Real-world: Run with port mapping and detached mode
docker run -d -p 8080:80 --name my-nginx nginx

# Production: Run with resource limits, restart policy, and environment variables
docker run -d \
  --name production-app \
  -p 443:443 \
  -e DATABASE_URL=postgres://db:5432 \
  --restart unless-stopped \
  --memory="512m" \
  --cpus="1.0" \
  -v /data:/app/data \
  myapp:v1.2.3

โœ”๏ธ Notes, Tips & Common Mistakes

  • Use -d (detached) for background processes; omit for interactive sessions
  • Always name containers with --name for easier management
  • Port format: -p HOST:CONTAINER (e.g., -p 8080:80)
  • Use --rm for temporary containers that auto-delete after exit
  • Combine -it for interactive terminal sessions

๐Ÿ”น Command: docker pull

โœ”๏ธ What It Does
Downloads a Docker image from a registry (Docker Hub by default) without running it. Useful for pre-fetching images or updating to latest versions.

โœ”๏ธ Syntax Examples

# Basic: Pull latest version
docker pull nginx

# Real-world: Pull specific version
docker pull postgres:15.2-alpine

# Production: Pull from private registry
docker pull myregistry.azurecr.io/myapp:v2.1.0

โœ”๏ธ Notes, Tips & Common Mistakes

  • Always specify version tags in production (avoid :latest)
  • Use --platform for multi-architecture images
  • Images are cached locally; re-pulling only downloads changed layers
  • Check image size before pulling large images

๐Ÿ”น Command: docker ps

โœ”๏ธ What It Does
Lists running containers. Add -a to see all containers including stopped ones.

โœ”๏ธ Syntax Examples

# Basic: Show running containers
docker ps

# Real-world: Show all containers with custom formatting
docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

# Production: Filter and monitor specific containers
docker ps --filter "status=running" --filter "name=prod-*"

โœ”๏ธ Notes, Tips & Common Mistakes

  • Use -q to get only container IDs (useful for scripting)
  • --no-trunc shows full container IDs and commands
  • Combine with grep for quick filtering: docker ps | grep nginx

๐Ÿ”น Command: docker logs

โœ”๏ธ What It Does
Retrieves logs from a container's stdout/stderr. Essential for debugging and monitoring.

โœ”๏ธ Syntax Examples

# Basic: View all logs
docker logs my-container

# Real-world: Follow logs in real-time with timestamps
docker logs -f --timestamps my-app

# Production: View last 100 lines and follow
docker logs --tail 100 -f production-api

โœ”๏ธ Notes, Tips & Common Mistakes

  • Use -f (follow) to stream logs like tail -f
  • --since and --until filter by time: --since 1h
  • Logs are stored until container is removed (can grow large)
  • Use log drivers for production (json-file, syslog, fluentd)

๐Ÿ”น Command: docker exec

โœ”๏ธ What It Does
Executes a command inside a running container. Perfect for debugging, running maintenance tasks, or accessing a shell.

โœ”๏ธ Syntax Examples

# Basic: Run a single command
docker exec my-container ls /app

# Real-world: Interactive shell access
docker exec -it my-container /bin/bash

# Production: Run database backup
docker exec postgres-db pg_dump -U postgres mydb > backup.sql

โœ”๏ธ Notes, Tips & Common Mistakes

  • Always use -it for interactive sessions
  • Use /bin/sh if /bin/bash is not available (Alpine images)
  • Cannot exec into stopped containers (use docker start first)
  • Runs as root by default; use -u to specify user

๐Ÿ”น Command: docker build

โœ”๏ธ What It Does
Builds a Docker image from a Dockerfile. This is how you create custom images for your applications.

โœ”๏ธ Syntax Examples

# Basic: Build from current directory
docker build -t myapp:latest .

# Real-world: Build with build arguments
docker build -t myapp:v1.0 --build-arg NODE_ENV=production .

# Production: Multi-platform build with cache optimization
docker build \
  -t myregistry.io/myapp:v2.0.1 \
  --platform linux/amd64,linux/arm64 \
  --build-arg VERSION=2.0.1 \
  --no-cache \
  -f Dockerfile.prod \
  .

โœ”๏ธ Notes, Tips & Common Mistakes

  • Use .dockerignore to exclude unnecessary files
  • Tag images with meaningful versions, not just :latest
  • --no-cache forces fresh build (useful for debugging)
  • Use -f to specify alternate Dockerfile names
  • Build context is the final argument (usually .)

๐Ÿ”น Command: docker stop / docker start / docker restart

โœ”๏ธ What It Does

  • stop: Gracefully stops a running container (SIGTERM, then SIGKILL after timeout)
  • start: Starts a stopped container
  • restart: Stops and starts a container

โœ”๏ธ Syntax Examples

# Basic: Stop a container
docker stop my-container

# Real-world: Stop with custom timeout (default 10s)
docker stop -t 30 my-app

# Production: Restart multiple containers
docker restart $(docker ps -q --filter "name=prod-")

โœ”๏ธ Notes, Tips & Common Mistakes

  • stop waits for graceful shutdown; use kill for immediate termination
  • Stopped containers retain their state and can be restarted
  • Use restart for applying configuration changes that don't require rebuild

๐Ÿ”น Command: docker rm / docker rmi

โœ”๏ธ What It Does

  • docker rm: Removes one or more containers
  • docker rmi: Removes one or more images

โœ”๏ธ Syntax Examples

# Basic: Remove a stopped container
docker rm my-container

# Real-world: Force remove running container
docker rm -f my-container

# Production: Remove all stopped containers
docker rm $(docker ps -aq -f status=exited)

# Remove unused images
docker rmi $(docker images -f "dangling=true" -q)

โœ”๏ธ Notes, Tips & Common Mistakes

  • Cannot remove running containers without -f (force)
  • Cannot remove images used by containers
  • Use docker container prune for safer cleanup
  • -v flag removes associated anonymous volumes

๐Ÿ”น Command: docker volume

โœ”๏ธ What It Does
Manages Docker volumes for persistent data storage. Volumes outlive containers and can be shared between containers.

โœ”๏ธ Syntax Examples

# Basic: Create a volume
docker volume create my-data

# Real-world: List and inspect volumes
docker volume ls
docker volume inspect my-data

# Production: Create and use volume with container
docker run -d \
  --name postgres \
  -v pgdata:/var/lib/postgresql/data \
  postgres:15

# Cleanup unused volumes
docker volume prune

โœ”๏ธ Notes, Tips & Common Mistakes

  • Named volumes persist after container deletion
  • Anonymous volumes (no name) are harder to manage
  • Use volumes for databases, not bind mounts
  • Backup volumes with docker run --rm -v

๐Ÿ”น Command: docker network

โœ”๏ธ What It Does
Manages Docker networks for container communication. Containers on the same network can communicate using container names as hostnames.

โœ”๏ธ Syntax Examples

# Basic: Create a network
docker network create my-network

# Real-world: Create with specific driver and subnet
docker network create --driver bridge --subnet 172.20.0.0/16 app-network

# Production: Connect containers to network
docker network connect app-network my-container

# Inspect network details
docker network inspect app-network

โœ”๏ธ Notes, Tips & Common Mistakes

  • Default bridge network doesn't support DNS resolution
  • Custom networks enable container name-based communication
  • Use host network for maximum performance (loses isolation)
  • overlay networks for Docker Swarm multi-host setups

Intermediate & Advanced Commands

๐Ÿ”น Multi-Stage Builds

โœ”๏ธ What It Does
Optimizes image size by using multiple FROM statements, keeping only necessary artifacts in the final image.

โœ”๏ธ Example Dockerfile

# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]

โœ”๏ธ Benefits

  • Smaller final images (exclude build tools)
  • Faster deployments
  • Better security (fewer attack surfaces)

๐Ÿ”น Cleanup Commands

โœ”๏ธ System Prune

# Remove all unused data (containers, networks, images, cache)
docker system prune -a

# Prune with volume cleanup
docker system prune -a --volumes

# Show what would be removed
docker system df

โœ”๏ธ Targeted Cleanup

# Remove unused images
docker image prune -a

# Remove build cache
docker builder prune

# Remove stopped containers
docker container prune

# Remove unused volumes
docker volume prune

โœ”๏ธ Notes

  • Run cleanup regularly in CI/CD environments
  • Use --filter for selective cleanup: --filter "until=24h"
  • Always review before pruning in production

๐Ÿ”น Container Inspection & Debugging

# View detailed container information
docker inspect my-container

# Check resource usage in real-time
docker stats

# View container processes
docker top my-container

# Monitor events
docker events --filter container=my-container

# Export container filesystem
docker export my-container > container.tar

๐Ÿ”น Image Management

# Tag an image
docker tag myapp:latest myregistry.io/myapp:v1.0.0

# Push to registry
docker push myregistry.io/myapp:v1.0.0

# Save image to tar file
docker save myapp:latest > myapp.tar

# Load image from tar file
docker load < myapp.tar

# View image history and layers
docker history myapp:latest

๐Ÿ”น Copy Files

# Copy from container to host
docker cp my-container:/app/logs/app.log ./local-logs/

# Copy from host to container
docker cp ./config.json my-container:/app/config/

# Copy entire directory
docker cp my-container:/app/data ./backup/

Docker Compose Mastery

๐Ÿ”น Command: docker compose up

โœ”๏ธ What It Does
Starts all services defined in docker-compose.yml. Creates networks, volumes, and containers as needed.

โœ”๏ธ Syntax Examples

# Basic: Start all services
docker compose up

# Real-world: Detached mode with build
docker compose up -d --build

# Production: Specific services with scaling
docker compose up -d --scale worker=3 api worker

โœ”๏ธ Example docker-compose.yml

version: '3.8'

services:
  web:
    build: .
    ports:
      - "3000:3000"
    environment:
      - NODE_ENV=production
      - DATABASE_URL=postgres://db:5432/myapp
    depends_on:
      - db
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
      interval: 30s
      timeout: 10s
      retries: 3

  db:
    image: postgres:15-alpine
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      - POSTGRES_PASSWORD=${DB_PASSWORD}
    restart: unless-stopped

volumes:
  pgdata:

๐Ÿ”น Command: docker compose down

โœ”๏ธ What It Does
Stops and removes containers, networks created by up. Volumes persist unless specified.

# Basic: Stop and remove containers
docker compose down

# Remove volumes too
docker compose down -v

# Remove images as well
docker compose down --rmi all

๐Ÿ”น Command: docker compose logs

# View all service logs
docker compose logs

# Follow specific service
docker compose logs -f web

# Last 100 lines from all services
docker compose logs --tail=100

๐Ÿ”น Command: docker compose build

# Build all services
docker compose build

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

# Build specific service
docker compose build web

๐Ÿ”น Environment Variables & .env Files

โœ”๏ธ .env File Example

NODE_ENV=production
DB_PASSWORD=secure_password_here
API_KEY=your_api_key
PORT=3000

โœ”๏ธ Usage in docker-compose.yml

services:
  app:
    environment:
      - NODE_ENV=${NODE_ENV}
      - DB_PASSWORD=${DB_PASSWORD}
    ports:
      - "${PORT}:3000"

๐Ÿ”น Production Best Practices

โœ”๏ธ Healthchecks

healthcheck:
  test: ["CMD-SHELL", "curl -f http://localhost/health || exit 1"]
  interval: 30s
  timeout: 10s
  retries: 3
  start_period: 40s

โœ”๏ธ Resource Limits

services:
  web:
    deploy:
      resources:
        limits:
          cpus: '0.5'
          memory: 512M
        reservations:
          cpus: '0.25'
          memory: 256M

โœ”๏ธ Logging Configuration

services:
  web:
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

Troubleshooting & Best Practices

Common Issues & Solutions

Container won't start

# Check logs
docker logs container-name

# Inspect container config
docker inspect container-name

# Check if port is already in use
netstat -an | grep PORT_NUMBER

Out of disk space

# Check Docker disk usage
docker system df

# Clean up
docker system prune -a --volumes

Network connectivity issues

# Inspect network
docker network inspect network-name

# Test connectivity between containers
docker exec container1 ping container2

Security Best Practices

  1. Never run as root in production
  2. Use specific image tags, not :latest
  3. Scan images for vulnerabilities: docker scan myimage:tag
  4. Use secrets management for sensitive data
  5. Limit container resources
  6. Keep images updated regularly
  7. Use multi-stage builds to reduce attack surface

Performance Optimization

  1. Use .dockerignore to reduce build context
  2. Order Dockerfile commands by change frequency
  3. Leverage build cache effectively
  4. Use Alpine-based images when possible
  5. Combine RUN commands to reduce layers
  6. Use volumes for I/O intensive operations

๐ŸŽ“ Master Class Complete
This reference covers essential Docker commands for enterprise-level engineering. Bookmark this guide and refer to it as your Docker knowledge base.