Every essential Docker command in one place — containers, images, volumes, networks, Compose, Dockerfile, registries and more. Built for DevOps beginners to production engineers.
Run, stop, start, restart and remove containers. Understand the container lifecycle and key runtime flags.
# Basic run docker run nginx # Detached + named + port mapping docker run -d --name webserver \ -p 8080:80 nginx # Interactive shell docker run -it ubuntu bash # Remove on exit docker run --rm alpine echo "hello" # Set env variable docker run -e MYSQL_ROOT_PASSWORD=secret \ mysql:8 # Limit CPU & memory docker run --cpus="1.5" --memory="512m" \ nginx
# List running containers docker ps # List all containers (incl. stopped) docker ps -a # Stop / start / restart docker stop webserver docker start webserver docker restart webserver # Pause / unpause docker pause webserver docker unpause webserver # Remove container docker rm webserver # Force-remove running container docker rm -f webserver # Remove all stopped containers docker container prune
# Open interactive shell docker exec -it webserver bash # Run single command docker exec webserver ls /var/www # Copy file TO container docker cp ./config.json \ webserver:/app/config.json # Copy file FROM container docker cp \ webserver:/app/logs/app.log ./ # Rename container docker rename webserver nginx_prod
| Flag | Description | Example |
|---|---|---|
-d |
Detached (background) mode | docker run -d nginx |
-it |
Interactive terminal | docker run -it ubuntu bash |
--name |
Assign a container name | --name myapp |
-p host:ctr |
Publish port mapping | -p 8080:80 |
-v src:dst |
Bind mount volume | -v /data:/app/data |
-e KEY=VAL |
Set environment variable | -e NODE_ENV=production |
--rm |
Remove container on exit | docker run --rm alpine sh |
--network |
Connect to network | --network mynet |
--restart |
Restart policy | --restart unless-stopped |
Pull, build, tag, push, inspect and remove Docker images. Understand layers and best practices for lean images.
# Pull latest tag docker pull nginx # Pull specific tag docker pull node:20-alpine # List local images docker images docker image ls # Show image history/layers docker history nginx # Remove image docker rmi nginx docker image rm nginx # Remove all unused images docker image prune -a # Search Docker Hub docker search postgres
# Build from current directory docker build -t myapp:1.0 . # Build from custom Dockerfile docker build -f Dockerfile.prod \ -t myapp:prod . # Build with build args docker build \ --build-arg NODE_ENV=production \ -t myapp:latest . # No cache build docker build --no-cache \ -t myapp:fresh . # Multi-platform build (Buildx) docker buildx build \ --platform linux/amd64,linux/arm64 \ -t myapp:multi --push .
# Tag an existing image docker tag myapp:1.0 \ myuser/myapp:1.0 # Save image to tar file docker save -o myapp.tar myapp:1.0 # Load image from tar file docker load -i myapp.tar # Export container filesystem docker export mycontainer > fs.tar # Import filesystem as image docker import fs.tar myimage:v1 # Commit container changes docker commit mycontainer \ myimage:snapshot
Persist data with named volumes, bind mounts and tmpfs. Volumes survive container restarts and removals.
# Create a named volume docker volume create pgdata # List all volumes docker volume ls # Inspect a volume docker volume inspect pgdata # Remove a volume docker volume rm pgdata # Remove all unused volumes docker volume prune # Mount named volume to container docker run -v pgdata:/var/lib/postgresql/data \ postgres:15 # Bind mount (host path) docker run -v /home/user/data:/app/data \ myapp
| Type | Syntax | Best For |
|---|---|---|
| Named Volume | -v pgdata:/data |
DB persistence, prod data |
| Bind Mount | -v /host/path:/ctr |
Dev: live code reload |
| tmpfs | --tmpfs /run |
Secrets, temp data in RAM |
| Anonymous | -v /data |
Throwaway data (not recommended) |
# tmpfs mount (RAM-only) docker run --tmpfs /run:rw,size=64m \ nginx # Read-only bind mount docker run -v /config:/etc/config:ro \ myapp
Create and manage Docker networks. Connect containers so they can talk to each other using service names as DNS.
# Create a bridge network docker network create mynet # List all networks docker network ls # Inspect a network docker network inspect mynet # Connect container to network docker network connect mynet webserver # Disconnect container docker network disconnect mynet webserver # Remove network docker network rm mynet # Remove unused networks docker network prune
| Driver | Use Case |
|---|---|
| bridge | Default; isolated containers on same host |
| host | Share host network stack (Linux only) |
| overlay | Multi-host (Swarm / Kubernetes) |
| macvlan | Assign real MAC addr, appear on LAN |
| none | No networking, fully isolated |
# Map host 8080 → container 80 docker run -p 8080:80 nginx # Bind to specific host IP docker run -p 127.0.0.1:8080:80 nginx # Map random host port docker run -P nginx # Show port mappings docker port webserver # Create overlay network (Swarm) docker network create \ --driver overlay my_overlay
Write efficient Dockerfiles using multi-stage builds, layer caching strategies and best practices for minimal image sizes.
| Instruction | Description |
|---|---|
FROM |
Base image (must be first instruction) |
RUN |
Execute command in a new layer |
COPY |
Copy files from build context |
ADD |
Like COPY + supports URLs and tar extraction |
WORKDIR |
Set working directory for subsequent instructions |
ENV |
Set environment variable (persists in container) |
ARG |
Build-time variable (not in final image) |
EXPOSE |
Document which port the container uses |
CMD |
Default command (overridable) |
ENTRYPOINT |
Fixed entry command (CMD provides args) |
VOLUME |
Declare a mount point |
USER |
Set running user |
LABEL |
Add metadata key=value |
HEALTHCHECK |
Define container health test |
# ── Stage 1: build ───────────────── FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci --only=production COPY . . RUN npm run build # ── Stage 2: runtime ─────────────── FROM node:20-alpine WORKDIR /app # Copy only build artifacts COPY --from=builder /app/dist ./dist COPY --from=builder /app/node_modules ./node_modules USER node EXPOSE 3000 HEALTHCHECK --interval=30s CMD \ wget -qO- http://localhost:3000/health CMD ["node", "dist/index.js"]
FROM node:20-alpine
not latest
for reproducible buildsRUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*
USER app
instruction before CMD for security hardeningDefine and run multi-container applications with a single YAML file. Essential for local development and CI environments.
# Start all services (detached) docker compose up -d # Build + start docker compose up --build # Stop and remove containers docker compose down # Stop + remove volumes too docker compose down -v # View running services docker compose ps # View logs (follow) docker compose logs -f # Scale a service docker compose up --scale web=3 # Exec into a service docker compose exec web sh
services: web: build: . ports: - "3000:3000" environment: DATABASE_URL: postgres://user:pass@db/app REDIS_URL: redis://cache:6379 depends_on: - db - cache db: image: postgres:15-alpine volumes: - pgdata:/var/lib/postgresql/data environment: POSTGRES_PASSWORD: pass cache: image: redis:7-alpine volumes: pgdata:
| Key | Description |
|---|---|
image |
Image to use for the service |
build |
Path to Dockerfile context |
ports |
Host:container port mappings |
volumes |
Volume mounts |
environment |
Environment variables |
env_file |
Load vars from .env file |
depends_on |
Startup order dependency |
networks |
Networks to join |
restart |
Restart policy |
healthcheck |
Health probe definition |
deploy |
Replicas & resource limits |
Authenticate with Docker Hub, push and pull images from public and private registries including ECR, GCR and GHCR.
# Login to Docker Hub docker login # Login with username docker login -u myuser # Tag for Docker Hub docker tag myapp:1.0 myuser/myapp:1.0 docker tag myapp:1.0 myuser/myapp:latest # Push to Docker Hub docker push myuser/myapp:1.0 docker push myuser/myapp:latest # Pull from Docker Hub docker pull myuser/myapp:1.0 # Logout docker logout
# AWS ECR login aws ecr get-login-password \ --region us-east-1 | \ docker login --username AWS \ --password-stdin \ 123456789.dkr.ecr.us-east-1.amazonaws.com # Push to ECR docker push \ 123456789.dkr.ecr.us-east-1.amazonaws.com/myapp:latest # GitHub Container Registry (GHCR) docker login ghcr.io \ -u USERNAME -p $GITHUB_TOKEN docker tag myapp:1.0 \ ghcr.io/myuser/myapp:1.0 docker push ghcr.io/myuser/myapp:1.0
Read container logs, inspect configuration, monitor resource usage and debug running workloads.
# Show all logs docker logs webserver # Follow (tail -f) docker logs -f webserver # Last 50 lines docker logs --tail 50 webserver # Logs since timestamp docker logs --since "2024-01-01T10:00" \ webserver # Include timestamps docker logs -t webserver # Show stderr only docker logs --stderr webserver
# Full JSON metadata docker inspect webserver # Get container IP address docker inspect -f \ '{{.NetworkSettings.IPAddress}}' \ webserver # Get mount info docker inspect -f \ '{{json .Mounts}}' webserver # Get all env vars docker inspect -f \ '{{.Config.Env}}' webserver # Inspect an image docker inspect nginx:latest
# Live resource usage (all) docker stats # Stats for one container docker stats webserver # One-shot stats (no stream) docker stats --no-stream # Show running processes docker top webserver # List changed files docker diff webserver # Get container exit code docker inspect -f \ '{{.State.ExitCode}}' webserver # Wait for container to stop docker wait webserver
Free disk space, manage Docker daemon settings and view system-wide information.
# Remove stopped containers docker container prune # Remove dangling images docker image prune # Remove ALL unused images docker image prune -a # Remove unused volumes docker volume prune # Remove unused networks docker network prune # ⚠️ Remove ALL unused objects docker system prune # ⚠️ Prune including volumes docker system prune -a --volumes # Skip confirmation prompt docker system prune -f
# Docker version docker version docker --version # Daemon info (storage, OS, etc.) docker info # Disk usage breakdown docker system df # Verbose disk usage docker system df -v # View system events (live) docker events # Events in time range docker events \ --since "1h" --until "0h"
Cluster multiple Docker hosts, deploy services with replicas and perform rolling updates with zero downtime.
# Initialize swarm on manager docker swarm init \ --advertise-addr 192.168.1.10 # Get join token for workers docker swarm join-token worker # Get join token for managers docker swarm join-token manager # Join as worker (run on worker node) docker swarm join \ --token SWMTKN-... \ 192.168.1.10:2377 # List nodes in swarm docker node ls # Leave swarm docker swarm leave --force
# Create a service docker service create \ --name web --replicas 3 \ -p 80:80 nginx # List services docker service ls # Service tasks (pods) docker service ps web # Scale a service docker service scale web=5 # Rolling update docker service update \ --image nginx:1.25 web # Remove service docker service rm web
# Deploy a stack docker stack deploy \ -c compose.yaml mystack # List stacks docker stack ls # List stack services docker stack services mystack # List stack tasks docker stack ps mystack # Remove stack docker stack rm mystack # Swarm secrets echo "s3cr3t" | \ docker secret create db_pass - docker secret ls
Expand your DevOps & developer toolkit with our free reference sheets.