Skip to content

This is a cheatsheet-style repository I created while learning and practicing Docker. It includes a comprehensive README of essential Docker commands and a fully dockerized full-stack project with a TypeScript backend, Next.js frontend, and MongoDB—built to strengthen my understanding of containerization.

Notifications You must be signed in to change notification settings

shahadathhs/docker-cheatsheet

Repository files navigation

Docker Cheat Sheet: Beginner to Expert


🚀 Getting Started with Docker

Check Docker Installation

# Displays Docker version
docker --version

Docker Help Commands

# General help
docker --help
# Help for a specific command (e.g., run)
docker <command> --help

🧱 Docker Basics

Pull an Image

# Pulls an image from Docker Hub
docker pull <image-name>[:<tag>]

Important Flags/Options:

  • :tag — Specify image tag (default: latest)

Examples:

docker pull ubuntu:22.04

List Local Images

# Lists images stored locally
docker images [OPTIONS]

Important Flags/Options:

  • -a, --all — Show all images (default hides intermediate layers)
  • --filter, -f — Filter output based on conditions (e.g., "dangling=true")
  • --format — Pretty-print using a Go template (e.g., "{{.Repository}}: {{.Tag}}")
  • --no-trunc — Don’t truncate output
  • -q, --quiet — Only show numeric IDs

Examples:

docker images --filter "dangling=false" --format "{{.Repository}}:{{.Tag}} {{.Size}}"

Run a Container

docker run [OPTIONS] <image-name> [COMMAND] [ARG...]

Important Flags/Options:

  • -d, --detach — Run container in background and print container ID
  • -i, --interactive — Keep STDIN open even if not attached
  • -t, --tty — Allocate a pseudo-TTY (combine with -i for interactive shell)
  • --rm — Automatically remove the container when it exits
  • --name — Assign a name to the container
  • -p, --publish — Publish a container’s port(s) to the host (e.g., -p 8080:80)
  • -e, --env — Set environment variables (e.g., -e ENV_VAR=value)
  • -v, --volume — Bind mount a volume (e.g., -v host_path:container_path)
  • -w, --workdir — Working directory inside the container
  • --network — Connect a container to a network (e.g., --network my-network)
  • --user — Username or UID (e.g., --user 1000:1000)
  • --restart — Restart policy (no, on-failure[:max-retries], always, unless-stopped)

Examples:

# Interactive Ubuntu shell
docker run -it ubuntu:22.04 /bin/bash
# Run in background, name it "webapp", map port 8080 to 80, and remove on exit
docker run -d --name webapp --rm -p 8080:80 nginx:latest
# Run and mount local "mydata" folder to "/app/data" inside container
docker run -it -v $(pwd)/mydata:/app/data node:16-alpine sh

Run a Container in Detached Mode

docker run -d [OPTIONS] <image-name>

Same OPTIONS as docker run above.

Example:

docker run -d --name db-server -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:14

Name a Container on Run

# Assigns a custom name to the container
docker run --name <container-name> [OPTIONS] <image-name>

Example:

docker run --name my-redis -d redis:7

Auto-Remove Container on Exit

# Automatically removes the container filesystem after it exits
docker run --rm [OPTIONS] <image-name>

Example:

docker run --rm ubuntu:22.04 echo "Hello Docker"

Tag an Image

docker tag <image-id> <repository>/<image-name>:<tag>

Example:

# Tagging local image ID d1e3f to "myrepo/myapp:1.0"
docker tag d1e3f myrepo/myapp:1.0

Remove a Container

# Stop and remove a container in one command
docker rm [OPTIONS] <container-id or name>

Important Flags/Options:

  • -f, --force — Force the removal of a running container (uses SIGKILL)
  • -v, --volumes — Remove anonymous volumes associated with the container

Example:

docker rm -f -v old-container

Remove an Image

# Removes one or more images
docker rmi [OPTIONS] <image-name or ID>

Important Flags/Options:

  • -f, --force — Force removal of the image (even if tagged in multiple repositories)
  • --no-prune — Do not delete untagged parent images

Example:

docker rmi -f myrepo/myapp:1.0

🧩 Container Management

List Running Containers

docker ps [OPTIONS]

Important Flags/Options:

  • -a, --all — Show all containers (default shows just running)
  • -q, --quiet — Only display container IDs
  • --filter — Filter output (e.g., "status=exited", "name=myapp")
  • --format — Pretty-print using a Go template (e.g., "{{.ID}}: {{.Names}}")

