Skip to content

pinkpixel-dev/the-definitive-docker-codex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 

Repository files navigation

🐳 The Definitive Docker Codex

License: MIT

Docker Codex

This cheat sheet is a practical, one-stop reference for working with Docker. It covers the core concepts, container lifecycle commands, image and volume management, debugging workflows, Dockerfile and Compose patterns, cleanup, security, and newer tools like Docker Scout, Docker Model Runner, and Docker MCP—so you can find the right command or concept quickly without digging through scattered docs.

Table of Contents

  1. Core Docker Concepts
  2. Container Lifecycle
  3. Inspecting & Debugging Containers
  4. Images
  5. Volumes & Bind Mounts
  6. Resource Limits
  7. Copying Files
  8. Logs, Stats & Monitoring
  9. Dockerfile Cheatsheet
  10. Docker Compose Cheatsheet
  11. Docker Swarm / Services
  12. Cleanup Commands
  13. Docker Scout Security
  14. Docker Model Runner
  15. Docker MCP
  16. Best Practices

Core Docker Concepts

Term Meaning
Image A read-only template used to create containers
Container A running (or stopped) instance of an image
Volume Persistent storage managed by Docker
Bind Mount Maps a host folder/file into a container
Dockerfile A recipe for building an image
Compose A way to define and run multi-container apps

Container Lifecycle

Most Common Commands

Command What it does
docker run <image> Create and start a new container
docker create <image> Create a container without starting it
docker start <container> Start a stopped container
docker stop <container> Gracefully stop a running container
docker kill <container> Force-stop a running container immediately
docker restart <container> Restart a container
docker rm <container> Remove a stopped container
docker rm -f <container> Force remove a running container

Common Examples

docker run nginx
docker run -d --name mynginx -p 8080:80 nginx
docker create -it fedora bash
docker start -ai <container_id>
docker stop mynginx
docker restart mynginx
docker rm mynginx

Useful Notes

  • docker run = docker create + docker start
  • docker stop sends SIGTERM, then SIGKILL after a timeout
  • docker kill is immediate and less polite 😈

Inspecting & Debugging Containers

Container Listing

Command Description
docker ps Show running containers
docker ps -a Show all containers
docker top <container> Show processes running inside container
docker inspect <container> Show detailed JSON metadata
docker diff <container> Show file changes inside container
docker ps
docker ps -a
docker top mynginx
docker inspect mynginx
docker diff mynginx

Exec / Attach / Shell Access

Command Description
docker exec -it <container> bash Open interactive shell
docker exec -it <container> sh Open shell (for smaller images like Alpine)
docker attach <container> Attach to the main running process
docker exec -it mynginx bash
docker exec -it alpinebox sh
docker attach mycontainer

Tip: Prefer docker exec over docker attach for debugging.


Images

Image Commands

Command Description
docker images List local images
docker pull <image> Download image from registry
docker push <image> Push image to registry
docker build -t <name> . Build image from Dockerfile
docker tag <image> <new_tag> Tag image
docker rmi <image> Remove image
docker history <image> Show image layer history
docker inspect <image> Show image metadata
docker images
docker pull nginx
docker build -t myapp .
docker tag myapp myrepo/myapp:latest
docker push myrepo/myapp:latest
docker rmi myapp

Save / Load / Export / Import

Command Description
docker save <image> -o image.tar Save image as tarball
docker load -i image.tar Load image from tarball
docker export <container> > container.tar Export container filesystem
docker import container.tar myimage:latest Import filesystem as image
docker save nginx -o nginx.tar
docker load -i nginx.tar
docker export mycontainer > mycontainer.tar
docker import mycontainer.tar myimage:latest

Volumes & Bind Mounts

Quick Difference

Type Best for Example
Volume Docker-managed persistent storage -v mydata:/data
Bind Mount Mounting host files/folders -v ./app:/app

Bind Mount Examples

# Read-only
docker run -v c:\ContainerData:c:\data:ro myimage

# Read-write
docker run -v c:\ContainerData:c:\data:rw myimage

# Read-write (default)
docker run -v c:\ContainerData:c:\data myimage

Real Examples

docker run -itd -p 8030:80 -m 1GB --name nginx1 -v c:/html:/usr/share/nginx/html nginx

