---
title: "Docker"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/docker
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Docker

Docker is a containerization platform for building, shipping, and running applications in isolated environments. This cheatsheet covers the core Docker CLI commands.

6 Categories16 Sections48 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

DockerContainersImagesDevOpsVirtualizationDeployment

[Markdown for AI(opens in a new tab)](/docker/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Containers & Kubernetes](/series/containers--kubernetes)1/7

[NextHelm](/cheatsheets/helm)

All posts in this series (7)

Cheatsheets7

1.  [DockerYou are here](/cheatsheets/docker)
2.  [Helm](/cheatsheets/helm)
3.  [Kubernetes](/cheatsheets/kubernetes)
4.  [Docker Compose](/cheatsheets/docker-compose)
5.  [Dockerfile](/cheatsheets/dockerfile)
6.  [Docker Swarm](/cheatsheets/docker-swarm)
7.  [kubectl](/cheatsheets/kubectl)

Docker is a containerization platform that packages applications with their dependencies into isolated, portable environments called containers. It enables developers to build, ship, and run applications consistently across different systems.

## [Benefits](#benefits)

-   Run the same environment in development, test, and production.
-   Applications are isolated from each other and from the host system.
-   A containerized application deploys to any system running Docker.
-   Containers are lighter than virtual machines and start faster.
-   Scale horizontally by running more containers.

## [Quick start](#quick-start)

**Install Docker**: Follow the installation guide in the Getting Started section.

**Run your first container**: `docker run -d -p 8080:80 nginx:latest`