Example:

docker ps --filter "status=exited" --format "{{.ID}}\t{{.Names}}"

List All Containers (including stopped)

docker ps -a [OPTIONS]

Same OPTIONS as docker ps above.

Stop a Container

docker stop [OPTIONS] <container-id or name> [<container-id or name>...]

Important Flags/Options:

  • -t, --time — Seconds to wait for stop before killing it (default: 10)

Example:

docker stop -t 5 my-redis

Start a Stopped Container

docker start [OPTIONS] <container-id or name> [<container-id or name>...]

Important Flags/Options:

  • -a, --attach — Attach STDOUT/STDIN and forward signals
  • -i, --interactive — Attach container’s STDIN

Example:

docker start -ai my-redis

View Container Logs

docker logs [OPTIONS] <container-id or name>

Important Flags/Options:

  • -f, --follow — Follow log output (like tail -f)
  • --since — Show logs since a timestamp (e.g., 2025-06-01T15:00:00)
  • --until — Show logs up to a timestamp
  • --tail — Number of lines to show from the end (e.g., --tail 100)
  • --timestamps — Show timestamps

Example:

docker logs -f --tail 50 my-redis

Execute a Command in a Running Container

docker exec [OPTIONS] <container-id or name> <command> [ARG...]

Important Flags/Options:

  • -d, --detach — Detached mode: run command in the background
  • -i, --interactive — Keep STDIN open even if not attached
  • -t, --tty — Allocate a pseudo-TTY
  • -u, --user — Username or UID (e.g., -u root)
  • -w, --workdir — Working directory inside the container

Example:

docker exec -it -u root my-container bash

Inspect a Container

docker inspect [OPTIONS] <container-id or name>

Important Flags/Options:

  • --format — Format output using a Go template (e.g., "{{json .Mounts}}")

Example:

docker inspect --format '{{.Config.Cmd}}' my-container

Rename a Container

docker rename <old-name> <new-name>

Example:

docker rename old-container new-container

Force Remove Running Container

docker rm -f <container-id or name>

Example:

docker rm -f praiseworthy-container

📡 Networking

List Networks

docker network ls [OPTIONS]

Important Flags/Options:

  • --filter — Filter output (e.g., "driver=bridge")
  • -q, --quiet — Only display network IDs

Example:

docker network ls --filter "driver=overlay"

Create a Network

docker network create [OPTIONS] <network-name>

Important Flags/Options:

  • --driver — Driver to manage the Network (default: bridge)
  • --subnet — Subnet in CIDR form (e.g., --subnet 192.168.1.0/24)
  • --gateway — IPv4 or IPv6 Gateway for the master subnet
  • --opt — Set driver-specific options (e.g., --opt encrypted=true)

Example:

docker network create --driver overlay --subnet 10.0.9.0/24 my-overlay-net

Connect a Container to a Network

docker network connect [OPTIONS] <network-name> <container-id or name>

Important Flags/Options:

  • --alias — Add network-scoped alias for the container

Example:

docker network connect --alias webapp app-network web-container

Disconnect a Container from a Network

docker network disconnect [OPTIONS] <network-name> <container-id or name>

Important Flags/Options:

  • -f, --force — Force the container to disconnect from the network

Example:

docker network disconnect -f app-network web-container

Inspect a Network

docker network inspect [OPTIONS] <network-name>

Important Flags/Options:

  • --format — Format output using a Go template

Example:

docker network inspect --format '{{json .IPAM.Config}}' my-network

💾 Volumes and Data Management

Create a Volume

docker volume create [OPTIONS] <volume-name>

Important Flags/Options:

  • --driver — Specifies volume driver to use (default: local)
  • --label — Set metadata on volume (e.g., --label project=alpha)

Example:

docker volume create --label purpose=dbdata mydbvolume

List Volumes

docker volume ls [OPTIONS]

Important Flags/Options:

  • -q, --quiet — Only display volume names
  • --filter — Filter output (e.g., "dangling=true")

Example:

docker volume ls --filter "dangling=true"

Remove a Volume

docker volume rm [OPTIONS] <volume-name> [<volume-name>...]

Important Flags/Options:

  • -f, --force — Force removal of one or more volumes

Example:

docker volume rm -f oldvolume1 oldvolume2

Mount a Volume to a Container

