Post

Docker Cheat Sheet for Linux Sysadmins

Docker Cheat Sheet for Linux Sysadmins

Docker Cheat Sheet

A quick reference guide for Linux sysadmins managing Docker containers.


πŸ”Ή Common Container Commands

  • Run a Container:
    1
    
    docker run -it ubuntu
    
  • Run a Container in Background:
    1
    
    docker run -d nginx
    
  • List Running Containers:
    1
    
    docker ps
    
  • List All Containers (including stopped):
    1
    
    docker ps -a
    
  • Stop a Container:
    1
    
    docker stop <container_id>
    
  • Start a Container:
    1
    
    docker start <container_id>
    
  • Remove a Container:
    1
    
    docker rm <container_id>
    
  • Remove All Stopped Containers:
    1
    
    docker container prune  # Removes all stopped containers to free up space
    

πŸ”Ή Docker Images

  • List Images:
    1
    
    docker images
    
  • Pull an Image:
    1
    
    docker pull ubuntu
    
  • Build an Image (from Dockerfile):
    1
    
    docker build -t myimage:latest .  # Builds an image from the Dockerfile in the current directory
    
  • Remove an Image:
    1
    
    docker rmi <image_id>  # Deletes an image by its ID
    
  • Remove Unused Images:
    1
    
    docker image prune  # Removes dangling images (untagged layers)
    

πŸ”Ή Docker Volumes

  • Create a Volume:
    1
    
    docker volume create my_volume  # Creates a named volume for persistent storage
    
  • List Volumes:
    1
    
    docker volume ls
    
  • Inspect a Volume:
    1
    
    docker volume inspect my_volume  # Shows detailed information about the volume
    
  • Remove a Volume:
    1
    
    docker volume rm my_volume  # Deletes a specific volume
    
  • Remove Unused Volumes:
    1
    
    docker volume prune  # Removes all unused volumes to free up space
    

πŸ”Ή Docker Networks

  • List Networks:
    1
    
    docker network ls
    
  • Create a Network:
    1
    
    docker network create my_network  # Creates a custom bridge network
    
  • Connect a Container to a Network:
    1
    
    docker network connect my_network <container_id>  # Adds a container to a specific network
    
  • Disconnect a Container from a Network:
    1
    
    docker network disconnect my_network <container_id>  # Removes a container from a specific network
    
  • Remove Unused Networks:
    1
    
    docker network prune  # Deletes all unused networks
    

πŸ”Ή Exec & Logs

  • Exec into a Running Container:
    1
    
    docker exec -it <container_id> /bin/bash  # Opens an interactive bash shell inside the container
    
  • Check Logs:
    1
    2
    
    docker logs <container_id>  # Displays logs from the container
    docker logs -f <container_id>   # Streams logs in real-time
    
  • Check Resource Usage:
    1
    
    docker stats  # Shows real-time resource usage statistics for running containers
    

πŸ”Ή Docker Compose

  • Start Services:
    1
    
    docker-compose up -d  # Starts all services defined in the docker-compose.yml file in detached mode
    
  • Stop Services:
    1
    
    docker-compose down  # Stops and removes all services and networks defined in the Compose file
    
  • View Logs:
    1
    
    docker-compose logs -f  # Streams logs from all services in real-time
    
  • Rebuild and Restart:
    1
    
    docker-compose up -d --build  # Rebuilds images and restarts services
    

πŸ”Ή Docker Compose Options

Docker Compose uses a docker-compose.yml file to define and run multi-container Docker applications. Below are the key options with explanations and examples:

Version

Specifies the Compose file format version.

1
version: '3.8'

Services

Defines the containers to be run.

1
2
3
4
5
services:
  web:
    image: nginx
    ports:
      - "80:80"

Build

Specifies build context and Dockerfile.

1
2
3
build:
  context: ./app  # Path to the directory containing the Dockerfile
  dockerfile: Dockerfile  # Name of the Dockerfile (optional if named 'Dockerfile')

Ports

Maps container ports to host ports. Format: hostport:containerport.

1
2
ports:
  - "8080:80"  # Maps port 8080 on the host to port 80 in the container

Volumes

Mounts host directories or volumes into containers. Format: hostpath:containerpath.

1
2
volumes:
  - ./data:/data  # Mounts the ./data directory on the host to /data in the container

Environment

Defines environment variables for the container.

1
2
environment:
  - NODE_ENV=production  # Sets the NODE_ENV variable to 'production'

Networks

Specifies custom networks for inter-container communication.

1
2
3
networks:
  my_network:
    driver: bridge  # Creates a bridge network named 'my_network'

Depends_on

Specifies service dependencies. Ensures a service starts only after its dependencies are started.