**Access the service**: Open [http://localhost:8080](http://localhost:8080) in your browser.

## [Common workflows](#common-workflows)

1.  **Development**: Use containers to match production environment locally
2.  **Building Images**: Create Dockerfiles and build images for your applications
3.  **Running Services**: Run containers with proper networking and storage configuration
4.  **Scaling**: Use container orchestration (Docker Swarm or Kubernetes) for production deployments

The sections above cover Docker commands, networking, storage, and best practices for containerized applications.

[Getting Started](#category-getting-started)

-   [What is Docker](#section-what-is-docker)
-   [Installation Setup](#section-installation)
-   [Hello World](#section-hello-world)

[Build & Images](#category-build-images)

-   [Docker Build](#section-docker-build)
-   [Managing Images](#section-docker-images)
-   [Remove Images](#section-docker-rmi)

[Run & Containers](#category-run-containers)

-   [Docker Run](#section-docker-run)
-   [Docker Create](#section-docker-create)
-   [Docker Exec](#section-docker-exec)

[Container Management](#category-container-management)

-   [Start & Stop Containers](#section-docker-start-stop)
-   [List Containers](#section-docker-ps)
-   [Docker Logs](#section-docker-logs)

[Networking & Volumes](#category-networking-volumes)

-   [Port Mapping & Networking](#section-ports-networking)
-   [Docker Volumes](#section-docker-volumes)

[Cleanup & System](#category-cleanup-system)

-   [Container & Image Cleanup](#section-cleanup-containers)
-   [System Management](#section-system-management)

No commands found

Try adjusting your search term

## Getting Started

Fundamental Docker concepts and basic setup for beginners.

### What is Docker

Introduction to Docker and containerization concepts.

#### Accessibility

Ensure conceptual explanations are clear and accessible.

#### Best Practices

-   Always use specific image versions/tags instead of 'latest'.
-   Understand the difference between images and containers before proceeding.

#### Common Errors

-   **Docker daemon not running:** Start Docker daemon with \`systemctl start docker\` or Docker Desktop.

#### Keywords

containerizationimagescontainersisolationdocker-daemon

[Learn more](https://docs.docker.com/engine/docker-overview/)

#### Docker overview

Docker is a lightweight virtualization platform that uses containerization to isolate applications and their dependencies.

Code

Terminal window

```
# Docker is a containerization platform that packages applications# with their dependencies into isolated, portable containers.
# Key concepts:# - Image: Blueprint/template for creating containers# - Container: Running instance of an image# - Registry: Repository for storing images (Docker Hub)# - Daemon: Background service running Docker
```

Execution

Terminal window

```
docker --version
```

Output

Terminal window

```
Docker version 24.0.0, build abcd1234
```

-   Containers are more lightweight than virtual machines.
-   Docker uses images as templates to create containers.
-   All containers run on the same kernel but are isolated from each other.

#### Docker client-server architecture

Explains the client-server architecture of Docker and how commands flow through the system.

Code

Terminal window

```
# Docker uses a client-server architecture:# 1. Client: CLI that sends commands to the daemon# 2. Server: Daemon that manages containers and images# 3. Registries: Stores images (public or private)
# Communication flow:# Docker CLI → Docker Daemon → Container Runtime → Containers
```

Execution

Terminal window

```
docker info
```

Output

Terminal window

```
Client: Version: 24.0.0Server: Containers: 3 Running: 1 Images: 15
```

-   The Docker daemon must be running for CLI commands to work.
-   Multiple clients can connect to one daemon.

#### Container vs image

Demonstrates the relationship between images and containers with concrete examples.

Code

Terminal window

```
# Image: Read-only template containing application code and dependencies# - Similar to a class in object-oriented programming# - Built from Dockerfile instructions# - Immutable and portable
# Container: Running instance of an image# - Similar to an object in object-oriented programming# - Has writable layer on top of image# - Each container is isolated with own filesystem, network, processes
```

Execution

Terminal window

```
docker images && docker ps
```

Output

Terminal window

```
REPOSITORY   TAG      IMAGE IDubuntu       20.04    1234567
CONTAINER ID  IMAGE   STATUSabcd1234      ubuntu  Up 2 hours
```

-   One image can create multiple containers.
-   Containers are ephemeral and data is lost when stopped (unless using volumes).

### Installation Setup

Installing Docker and verifying the installation.

#### Accessibility

Provide clear step-by-step instructions.

#### Best Practices

-   Enable WSL 2 on Windows for better performance.
-   Run hello-world to verify successful installation.

#### Common Errors

-   **Permission denied while trying to connect to Docker daemon:** Add user to docker group or use sudo with Docker commands.

#### Keywords

installsetupdocker-desktopverify

[Learn more](https://docs.docker.com/install/)

#### Install Docker on Linux

Installation steps for Docker on Ubuntu/Debian-based Linux systems.

Code

Terminal window

```
# Update package managersudo apt-get update
# Install Docker packagesudo apt-get install -y docker.io
# Start Docker daemonsudo systemctl start docker
# Enable Docker to start on bootsudo systemctl enable docker
```

Execution

Terminal window

```
sudo docker --version
```

Output

Terminal window

```
Docker version 24.0.0, build abcd1234
```

-   Requires Ubuntu 16.04 LTS or newer.
-   Using \`sudo\` is necessary for Docker commands unless configured otherwise.

#### Post-installation setup

Post-installation configuration to run Docker without sudo and verify the setup.

Code

Terminal window

```
# Run Docker without sudo (optional)sudo usermod -aG docker $USER
# Apply group membershipnewgrp docker
# Verify installationdocker run hello-world
```

Execution

Terminal window

```
docker run hello-world
```

Output

Terminal window

```
Unable to find image 'hello-world:latest' locallylatest: Pulling from library/hello-worldStatus: Downloaded newer image for hello-world:latestHello from Docker!
```

-   Adding user to docker group allows running without sudo.
-   Must logout and login again for group changes to take effect.

#### Docker Desktop installation (macOS/Windows)

Installation instructions for Docker Desktop on macOS and Windows systems.

Code

Terminal window

```
# macOS: Install using Homebrewbrew install --cask docker
# Or download from: https://www.docker.com/products/docker-desktop
# Windows: Download Docker Desktop installer from official site# Then run installer and enable WSL 2 integration
# After installation, verifydocker --version
```

Execution

Terminal window

```
docker --version && docker run hello-world
```

Output

Terminal window

```
Docker version 24.0.0, build abcd1234Hello from Docker!
```

-   Docker Desktop includes Docker engine, CLI, and Docker Compose.
-   On Windows, Docker Desktop performs best with WSL 2 (Windows Subsystem for Linux 2).

### Hello World

Running your first Docker container.

#### Accessibility

Make first container experience straightforward.

#### Best Practices

-   Always use specific image versions instead of just 'latest'.
-   Use meaningful container names for easy identification.

#### Common Errors

-   **Image not found locally:** Docker pulls the image from Docker Hub automatically. Check your internet connection.

#### Keywords

hello-worldrunfirst-containerbasic-usage

[Learn more](https://docs.docker.com/get-started/)

#### Run hello-world image

Demonstrates the basic workflow of pulling an image and running a container.

Code

Terminal window

```
docker run hello-world
```

Execution

Terminal window

```
docker run hello-world
```

Output

Terminal window

```
Unable to find image 'hello-world:latest' locallylatest: Pulling from library/hello-world2db29710123e: Pull completeStatus: Downloaded newer image for hello-world:latest
Hello from Docker!This message shows that your installation appears to be working correctly.
```

-   Docker downloads the image from Docker Hub if it's not already present.
-   The container runs and exits automatically for hello-world.

#### Run interactive shell container

Runs an interactive shell in an Ubuntu container, allowing you to explore the container filesystem.

Code

Terminal window

```
docker run -it ubuntu:22.04 /bin/bash
```

Execution

Terminal window

```
docker run -it ubuntu:22.04 /bin/bash
```

Input

Terminal window

```
ls -laexit
```

Output

Terminal window

```
total 32drwxr-xr-x   1 root root 4096 Jan 10 12:00 .drwxr-xr-x   1 root root 4096 Jan 10 12:00 ..-rwxr-xr-x   1 root root    0 Jan 10 12:00 .dockerenv...
```

-   \`-it\` flags enable interactive terminal access.
-   Type \`exit\` to leave the container.

#### Run container with custom command

Runs a specific command in the container and then exits.

Code

Terminal window

```
docker run --name my-python-app python:3.11 python --version
```

Execution

Terminal window

```
docker run --name my-python-app python:3.11 python --version
```

Output

Terminal window

```
Python 3.11.5
```

-   \`--name\` assigns a friendly name to the container.
-   Container exits after command completes.

## Build & Images

Creating, managing, and working with Docker images.

### Docker Build

Creating Docker images from Dockerfiles.

#### Accessibility

Include clear examples of Dockerfile syntax.

#### Best Practices

-   Use specific base image versions.
-   Minimize layers by combining RUN commands.
-   Use multi-stage builds for smaller production images.

#### Common Errors

-   **COPY/ADD path outside build context:** Keep the files you copy inside the build context directory.

#### Keywords

builddockerfileimage-creationlayerstags

[Learn more](https://docs.docker.com/engine/reference/commandline/build/)

#### Basic Docker build

Demonstrates basic Docker image building with tag naming.

Code

Terminal window

```
# Create a Dockerfilecat > Dockerfile << 'EOF'FROM ubuntu:22.04RUN apt-get update && apt-get install -y curlCOPY . /appWORKDIR /appCMD ["echo", "Hello from Docker!"]EOF
# Build the imagedocker build -t my-app:1.0 .
```

Execution

Terminal window

```
docker build -t my-app:1.0 .
```

Output

Terminal window

```
Sending build context to Docker daemon  2.048kBStep 1/5 : FROM ubuntu:22.04Step 2/5 : RUN apt-get update && apt-get install -y curlStep 3/5 : COPY . /appStep 4/5 : WORKDIR /appStep 5/5 : CMD ["echo", "Hello from Docker!"]Successfully built abc123def456Successfully tagged my-app:1.0
```

-   Build context includes all files in current directory.
-   Tag format is \`repository:tag\` or \`registry/repository:tag\`.
-   Each RUN instruction creates a layer.

#### Build with build arguments

Demonstrates build-time arguments for customizing image builds.

Code

Terminal window

```
# Dockerfile with build argumentscat > Dockerfile << 'EOF'FROM python:3.11ARG APP_VERSION=1.0ARG APP_ENV=productionRUN echo "Building version $APP_VERSION for $APP_ENV"COPY . /appWORKDIR /appRUN pip install -r requirements.txtCMD ["python", "app.py"]EOF
# Build with custom argumentsdocker build \  --build-arg APP_VERSION=2.5 \  --build-arg APP_ENV=staging \  -t my-python-app:2.5 .
```

Execution

Terminal window

```
docker build --build-arg APP_VERSION=2.5 -t my-python-app:2.5 .
```

Output

Terminal window

```
Sending build context to Docker daemonStep 1/7 : FROM python:3.11Step 2/7 : ARG APP_VERSION=1.0Step 3/7 : ARG APP_ENV=productionStep 4/7 : RUN echo "Building version 2.5 for staging"Building version 2.5 for stagingSuccessfully tagged my-python-app:2.5
```

-   ARG values can be overridden during build time.
-   Build arguments are only available during build, not in running containers.

#### Multi-stage Docker build

Multi-stage builds reduce final image size by using temporary build stages.

Code

Terminal window

```
cat > Dockerfile << 'EOF'# Build stageFROM golang:1.21 as builderWORKDIR /appCOPY . .RUN go build -o myapp
# Runtime stageFROM alpine:latestWORKDIR /root/COPY --from=builder /app/myapp .CMD ["./myapp"]EOF
docker build -t go-optimized:latest .
```

Execution

Terminal window

```
docker build -t go-optimized:latest .
```

Output

Terminal window

```
Step 1/8 : FROM golang:1.21 as builderStep 2/8 : WORKDIR /appStep 3/8 : COPY . .Step 4/8 : RUN go build -o myappStep 5/8 : FROM alpine:latestStep 6/8 : WORKDIR /root/Step 7/8 : COPY --from=builder /app/myapp .Step 8/8 : CMD ["./myapp"]Successfully tagged go-optimized:latest
```

-   Only final stage is included in the image.
-   Cuts image size for compiled applications, since build tools stay out of the final stage.

### Managing Images

Listing, inspecting, and managing Docker images.

#### Accessibility

Provide clear output examples for image listing.

#### Best Practices

-   Use docker images -q to get only image IDs for scripting.
-   Tag images meaningfully with version numbers.

#### Common Errors

-   **Image with tag not found:** Check the spelling and confirm the image exists locally or on the registry.

#### Keywords

imageslistinspecttagshistory

[Learn more](https://docs.docker.com/engine/reference/commandline/images/)

#### List all images

Displays all Docker images and their metadata.

Code

Terminal window

```
# List all local imagesdocker images
# List with all details including dangling imagesdocker images -a
```

Execution

Terminal window

```
docker images
```

Output

Terminal window

```
REPOSITORY          TAG      IMAGE ID       CREATED       SIZEubuntu              22.04    6b038c8a0437   2 weeks ago   77.9MBpython              3.11     abc123def456   2 weeks ago   920MBnginx               latest   def456abc123   1 week ago    187MBmy-app              1.0      xyz789abc123   3 days ago    250MB
```

-   IMAGE ID is the unique identifier for the image.
-   SIZE is the uncompressed size of the image.

#### Inspect image details

Shows detailed JSON metadata about a specific image.

Code

Terminal window

```
# Get detailed information about an imagedocker inspect ubuntu:22.04
# Get specific information using jqdocker inspect ubuntu:22.04 | jq '.[0].Config.Env'
```

Execution

Terminal window

```
docker inspect ubuntu:22.04
```

Output

Terminal window

```
[  {    "Id": "sha256:6b038c8a043...",    "RepoTags": ["ubuntu:22.04"],    "Size": 77880000,    "Architecture": "amd64",    "Config": {      "Hostname": "",      "Env": ["PATH=/usr/local/sbin:/usr/local/bin:..."]    }  }]
```

-   Output is in JSON format.
-   Includes environment variables, exposed ports, and more.

#### View image history

Displays the build history showing each layer and command.

Code

Terminal window

```
# Show image build history (layers)docker history my-app:1.0
# Show human-readable formatdocker history --human my-app:1.0
```

Execution

Terminal window

```
docker history my-app:1.0
```

Output

Terminal window

```
IMAGE          CREATED       CREATED BY                      SIZEabc123def456   3 hours ago   /bin/sh -c #(nop)  CMD ["pytho   0Bdef456abc123   3 hours ago   /bin/sh -c pip install -r req   45MBghi789def012   3 hours ago   /bin/sh -c #(nop) COPY dir:...  2.5MBpython:3.11    2 weeks ago   /bin/sh -c #(nop)  CMD ["pyth   0B
```

-   Each row represents a layer in the image.
-   Helps understand what commands created each layer.

### Remove Images

Deleting Docker images and managing disk space.

#### Accessibility

Include warning notes about irreversible operations.

#### Best Practices

-   Remove unused images regularly to save disk space.
-   Always stop and remove containers before removing images.

#### Common Errors

-   **Image is in use by running container:** Stop and remove the container first using \`docker stop\` and \`docker rm\`.

#### Keywords

removermideletecleanupdangling

[Learn more](https://docs.docker.com/engine/reference/commandline/rmi/)

#### Remove single image by ID

Removes a Docker image by its ID.

Code

Terminal window

```
# Remove image by IDdocker rmi abc123def456
# Force remove even if in usedocker rmi -f abc123def456
```

Execution

Terminal window

```
docker rmi abc123def456
```

Output

Terminal window

```
Untagged: my-app:1.0Deleted: sha256:abc123def456...Deleted: sha256:def456abc123...
```

-   Cannot remove image if running containers use it.
-   Use \`-f\` flag to force remove, but may orphan containers.

#### Remove image by repository name

Removes Docker images by repository and tag name.

Code

Terminal window

```
# Remove specific image tagdocker rmi ubuntu:22.04
# Remove all tags of repositorydocker rmi ubuntu
```

Execution

Terminal window

```
docker rmi python:3.11
```

Output

Terminal window

```
Untagged: python:3.11Deleted: sha256:abc123def456...Deleted: sha256:def456abc123...
```

-   Remove containers first before removing images they use.

#### Remove dangling images

Cleans up unused and dangling images to free disk space.

Code

Terminal window

```
# Find dangling images (untagged, unused layers)docker images -f dangling=true
# Remove all dangling imagesdocker image prune -a
# Remove with confirmationdocker image prune -a --force
```

Execution

Terminal window

```
docker image prune -a
```

Output

Terminal window

```
WARNING! This will remove all images without at least one container associated to them.Are you sure you want to continue? [y/N] yDeleted Images:untagged: old-app:1.0@sha256:...total reclaimed space: 245.3MB
```

-   Dangling images have no repository or tag reference.
-   This operation is irreversible.

## Run & Containers

Creating and running Docker containers with various options.

### Docker Run

Creating and starting containers with the run command.

#### Accessibility

Provide comprehensive examples of common run options.

#### Best Practices

-   Always use specific image versions, not 'latest'.
-   Mount volumes for persistent data.
-   Set resource limits to prevent system overload.

#### Common Errors

-   **Port is already allocated:** Use a different host port or stop the container using that port.

#### Keywords

runcontainer-creationoptionsportsvolumesenvironment

[Learn more](https://docs.docker.com/engine/reference/commandline/run/)

#### Basic container run

Demonstrates basic run options for different scenarios.

Code

Terminal window

```
# Run container and keep it runningdocker run -d --name my-web nginx:latest
# Run with interactive terminaldocker run -it ubuntu:22.04 /bin/bash
# Run and remove after exitdocker run --rm python:3.11 python --version
```

Execution

Terminal window

```
docker run -d --name my-web nginx:latest
```

Output

Terminal window

```
1a2b3c4d5e6f7g8h9i0j (container ID)
```

-   \`-d\` runs container in detached (background) mode.
-   \`-it\` allows interactive terminal access.
-   \`--rm\` automatically removes container when it exits.

#### Run with port mapping and volumes

Maps container ports to host and mounts volumes.

Code

Terminal window

```
# Map container port to host portdocker run -d -p 8080:80 --name my-web \  -v /var/www/html:/usr/share/nginx/html \  nginx:latest
# Multiple port mappingsdocker run -d -p 80:80 -p 443:443 \  --name my-secure-web nginx:latest
```

Execution

Terminal window

```
docker run -d -p 8080:80 --name my-web nginx:latest
```

Output

Terminal window

```
abc123def456ghi789jkl
```

-   Format is \`-p host\_port:container\_port\`.
-   \`-v\` mounts host directory into container.
-   Must use absolute paths for volume mounting.

#### Run with environment variables and resource limits

Demonstrates environment variables and resource constraints.

Code

Terminal window

```
# Set environment variablesdocker run -d --name my-app \  -e DATABASE_URL=postgres://db:5432 \  -e APP_ENV=production \  -e LOG_LEVEL=info \  my-app:1.0
# Set resource limitsdocker run -d --name my-limited-app \  -m 512m \  --cpus="0.5" \  my-app:1.0
```

Execution

Terminal window

```
docker run -d -e APP_ENV=production my-app:1.0
```

Output

Terminal window

```
xyz123abc456def789ghi
```

-   \`-e\` sets environment variables in the container.
-   \`-m\` limits memory in MB or GB.
-   \`--cpus\` limits CPU resources.

### Docker Create

Creating containers without starting them immediately.

#### Accessibility

Explain difference between create and run.

#### Best Practices

-   Use create when you need to configure before starting.
-   Add health checks for critical services.

#### Common Errors

-   **Container name already exists:** Use unique name or remove existing container with \`docker rm\`.

#### Keywords

createcontainer-creationprepareconfiguration

[Learn more](https://docs.docker.com/engine/reference/commandline/create/)

#### Create container configuration

Separates container creation from startup for more control.

Code

Terminal window

```
# Create container without startingdocker create --name my-db \  -e MYSQL_ROOT_PASSWORD=secret \  -p 3306:3306 \  -v db-data:/var/lib/mysql \  mysql:8.0
# Verify it's created but not runningdocker ps -a
```

Execution

Terminal window

```
docker create --name my-db mysql:8.0
```

Output

Terminal window

```
abc123def456ghi789jkl (container ID)
```

-   Container is created but in stopped state.
-   Useful for configuring containers before starting.

#### Create with advanced networking

Creates containers on specific networks for container-to-container communication.

Code

Terminal window

```
# Create networkdocker network create my-network
# Create container on specific networkdocker create --name web-server \  --network my-network \  --network-alias web \  -p 80:80 \  nginx:latest
# Create another container on same networkdocker create --name app-server \  --network my-network \  my-app:1.0
```

Execution

Terminal window

```
docker create --network my-network --name web-server nginx:latest
```

Output

Terminal window

```
def456ghi789jkl123abc
```

-   Containers on same network can communicate using container name.
-   Network aliases provide DNS resolution within the network.

#### Create with health check

Creates container with health check for monitoring availability.

Code

Terminal window

```
# Create with health checkdocker create --name healthy-app \  --health-cmd="curl -f http://localhost:8080/health || exit 1" \  --health-interval=30s \  --health-timeout=10s \  --health-retries=3 \  my-app:1.0
```

Execution

Terminal window

```
docker create --health-cmd="curl localhost:8080" my-app:1.0
```

Output

Terminal window

```
ghi789jkl123abc456def
```

-   Health check runs at specified intervals.
-   Docker marks container as unhealthy after retries fail.

### Docker Exec

Running commands inside running containers.

#### Accessibility

Include realistic debugging examples.

#### Best Practices

-   Use exec for quick one-off commands and debugging.
-   Always verify container is running before exec.

#### Common Errors

-   **Container is not running:** Start container with \`docker start container-name\` first.

#### Keywords

execrunning-commandinteractivedebugginginspection

[Learn more](https://docs.docker.com/engine/reference/commandline/exec/)

#### Execute command in running container

Executes a command inside a running container without entering shell.

Code

Terminal window

```
# Execute single commanddocker exec my-web ls -la /var/www/html
# Execute with outputdocker exec my-db mysql -u root -p$MYSQL_ROOT_PASSWORD -e "SHOW DATABASES;"
```

Execution

Terminal window

```
docker exec my-web ls -la /var/www/html
```

Output

Terminal window

```
total 24drwxr-xr-x   1 root root 4096 Jan 10 12:00 .drwxr-xr-x   1 root root 4096 Jan 10 12:00 ..-rw-r--r--   1 root root 1234 Jan 10 12:00 index.html
```

-   Container must be in running state.
-   Useful for quick debugging and inspection.

#### Interactive shell access

Provides interactive shell access for debugging and exploration.

Code

Terminal window

```
# Enter interactive shelldocker exec -it my-app /bin/bash
# Once inside, run commands# $ ps aux# $ cat /var/log/app.log# $ exit
```

Execution

Terminal window

```
docker exec -it my-app /bin/bash
```

Input

Terminal window

```
idpwd
```

Output

Terminal window

```
uid=0(root) gid=0(root) groups=0(root)/app
```

-   \`-it\` enables interactive terminal mode.
-   Type \`exit\` to leave the shell.

#### Execute with user and working directory

Demonstrates user, directory, and background execution options.

Code

Terminal window

```
# Execute as specific userdocker exec -u appuser my-app whoami
# Execute in specific directorydocker exec -w /var/log my-app tail -f app.log
# Execute in backgrounddocker exec -d my-app python script.py
```

Execution

Terminal window

```
docker exec -u appuser my-app whoami
```

Output

Terminal window

```
appuser
```

-   \`-u\` specifies user for command execution.
-   \`-w\` sets working directory for command.
-   \`-d\` runs command in background.

## Container Management

Managing container lifecycle, status, and logs.

### Start & Stop Containers

Starting, stopping, and restarting containers.

#### Accessibility

Include practical restart scenarios.

#### Best Practices

-   Use \`stop\` for graceful shutdown of services.
-   Use \`kill\` only when necessary.

#### Common Errors

-   **Container no response to stop signal:** Use \`docker kill\` to force termination.

#### Keywords

startstoprestartpauseunpause

[Learn more](https://docs.docker.com/engine/reference/commandline/stop/)

#### Start and stop containers

Basic container lifecycle operations.

Code

Terminal window

```
# Stop a running container gracefullydocker stop my-web
# Start a stopped containerdocker start my-web
# Restart a container (stop then start)docker restart my-web
```

Execution

Terminal window

```
docker stop my-web && docker start my-web
```

Output

Terminal window

```
my-webmy-web
```

-   \`stop\` sends SIGTERM and gives the container 10 seconds to shut down.
-   \`start\` restarts stopped container with same configuration.

#### Stop with timeout and force kill

Advanced stop options including timeout and force kill.

Code

Terminal window

```
# Stop with custom timeout before killingdocker stop -t 30 my-web
# Force kill container immediatelydocker kill my-web
# Kill all running containersdocker kill $(docker ps -q)
```

Execution

Terminal window

```
docker stop -t 30 my-web
```

Output

Terminal window

```
my-web
```

-   \`-t\` specifies seconds to wait before killing (default 10).
-   \`kill\` sends SIGKILL immediately, no graceful shutdown.

#### Pause and unpause containers

Temporarily pause container processes without stopping container.

Code

Terminal window

```
# Pause all processes in containerdocker pause my-app
# Resume paused containerdocker unpause my-app
# Check pause statusdocker inspect -f '{{.State.Paused}}' my-app
```

Execution

Terminal window

```
docker pause my-app && docker unpause my-app
```

Output

Terminal window

```
my-appmy-app
```

-   Paused containers still consume memory.
-   Useful for resource management without full stop.

### List Containers

Listing and filtering containers.

#### Accessibility

Provide clear filter examples.

#### Best Practices

-   Use \`docker ps -q\` in scripts to get only IDs.
-   Filter containers for easier management in large deployments.

#### Common Errors

-   **Container not found:** Run \`docker ps -a\` to check if container exists.

#### Keywords

pslistfilterstatusformat

[Learn more](https://docs.docker.com/engine/reference/commandline/ps/)

#### List running containers

Lists Docker containers with various output options.

Code

Terminal window

```
# List running containersdocker ps
# List all containers (running and stopped)docker ps -a
# List only container IDsdocker ps -q
```

Execution

Terminal window

```
docker ps
```

Output

Terminal window

```
CONTAINER ID   IMAGE       COMMAND   CREATED      STATUS      PORTSabc123def456   nginx:latest "nginx..." 2 hours ago  Up 2 hours  0.0.0.0:8080->80/tcpdef456ghi789   mysql:8.0   "docker..." 1 hour ago   Up 1 hour   3306/tcp
```

-   Default \`ps\` shows only running containers.
-   \`-a\` includes stopped containers.
-   \`-q\` shows only IDs for scripting.

#### Filter containers by status and labels

Advanced filtering options for container queries.

Code

Terminal window

```
# Filter by statusdocker ps -a -f status=exiteddocker ps -a -f status=running
# Filter by labeldocker ps -f label=environment=production
# Filter by imagedocker ps -f ancestor=nginx:latest
```

Execution

Terminal window

```
docker ps -a -f status=exited
```

Output

Terminal window

```
CONTAINER ID   IMAGE        STATUSxyz123abc456   ubuntu:20.04 Exited (0)ghi789jkl012   python:3.11  Exited (1)
```

-   Multiple filters can be combined with \`-f\`.
-   Labels must be set when creating containers.

#### Custom output formatting

Custom formatting options for better readability.

Code

Terminal window

```
# Show custom columnsdocker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# JSON formatdocker ps --format json
# Simple list of namesdocker ps --no-trunc --format "{{.Names}}"
```

Execution

Terminal window

```
docker ps --format "table {{.Names}}\t{{.Status}}"
```

Output

Terminal window

```
NAMES           STATUSmy-web          Up 2 hoursmy-db           Up 1 hour
```

-   \`--format\` accepts template variables.
-   Useful for scripting and automation.

### Docker Logs

Viewing and monitoring container logs.

#### Accessibility

Include real-time monitoring examples.

#### Best Practices

-   Use \`-f\` for real-time monitoring.
-   Redirect logs to files for analysis.
-   Set appropriate logging drivers for production.

#### Common Errors

-   **No logs for container:** Container may have exited; check with \`docker ps -a\`.

#### Keywords

logsoutputmonitoringtroubleshootingtail

[Learn more](https://docs.docker.com/engine/reference/commandline/logs/)

#### View container logs

Displays container output and logs.

Code

Terminal window

```
# View all logsdocker logs my-web
# View last 50 linesdocker logs --tail 50 my-web
# View logs with timestampsdocker logs -t my-web
```

Execution

Terminal window

```
docker logs my-web
```

Output

Terminal window

```
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to start nginx/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/2025-01-10T12:00:00.123Z [notice] starting server...2025-01-10T12:00:00.456Z [notice] listen() to 0.0.0.0:80
```

-   Logs are from container's stdout and stderr.
-   Can view logs even after container stops.

#### Follow logs in real-time

Real-time log streaming for monitoring container activity.

Code

Terminal window

```
# Stream logs in real-time (like tail -f)docker logs -f my-web
# Stream with timestampsdocker logs -f -t my-web
# Stream last 10 lines with followdocker logs --tail 10 -f my-web# Press Ctrl+C to exit
```

Execution

Terminal window

```
docker logs -f my-web
```

Output

Terminal window

```
2025-01-10T12:00:05.123Z GET / HTTP/1.1 2002025-01-10T12:00:06.456Z GET /api/users HTTP/1.1 2002025-01-10T12:00:07.789Z GET /style.css HTTP/1.1 304(continue streaming...)
```

-   \`-f\` follows log output continuously.
-   Press Ctrl+C to stop streaming.

#### Filter and search logs

Filters and searches logs for specific patterns.

Code

Terminal window

```
# Show logs since specific timedocker logs --since 2025-01-10T12:00:00 my-web
# Show logs from last hourdocker logs --since 1h my-web
# Search for specific patternsdocker logs my-web | grep ERRORdocker logs my-web | grep -i exception
```

Execution

Terminal window

```
docker logs my-web | grep ERROR
```

Output

Terminal window

```
2025-01-10T12:00:15.123Z [ERROR] Connection timeout2025-01-10T12:00:30.456Z [ERROR] Database unavailable
```

-   \`--since\` accepts timestamps or duration.
-   Pipe the output to grep for more specific searches.

## Networking & Volumes

Container networking, port mapping, and persistent storage.

### Port Mapping & Networking

Managing ports, networks, and container communication.

#### Accessibility

Include diagrams of networking concepts.

#### Best Practices

-   Use custom networks instead of --link.
-   Keep services on same network only if needed.

#### Common Errors

-   **Port already in use:** Use different host port or stop container using it.

#### Keywords

portsnetworkinglinkingdnsexpose

[Learn more](https://docs.docker.com/engine/reference/commandline/network/)

#### Port mapping

Maps container ports to host for external access.

Code

Terminal window

```
# Map single portdocker run -d -p 8080:80 --name my-web nginx:latest
# Map multiple portsdocker run -d -p 80:80 -p 443:443 -p 3000:3000 my-app:1.0
# Map to specific host interfacedocker run -d -p 127.0.0.1:8080:80 my-web
# Dynamic port mapping (OS assigns port)docker run -d -P nginx:latest
```

Execution

Terminal window

```
docker run -d -p 8080:80 nginx:latest
```

Output

Terminal window

```
abc123def456ghi789jkl
```

-   Format: \`-p host\_port:container\_port\`.
-   \`-P\` auto-assigns high ports above 32768.
-   Access locally: \`http://localhost:8080\`.

#### Docker networks and container linking

Creates custom networks for container-to-container communication.

Code

Terminal window

```
# Create custom bridge networkdocker network create my-app-network
# Run containers on networkdocker run -d --name web \  --network my-app-network \  -p 8080:80 \  nginx:latest
docker run -d --name db \  --network my-app-network \  -e MYSQL_ROOT_PASSWORD=secret \  mysql:8.0
# Containers can communicate using namesdocker exec web curl http://db:3306
```

Execution

Terminal window

```
docker network create my-app-network
```

Output

Terminal window

```
abc123def456ghi789jklmnopq
```

-   Containers on same network can communicate using names.
-   Better than deprecated \`--link\` option.

#### Inspect and manage networks

Manages and inspects Docker networks.

Code

Terminal window

```
# List networksdocker network ls
# Inspect network detailsdocker network inspect my-app-network
# Connect container to networkdocker network connect my-app-network container-name
# Disconnect from networkdocker network disconnect my-app-network container-name
```

Execution

Terminal window

```
docker network ls
```

Output

Terminal window

```
NETWORK ID     NAME             DRIVER    SCOPEabc123def456   bridge           bridge    localdef456ghi789   host             host      localghi789jkl012   none             null      localjkl012mno345   my-app-network   bridge    local
```

-   bridge: Default, isolated network.
-   host: Uses host network.
-   none: No networking.

### Docker Volumes

Volume management for persistent data storage.

#### Accessibility

Include examples of data persistence scenarios.

#### Best Practices

-   Use named volumes for managed data storage.
-   Use bind mounts for development environments.
-   Always backup important volumes.

#### Common Errors

-   **Volume already exists:** Use existing volume or remove with \`docker volume rm\`.

#### Keywords

volumesstoragepersistentdatamount

[Learn more](https://docs.docker.com/storage/volumes/)

#### Create and manage volumes

Creates and manages named volumes for persistent storage.

Code

Terminal window

```
# Create named volumedocker volume create db-data
# List volumesdocker volume ls
# Inspect volumedocker volume inspect db-data
# Remove volumedocker volume rm db-data
```

Execution

Terminal window

```
docker volume create db-data
```

Output

Terminal window

```
db-data
```

-   Named volumes are stored on host at \`/var/lib/docker/volumes/\`.
-   Volumes persist even when containers are removed.

#### Mount volumes in containers

Mounts volumes and bind mounts in containers.

Code

Terminal window

```
# Mount named volumedocker run -d -v db-data:/var/lib/mysql \  --name my-db mysql:8.0
# Bind mount from host directorydocker run -d -v /data/app:/app \  --name my-app my-app:1.0
# Read-only mountdocker run -d -v db-data:/data:ro \  --name web-app my-web:1.0
```

Execution

Terminal window

```
docker run -d -v db-data:/var/lib/mysql mysql:8.0
```

Output

Terminal window

```
xyz123abc456def789ghi
```

-   Format: \`-v volume\_name:/container\_path\`.
-   Use absolute paths for bind mounts.
-   Add \`:ro\` for read-only mount.

#### Share data between containers

Uses volumes to share data between multiple containers.

Code

Terminal window

```
# Create shared volumedocker volume create shared-data
# Container 1 writes to volumedocker run -d -v shared-data:/data \  --name writer my-writer:1.0
# Container 2 reads from same volumedocker run -d -v shared-data:/shared \  --name reader my-reader:1.0
# Verify data is shareddocker exec writer sh -c "echo 'shared data' > /data/file.txt"docker exec reader cat /shared/file.txt
```

Execution

Terminal window

```
docker volume create shared-data
```

Output

Terminal window

```
shared-data
```

-   Multiple containers can mount same volume.
-   Useful for shared configuration and data.

## Cleanup & System

Removing containers, cleaning unused resources, and system management.

### Container & Image Cleanup

Removing containers and managing disk space.

#### Accessibility

Include warnings about irreversible operations.

#### Best Practices

-   Regularly clean up unused resources.
-   Use \`docker system df\` to check usage before cleanup.
-   Create cleanup scripts for automation.

#### Common Errors

-   **Container has dependent child images:** Remove containers first, then images.

#### Keywords

cleanupremoveprunedanglingdisk-space

[Learn more](https://docs.docker.com/config/pruning/)

#### Remove containers

Removes Docker containers to free resources.

Code

Terminal window

```
# Remove stopped containerdocker rm container-name
# Remove running container (force)docker rm -f container-name
# Remove multiple containersdocker rm container1 container2 container3
# Remove all stopped containersdocker container prune
```

Execution

Terminal window

```
docker rm stopped-container
```

Output

Terminal window

```
stopped-container
```

-   Use \`-f\` to force remove running containers.
-   Cannot remove without -f if container is running.

#### Prune system resources

Full cleanup of unused Docker resources.

Code

Terminal window

```
# Remove dangling images, containers, volumes, networksdocker system prune
# Also remove unused images (not just dangling)docker system prune -a
# Include volumes in cleanupdocker system prune -a --volumes
```

Execution

Terminal window

```
docker system prune -a
```

Output

Terminal window

```
WARNING! This will remove:  - all stopped containers  - all networks not used by at least one container  - all dangling images  - all build cache
Total reclaimed space: 2.5GB
```

-   \`prune\` is irreversible; review what will be removed.
-   Use \`-a\` to remove all unused images.

#### Cleanup specific resources

Targeted cleanup of specific resource types.

Code

Terminal window

```
# Remove dangling images onlydocker image prune
# Remove unused volumesdocker volume prune
# Stop all containers and remove themdocker stop $(docker ps -q)docker rm $(docker ps -a -q)
# Remove images matching patterndocker rmi $(docker images | grep 'old-app' | awk '{print $3}')
```

Execution

Terminal window

```
docker image prune
```

Output

Terminal window

```
WARNING! This will remove all dangling images.Total reclaimed space: 512MB
```

-   Can be more selective than system prune.
-   Useful for specific cleanup scenarios.

### System Management

Monitoring Docker system health and resource usage.

#### Accessibility

Explain metrics and statistics clearly.

#### Best Practices

-   Monitor docker stats regularly for resource issues.
-   Use docker system df to prevent disk space issues.
-   Set resource limits on containers.

#### Common Errors

-   **Docker using excessive disk space:** Run \`docker system prune\` to clean up unused resources.

#### Keywords

systemmonitoringstatisticsresource-usageevents

[Learn more](https://docs.docker.com/engine/reference/commandline/system/)

#### Monitor Docker disk usage

Shows Docker's resource consumption and disk usage.

Code

Terminal window

```
# Show Docker disk usagedocker system df
# Show detailed infodocker system df -v
# Show system informationdocker system info
```

Execution

Terminal window

```
docker system df
```

Output

Terminal window

```
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLEImages          15        3         2.5GB     1.8GBContainers      8         2         256MB     200MBLocal Volumes   12        4         512MB     100MB
```

-   TOTAL: Total count of resources.
-   ACTIVE: Currently in use.
-   RECLAIMABLE: Space that could be freed.

#### Monitor container statistics

Shows real-time resource usage for running containers.

Code

Terminal window

```
# Show container resource usagedocker stats
# Show stats for specific containersdocker stats my-web my-db
# Show without streaming (one snapshot)docker stats --no-stream
```

Execution

Terminal window

```
docker stats --no-stream
```

Output

Terminal window

```
CONTAINER   CPU %    MEM USAGE    MEM %    NET I/Omy-web      0.25%    45MB         5%       12MB/8MBmy-db       2.15%    185MB        18%      150MB/120MB
```

-   CPU %, Memory, Network I/O statistics.
-   Useful for identifying resource hogs.

#### Get system events

Monitors Docker system events in real-time.

Code

Terminal window

```
# Show system events in real-timedocker system events
# Filter events for containersdocker system events --filter type=container
# Filter for specific containerdocker system events --filter container=my-web
```

Execution

Terminal window

```
docker system events --filter type=container
```

Output

Terminal window

```
2025-01-10T12:00:15.123Z container create abc123def4562025-01-10T12:00:16.456Z container start abc123def4562025-01-10T12:00:45.789Z container stop abc123def456
```

-   Events include create, start, stop, delete, etc.
-   Filter by type (container, image, volume, etc.).

Was this useful?

## Tags

#Docker#Containers#Images#DevOps#Virtualization#Deployment

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Docker&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker&title=Docker&summary=Docker%20is%20a%20containerization%20platform%20for%20building%2C%20shipping%2C%20and%20running%20applications%20in%20isolated%20environments.%20This%20cheatsheet%20covers%20the%20core%20Docker%20CLI%20commands.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Docker%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker&text=Docker "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker&title=Docker "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker&t=Docker "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker&media=&description=Docker%20is%20a%20containerization%20platform%20for%20building%2C%20shipping%2C%20and%20running%20applications%20in%20isolated%20environments.%20This%20cheatsheet%20covers%20the%20core%20Docker%20CLI%20commands. "Share on Pinterest")[Email](<mailto:?subject=Docker&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fdocker>)

## Comments

## You might also enjoy

More posts on similar topics

## [Docker Swarm](/cheatsheets/docker-swarm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Docker
-   Containers
-   Orchestration
-   Deployment

This cheatsheet is a reference for managing Docker Swarm clusters, services, and stacks. It covers the commands and best practices for scaling, updating, and monitoring your swarm applications.

#Docker Swarm#Orchestration#Containers+4 tags

[read more](/cheatsheets/docker-swarm)

## [Kubernetes](/cheatsheets/kubernetes)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   Container Orchestration
-   Cloud Native
-   Cluster Management

Kubernetes is the de facto standard for container orchestration. It automates deployment, scaling, and management of containerized applications across clusters of machines. Configuration is declarativ

#Kubernetes#Kubectl#Containers+5 tags

[read more](/cheatsheets/kubernetes)

## [Helm](/cheatsheets/helm)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   Helm
-   Package Management
-   Cloud Native

Helm is the package manager for Kubernetes that simplifies the deployment, management, and upgrade of applications. It uses charts, which are templated Kubernetes manifests, to build reusable, configu

#Helm#Kubernetes#Package Manager+5 tags

[read more](/cheatsheets/helm)

## [kubectl](/cheatsheets/kubectl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   DevOps
-   Kubernetes
-   CLI
-   Container Orchestration
-   Cloud Native

kubectl is the command-line tool you use to talk to a Kubernetes cluster. Whatever you can do through a dashboard, you can do faster here: deploy apps, inspect resources, stream logs, run commands ins

#Kubectl#Kubernetes#K8s+5 tags

[read more](/cheatsheets/kubectl)

## [Docker Compose](/cheatsheets/docker-compose)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

Docker Compose is a tool for defining and running multi-container Docker applications. It uses a YAML file to configure application services, networks, and volumes. This cheatsheet provides a quick re

[read more](/cheatsheets/docker-compose)

## [Dockerfile](/cheatsheets/dockerfile)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Reference

This cheat sheet covers the core Dockerfile instructions, best practices, and common pitfalls for building small, secure Docker images. Each section pairs a Dockerfile snippet with the build output it

[read more](/cheatsheets/dockerfile)

6 related posts