# Named volume mount
docker run -v <volume-name>:<container-path> [OPTIONS] <image-name>
# Bind mount host directory
docker run -v $(pwd)/host_dir:<container-path> [OPTIONS] <image-name>

Example:

docker run -d -v mydbvolume:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:14

Inspect Volume

docker volume inspect [OPTIONS] <volume-name>

Important Flags/Options:

  • --format — Format output using a Go template

Example:

docker volume inspect --format '{{.Mountpoint}}' mydbvolume

🛠 Dockerfile and Building Images

Dockerfile Basic Structure

# Base image
FROM <base-image>:<tag>

# Labels and metadata
LABEL maintainer="<your-name>"
LABEL version="1.0"

# Create and set working directory
WORKDIR /app

# Copy application files
COPY . /app

# Install dependencies
RUN <command>  # e.g., `npm install`

# Expose ports
EXPOSE <port>   # e.g., `EXPOSE 3000`

# Run the application
CMD ["<executable>"]  # e.g., `CMD ["npm", "start"]`

Build an Image

docker build [OPTIONS] -t <repository>/<image-name>:<tag> <path-to-Dockerfile-dir>

Important Flags/Options:

  • -f, --file <file> — Name of the Dockerfile (default: ‘./Dockerfile’)
  • --no-cache — Do not use cache when building the image
  • --pull — Always attempt to pull a newer version of the base image
  • --build-arg <var>=<value> — Set build-time variables
  • --platform — Set target platform for build (e.g., --platform linux/amd64)
  • -q, --quiet — Suppress verbose build output, print only image ID

Example:

docker build --no-cache --pull -t myrepo/myapp:latest .

List Built Images

docker images [OPTIONS]

Refer to flags in “List Local Images” section.


📦 Image Management

Tag an Image (Retrospective)

docker tag [OPTIONS] <image-id> <repository>/<image-name>:<tag>

Refer to “Tag an Image” above.

Remove an Image

docker rmi [OPTIONS] <image-name or ID> [...]

Refer to flags in “Remove an Image” above.

Save an Image to Tar

docker save [OPTIONS] -o <file-name>.tar <image-name>:<tag>

Important Flags/Options:

  • -o, --output — Write to a file, instead of STDOUT
  • --quiet — Suppress verbose output

Example:

docker save --quiet -o myapp_v1.tar myrepo/myapp:1.0

Load an Image from Tar

docker load [OPTIONS] -i <file-name>.tar

Important Flags/Options:

  • -i, --input — Read from tar archive file, instead of STDIN
  • --quiet — Suppress verbose output

Example:

docker load --quiet -i myapp_v1.tar

Push Image to Docker Hub

# Log in first
docker login [OPTIONS]
# Push tagged image to registry
docker push [OPTIONS] <repository>/<image-name>:<tag>

Important Flags/Options for login:

  • --username, -u — Username
  • --password-stdin — Take password from STDIN rather than via prompt

Important Flags/Options for push:

  • --disable-content-trust — Skip image signing (default: true)
  • --quiet — Suppress verbose output

Example:

echo "my_secret_password" | docker login --username myuser --password-stdin
docker push myrepo/myapp:1.0

🧪 Docker Compose

Docker Compose Basic Commands

docker-compose [OPTIONS] up [OPTIONS] [SERVICE...]

Important Flags/Options for up:

  • -d, --detach — Run containers in the background
  • --build — Build images before starting containers
  • --no-build — Don’t build an image, even if it’s missing
  • --force-recreate — Recreate containers even if their configuration and image haven’t changed
  • --no-recreate — If containers already exist, don’t recreate them
  • --remove-orphans — Remove containers for services not defined in the Compose file
docker-compose [OPTIONS] down [OPTIONS]

Important Flags/Options for down:

  • -v, --volumes — Remove named volumes declared in the volumes section of the Compose file and anonymous volumes attached to containers
  • --rmi [all\|local] — Remove images. all: Remove all images used by any service. local: Remove only images that don’t have a repository specified
  • --remove-orphans — Remove containers for services not defined in the Compose file
# Scale a specific service to N instances
docker-compose up --scale <service-name>=<count>

View Compose Services

docker-compose ps [OPTIONS]

Important Flags/Options:

  • -q, --quiet — Only display IDs
  • --services — Display services
  • --filter — Filter services by conditions (e.g., "status=running")

Example:

docker-compose ps --services --filter "status=running"