docker run -itd -p 8040:80 -m 1GB --name nginx2 -v c:/html:/usr/share/nginx/html:ro nginx:v2

Named Volumes

docker volume create mydata
docker run -v mydata:/app/data myimage
docker volume ls
docker volume inspect mydata
docker volume rm mydata

Resource Limits

Memory Limits

Flag Meaning
--memory / -m Hard memory limit
--memory-swap Total memory + swap
--memory-reservation Soft memory reservation
docker run -d -p 8081:80 --memory=20m --memory-swap=20m nginx
docker run -d --memory-reservation=250m --name mymem1 alpine:3.8 sleep 3600

CPU Limits

Flag Meaning
--cpus Limit number of CPU cores
--cpu-period + --cpu-quota Older CPU throttling method
--cpu-shares Relative CPU priority
# Docker 1.13+
docker run -it --cpus=".5" ubuntu /bin/bash

# Older syntax
docker run -it --cpu-period=100000 --cpu-quota=50000 ubuntu /bin/bash
docker run -it --cpu-shares="512" ubuntu /bin/bash

Copying Files

docker cp

Host → Container

docker cp Dockerfile 779eb8148aa7:/tmp/Dockerfile
docker cp Dockerfile 779eb8148aa7:/tmp/Dockerfile123

Container → Host

docker cp 779eb8148aa7:/tmp/Dockerfile123 Dockerfile_Delete

Copy Folder

docker cp /home/captain/my_dir ubu_container:/home
docker cp ubu_container:/home/my_dir /home/captain

Syntax

docker cp <host_path> <container>:<container_path>
docker cp <container>:<container_path> <host_path>

Logs, Stats & Monitoring

Logs

docker logs <container>
docker logs -f <container>

Example:

docker logs 779eb8148aa7 --follow

Live Resource Usage

docker stats

Example:

docker run -itd -p 8030:80 --name nginx7 -v c:/html:/usr/share/nginx/html:ro nginx:v2
docker stats

Sample Output

CONTAINER ID   NAME     CPU %   MEM USAGE / LIMIT   MEM %   NET I/O   BLOCK I/O   PIDS
779eb8148aa7   nginx7   0.00%   1.914MiB / 8.75GiB  0.02%   906B/0B   0B/4.1kB    2

Useful docker run Flags

Common Runtime Flags

Flag Description
-d Detached mode
-it Interactive terminal
--name Name the container
-p host:container Publish ports
-v host:container Mount volume / bind mount
-e KEY=value Set environment variable
--env-file file Load env vars from file
-w <dir> Set working directory
--privileged Give elevated privileges
--rm Auto-remove when container exits

Environment Variables

docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash

docker run --env VAR1=value1 --env VAR2=value2 ubuntu env | grep VAR

Expected:

VAR1=value1
VAR2=value2

Working Directory (-w)

docker run -w /path/to/dir/ -it ubuntu pwd
  • Runs the command inside /path/to/dir/
  • If the directory doesn’t exist, Docker creates it inside the container

Example:

docker run -itd -p 8050:80 -m 1GB --name nginx3 -w /usr/share/nginx/html -v c:/html:/usr/share/nginx/html nginx

Privileged Mode

Without --privileged:

docker run -ti --rm ubuntu bash
mount -t tmpfs none /mnt
# permission denied

With --privileged:

docker run -ti --privileged ubuntu bash
mount -t tmpfs none /mnt
df -h

Warning: --privileged is powerful and risky. Use it only when you truly need low-level system access.


Dockerfile Cheatsheet

Common Instructions

Instruction Purpose
FROM Base image
WORKDIR Set working directory
COPY Copy files into image
ADD Copy files, extract archives, allow remote URLs
RUN Execute commands during build
ENV Set environment variables
USER Set default user
CMD Default command
ENTRYPOINT Main executable
EXPOSE Document container port

Example Dockerfile

FROM node:20-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

ENV NODE_ENV=production
EXPOSE 3000

CMD ["npm", "start"]

Multi-Stage Build Example

# Build stage
FROM golang:1.16 AS build_stage
WORKDIR /app
COPY . .
RUN go build -o my_app

# Runtime stage
FROM alpine:latest AS runtime_stage
WORKDIR /app
COPY --from=build_stage /app/my_app /app/my_app
CMD ["/app/my_app"]