1
2
depends_on:
  - db  # Ensures the 'db' service starts before this service

Restart

Defines restart policies for containers.

1
restart: always  # Always restart the container if it stops

Command

Overrides the default command specified in the image.

1
command: ["npm", "start"]  # Runs 'npm start' instead of the default command

Healthcheck

Defines health checks for a service to monitor its status.

1
2
3
4
5
healthcheck:
  test: ["CMD", "curl", "-f", "http://localhost"]  # Runs a curl command to check health
  interval: 1m30s  # Time between health checks
  timeout: 10s     # Time to wait for a health check to complete
  retries: 3       # Number of retries before marking as unhealthy

πŸ”Ή Quick Recovery & Troubleshooting

🟒 Container Won’t Start

  • Check logs:
    1
    
    docker logs <container_id>
    
  • Inspect container:
    1
    
    docker inspect <container_id>
    

🟑 Image Issues

  • Remove broken images:
    1
    
    docker rmi <image_id>
    
  • Clean everything unused:
    1
    
    docker system prune -a
    

🟠 Network Connectivity Issues

  • Inspect container network:
    1
    
    docker inspect <container_id> | grep IPAddress
    
  • Restart Docker service:
    1
    
    systemctl restart docker
    

πŸ”΄ Out of Disk Space

  • Check disk usage:
    1
    
    docker system df
    
  • Remove unused objects:
    1
    
    docker system prune -a --volumes
    

πŸ”Ή Docker Tuning & Cleanup Flags

CommandPurpose
docker system pruneRemove stopped containers, unused networks, dangling images.
docker system prune -aAlso removes unused images (not just dangling).
docker builder pruneClean up build cache.
docker image prune -aRemove unused and dangling images.
docker volume pruneRemove unused volumes.
docker network pruneRemove unused networks.

⚠️ Tip: Use these regularly on dev/test systems to free up space. On production, prune carefully!


πŸ”Ή Security & Hardening

  • Run as Non-Root User (inside Dockerfile):
    1
    2
    
    RUN useradd -m appuser
    USER appuser
    
  • Limit Container Resources:
    1
    
    docker run -d --cpus="2" --memory="2g" nginx  # Restricts CPU and memory usage for the container
    
  • Drop Unnecessary Linux Capabilities:
    1
    
    docker run -d --cap-drop=ALL --cap-add=NET_BIND_SERVICE nginx  # Drops all capabilities except NET_BIND_SERVICE
    
  • Read-Only Filesystem:
    1
    
    docker run -d --read-only nginx  # Makes the container's filesystem read-only
    
  • Disable Privileged Mode (avoid --privileged unless absolutely required).
  • Use Docker Bench Security:
    1
    2
    3
    
    docker run -it --net host --pid host --cap-add audit_control \
      -v /var/lib:/var/lib -v /var/run/docker.sock:/var/run/docker.sock \
      docker/docker-bench-security  # Runs Docker Bench Security to check for security best practices
    
  • Scan Images for Vulnerabilities:
    1
    
    docker scan <image>  # Scans the image for known vulnerabilities
    
  • Enable Content Trust (sign/verify images):
    1
    
    export DOCKER_CONTENT_TRUST=1  # Enables Docker Content Trust for image signing and verification
    
  • Keep Docker Daemon Rootless (where supported):
    1
    
    dockerd-rootless-setuptool.sh install  # Sets up the Docker daemon to run in rootless mode
    

πŸ”Ή Legend (Docker Terminology)

  • Image – A template used to create containers. Think of it like a snapshot.
  • Container – A running instance of an image. Isolated environment with its own process tree.
  • Volume – Persistent storage for containers, survives restarts/deletions.
  • Network – Virtual network to connect containers together.
  • Dockerfile – Text file with instructions to build an image.
  • docker-compose.yml – Defines and runs multi-container Docker applications.
  • Dangling Image – An untagged image layer, usually from interrupted builds.
  • Bind Mount – Mount a host directory into a container (-v /host:/container).
  • OverlayFS – Default storage driver for Docker on most Linux distros.

πŸ”Ή Best Practices

  • Use docker-compose for multi-container setups.
  • Tag images with versions (myapp:1.0) instead of latest for reproducibility.
  • Regularly prune unused containers, images, and volumes:
    1
    
    docker system prune -a --volumes
    
  • Store Dockerfiles and docker-compose.yml in Git for version control.
  • Use healthchecks in Dockerfiles or Compose to monitor container health.
  • Limit container resources in production:
    1
    
    docker run -d --cpus="2" --memory="2g" nginx
    
  • Avoid running privileged containers unless absolutely required.
  • Automate vulnerability scans and patching pipelines.
This post is licensed under CC BY 4.0 by the author.