Logs for Compose Services

docker-compose logs [OPTIONS] [SERVICE...]

Important Flags/Options:

  • -f, --follow — Follow log output
  • --tail="all" — Number of lines to show from the end
  • -t, --timestamps — Show timestamps

Example:

docker-compose logs -f --tail=100 web

🧹 Cleanup and Maintenance

Remove All Stopped Containers

docker container prune [OPTIONS]

Important Flags/Options:

  • -f, --force — Do not prompt for confirmation
  • --filter — Provide filter values (e.g., "until=24h")

Example:

docker container prune -f --filter "until=48h"

Remove Unused Images

docker image prune [OPTIONS]

Important Flags/Options:

  • -a, --all — Remove all unused images, not just dangling ones
  • -f, --force — Do not prompt for confirmation
  • --filter — Provide filter values (e.g., "label!=keep")

Example:

docker image prune -a -f --filter "until=72h"

Remove All Unused Data (Containers, Networks, Images, Build Cache)

docker system prune [OPTIONS]

Important Flags/Options:

  • -a, --all — Remove all unused images, not just dangling ones
  • --volumes — Prune volumes as well
  • -f, --force — Do not prompt for confirmation
  • --filter — Provide filter values (e.g., "label!=keep")

Example:

docker system prune -a --volumes -f --filter "until=24h"

Detailed Cleanup (Images, Containers, Volumes, Networks)

docker system prune -a --volumes --force

📊 System and Debugging

Get Docker System Info

docker info [OPTIONS]

Important Flags/Options:

  • --format — Format output using a Go template (e.g., "{{.Driver}}")

Example:

docker info --format '{{json .Plugins}}'

Check Container Stats (Real-Time)

docker stats [OPTIONS] [CONTAINER...]

Important Flags/Options:

  • -a, --all — Show all containers (default shows running only)
  • --format — Format output using a Go template (e.g., "{{.Name}}: {{.CPUPerc}}")

Example:

docker stats --format "table {{.Name}}\t{{.MemUsage}}\t{{.NetIO}}"

Top Processes in a Container

docker top <container-id or name> [ps OPTIONS]

Important Flags/Options:

  • You can pass ps options (e.g., aux) to view processes inside the container

Example:

docker top my-container aux

Inspect Container, Image, or Network (Retrospective)

# Container
docker inspect [OPTIONS] <container-id or name>
# Image
docker inspect [OPTIONS] <image-name or ID>
# Network
docker inspect [OPTIONS] <network-name>

Refer to flags in previous sections.


🧠 Expert Tips

Copy Files From Container

docker cp [OPTIONS] <container-id or name>:<container-path> <host-path>

Important Flags/Options:

  • --archive, -a — Archive mode (copy all UID/GID information)

Example:

docker cp -a my-container:/var/log/app.log ./app.log

Copy Files To Container

docker cp [OPTIONS] <host-path> <container-id or name>:<container-path>

Refer to flags above.

Create Image from Container (Commit Changes)

docker commit [OPTIONS] <container-id or name> <new-image-name>[:<tag>]

Important Flags/Options:

  • -a, --author — Author (e.g., "Jane Doe [email protected]")
  • -m, --message — Commit message

Example:

docker commit -a "Sajib" -m "Added config changes" my-container sabi/app:latest

Connect to Container with Docker Attach (Caution!)

docker attach [OPTIONS] <container-id or name>

Important Flags/Options:

  • --sig-proxy — Proxy all received signals to the process (default: true). Use caution as it can send SIGINT to process inside container.

Example:

docker attach --sig-proxy=false my-long-running-service

Export Container Filesystem

docker export [OPTIONS] <container-id or name>

Important Flags/Options:

  • -o, --output — Write to a file instead of STDOUT

Example:

docker export -o mycontainer_fs.tar my-container

Import Container Filesystem

docker import [OPTIONS] <file-name>.tar <repository>/<image-name>:<tag>

Important Flags/Options:

  • --change, -c — Apply Dockerfile instructions (e.g., -c "LABEL version=1.0")

Example:

docker import -c "LABEL imported=true" mycontainer_fs.tar myrepo/imported-image:1.0

About

This is a cheatsheet-style repository I created while learning and practicing Docker. It includes a comprehensive README of essential Docker commands and a fully dockerized full-stack project with a TypeScript backend, Next.js frontend, and MongoDB—built to strengthen my understanding of containerization.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published