Why use multi-stage builds?

  • Smaller final images
  • Better security
  • Fewer dependencies in production
  • Faster deploys

That’s not “nice to have” territory — that’s less garbage in prod territory 💀


Docker Compose Cheatsheet

Modern Docker uses docker compose (space) instead of older docker-compose (hyphen). Both may still work depending on your setup.

Core Commands

Command Description
docker compose up Start services
docker compose up -d Start in background
docker compose down Stop and remove services
docker compose start Start existing services
docker compose stop Stop services
docker compose pause Pause services
docker compose unpause Resume paused services
docker compose ps List services
docker compose logs -f Follow service logs
docker compose build Build service images

Minimal Example

services:
  web:
    build:
      context: ./Path
      dockerfile: Dockerfile
    ports:
      - "5000:5000"
    volumes:
      - .:/code

  redis:
    image: redis

Common Compose Options

Build / Image

services:
  web:
    build: .

  web-dev:
    build:
      context: ./dir
      dockerfile: Dockerfile.dev

  db:
    image: postgres:latest

Ports / Expose

services:
  app:
    image: my-app-image:latest
    ports:
      - "3000"
      - "8000:80"
    expose:
      - "3000"
  • ports = available to host
  • expose = internal to other containers only

Commands / Entrypoint

services:
  app:
    command: bundle exec thin -p 3000
    # or
    command: [bundle, exec, thin, -p, 3000]

    entrypoint: /app/start.sh
    # or
    entrypoint: [php, -d, vendor/bin/phpunit]

Environment Variables

services:
  app:
    environment:
      RACK_ENV: development
      API_KEY: abc123

Or:

services:
  app:
    environment:
      - RACK_ENV=development
      - API_KEY=abc123

Or load from files:

services:
  app:
    env_file:
      - .env
      - .development.env

Volumes

services:
  db:
    volumes:
      - /var/lib/mysql
      - ./_data:/var/lib/mysql

Dependencies

services:
  web:
    depends_on:
      - db
      - redis

Links (Legacy)

services:
  web:
    links:
      - db:database
      - redis

links is considered legacy. Prefer networks and service names.

Labels

services:
  web:
    labels:
      com.example.description: "Accounting web app"

DNS

services:
  web:
    dns:
      - 8.8.8.8
      - 8.8.4.4

Devices

services:
  web:
    devices:
      - "/dev/ttyUSB0:/dev/ttyUSB0"

External Links

services:
  web:
    external_links:
      - redis_1
      - project_db_1:mysql

Extra Hosts

services:
  web:
    extra_hosts:
      - "somehost:192.168.1.100"

Docker Swarm / Services

Service Commands

Command Description
docker service ls List swarm services
docker stack services <stack> List services in a stack
docker service logs <service> Show service logs
docker service scale <service>=<replicas> Scale service
docker service ls
docker stack services mystack
docker service logs mystack_web
docker service scale mystack_web=3

Cleanup Commands

Containers

Stop and remove all containers

docker stop $(docker ps -aq)
docker rm $(docker ps -aq)

One-liner

docker stop $(docker ps -aq); docker rm $(docker ps -aq)

Force remove all containers

docker rm -f $(docker ps -aq)

Images

Remove all images

docker rmi $(docker images -q)

Force remove all images

docker rmi -f $(docker images -q)

Remove specific images

docker rmi -f b00ea124ed62 529165268aa2 0c45f7936948

Cleanup / Prune

Command Description
docker image prune Remove dangling images
docker image prune -a Remove all unused images
docker volume prune Remove unused networks
docker system prune Remove unused containers, networks, images
docker system prune -a --volumes Aggressive full cleanup
docker image prune
docker system prune
docker system prune -a --volumes

Warning: prune commands can absolutely nuke stuff you meant to keep. Read before you smash Enter.


Docker Scout Security

Docker Scout helps scan images for vulnerabilities and generate SBOMs.

Core Commands

Command Description
docker scout cves IMAGE Scan image for CVEs
docker scout quickview IMAGE Quick vulnerability summary
docker scout compare --to IMAGE1 IMAGE2 Compare image vulnerabilities
docker scout sbom IMAGE Generate SBOM
docker scout policy IMAGE Check compliance policies

Useful Variants

docker scout cves myapp:latest
docker scout cves --only-severity critical,high myapp:latest
docker scout cves --only-package openssl myapp:latest
docker scout quickview myapp:latest
docker scout compare --to redis:6.0 redis:6-bullseye
docker scout sbom myapp:latest

Export Reports

docker scout cves --format sarif --output report.sarif.json myapp:latest
docker scout cves --format json --output report.json myapp:latest
docker scout sbom --format json --output sbom.json myapp:latest

CI/CD Example

docker build -t myapp:latest .
docker scout cves myapp:latest --exit-code --only-severity critical,high

Docker Model Runner

Run local AI models with Docker. Pretty damn cool.

Core Commands

Command Description
docker model pull MODEL_NAME Download a model
docker model run MODEL_NAME "prompt" Run inference
docker model ls List downloaded/cached models
docker model list List available models
docker model rm MODEL_NAME Remove model
docker model inspect MODEL_NAME Show model metadata
docker model status Show runner status
docker model version Show version

Examples

docker model pull ai/smollm2:360M-Q4_K_M
docker model run ai/smollm2:360M-Q4_K_M "Explain Docker containers"

docker model pull ai/llama3.3:70B-Q4_K_M
docker model run ai/llama3.3:70B-Q4_K_M "Write a Python function to sort a list"

OpenAI-Compatible API

Enable TCP access

docker desktop enable model-runner --tcp 12434

Endpoints

# For containers
http://model-runner.docker.internal/engines/v1

# For host apps
http://localhost:12434/engines/llama.cpp/v1

Example Request

curl http://localhost:12434/engines/llama.cpp/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "ai/smollm2",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is Docker?"}
    ]
  }'

Compose Integration Example

services:
  my-app:
    build: .
    environment:
      - MY_MODEL_URL=http://model-runner.docker.internal/engines/v1
      - MY_MODEL_MODEL=ai/smollm2
    depends_on:
      - my-model

  my-model:
    image: ai/smollm2:360M-Q4_K_M
    x-model-runner: true

Docker MCP

Docker MCP lets AI tools securely interact with tools and services.

MCP Server Commands

Command Description
docker mcp server list List available MCP servers
docker mcp server inspect SERVER_NAME Show server details
docker mcp server enable SERVER_NAME Enable server
docker mcp server disable SERVER_NAME Disable server
docker mcp server reset Disable all servers

MCP Tool Commands

Command Description
docker mcp tools call TOOL_NAME [args...] Call an MCP tool
docker mcp server list
docker mcp server inspect github
docker mcp server enable github
docker mcp tools call TOOL_NAME

Best Practices

Practical Advice

1) Name your containers

docker run -d --name postgres-db postgres

This is way better than working with random cryptid-ass IDs.

2) Use .env files for local config

docker run --env-file .env myapp

3) Prefer bind mounts for development

docker run -v $(pwd):/app myapp

4) Prefer named volumes for persistent app data

docker run -v postgres-data:/var/lib/postgresql/data postgres

5) Use multi-stage builds for production

Keeps your images lean, fast, and less cursed.

6) Avoid latest in production

postgres:16
node:20-alpine
nginx:1.27-alpine

7) Use health checks in Compose when possible

services:
  db:
    image: postgres:16
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

8) Don’t casually use --privileged

If a container needs god mode, make sure it’s for a real reason, not because some Stack Overflow goblin said so.


Fast Copy/Paste Section

Stop / Remove Everything

# Stop all containers
docker stop $(docker ps -aq)

# Remove all containers
docker rm $(docker ps -aq)

# Force remove all containers
docker rm -f $(docker ps -aq)

# Remove all images
docker rmi -f $(docker images -q)

Nginx Quick Test

docker run -d --name mynginx -p 8080:80 nginx

Shell into Running Container

docker exec -it mynginx bash

Build + Run Local App

docker build -t myapp .
docker run -p 3000:3000 myapp

Compose Up / Down

docker compose up -d
docker compose down

View Logs / Stats

docker logs -f myapp
docker stats

Final Note

This cheatsheet is meant to be:

  • easy to skim
  • useful
  • good for beginners and intermediates
  • less ugly than 90% of random Docker notes on the internet

About

A massive Docker cheat sheet and reference guide covering containers, images, volumes, Compose, debugging, security, and modern Docker tools like Scout, Model Runner, and MCP.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors