Skip to content

CLI Commands Reference

The Docker CLI (docker) is the primary interface for interacting with the Docker daemon. This reference covers the most commonly used commands organized by category.

Command Structure

Docker CLI commands follow a consistent structure:

bash
docker [OPTIONS] COMMAND [SUBCOMMAND] [ARG...] [FLAGS]

Global Options

OptionDescription
--configLocation of client config files (default ~/.docker)
-c, --contextName of the context to use
-D, --debugEnable debug mode
-H, --hostDaemon socket to connect to
-l, --log-levelSet the logging level (debug, info, warn, error, fatal)
--tlsUse TLS
--tlscacertTrust certs signed only by this CA
--tlscertPath to TLS certificate file
--tlskeyPath to TLS key file
-v, --versionPrint version information

Container Commands

docker run

Create and start a new container:

bash
# Basic usage
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

# Common examples
docker run nginx:latest                        # Run in foreground
docker run -d nginx:latest                     # Run in background (detached)
docker run -it ubuntu:22.04 /bin/bash          # Interactive with terminal
docker run --rm alpine echo "hello"            # Auto-remove after exit
docker run --name my-web -p 8080:80 nginx      # Name and port mapping
docker run -d -e DB_HOST=localhost my-app      # Environment variable
docker run -d -v data:/app/data my-app         # Volume mount
docker run -d --network my-net my-app          # Custom network
docker run -d --restart unless-stopped my-app  # Restart policy
docker run -d --memory 512m --cpus 1.5 my-app  # Resource limits

Run Options Reference

CategoryFlagDescription
Detach-d, --detachRun in background
Interactive-i, --interactiveKeep STDIN open
Terminal-t, --ttyAllocate a pseudo-TTY
Name--nameAssign a container name
Remove--rmAuto-remove when container exits
Ports-p, --publishMap host:container ports
Env-e, --envSet environment variables
Env File--env-fileRead env vars from a file
Volume-v, --volumeBind mount a volume
Mount--mountAttach a filesystem mount
Network--networkConnect to a network
Workdir-w, --workdirWorking directory inside container
User-u, --userUsername or UID
Memory--memoryMemory limit
CPUs--cpusNumber of CPUs
Restart--restartRestart policy
Platform--platformSet platform (e.g., linux/amd64)
Read Only--read-onlyMount root filesystem as read-only
Privileged--privilegedGive extended privileges
Cap Add--cap-addAdd Linux capabilities
Cap Drop--cap-dropDrop Linux capabilities

Container Lifecycle Commands

bash
# Create a container (without starting)
docker create --name my-container nginx:latest

# Start a stopped container
docker start my-container

# Stop a running container (SIGTERM, then SIGKILL after timeout)
docker stop my-container
docker stop -t 30 my-container    # 30-second timeout

# Restart a container
docker restart my-container

# Pause a container (freeze processes)
docker pause my-container

# Unpause a container
docker unpause my-container

# Kill a container (immediate SIGKILL)
docker kill my-container
docker kill -s SIGTERM my-container  # Send specific signal

# Remove a container
docker rm my-container
docker rm -f my-container           # Force remove (running container)

# Remove all stopped containers
docker container prune

Container Inspection Commands

bash
# List running containers
docker ps
docker container ls

# List all containers (including stopped)
docker ps -a

# List container IDs only
docker ps -q

# Format output
docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Ports}}"

# View container logs
docker logs my-container
docker logs -f my-container          # Follow (stream)
docker logs --tail 100 my-container  # Last 100 lines
docker logs --since 1h my-container  # Last hour
docker logs --timestamps my-container # With timestamps

# Inspect container details (JSON)
docker inspect my-container

# Get specific fields
docker inspect -f '{{.State.Status}}' my-container
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-container

# View resource usage statistics
docker stats
docker stats my-container
docker stats --no-stream             # Snapshot (non-streaming)

# View running processes
docker top my-container

# View port mappings
docker port my-container

# View filesystem changes
docker diff my-container

# Copy files between container and host
docker cp my-container:/app/log.txt ./log.txt
docker cp ./config.json my-container:/app/config.json

Execute Commands in Containers

bash
# Run a command in a running container
docker exec my-container ls /app

# Interactive shell
docker exec -it my-container /bin/bash
docker exec -it my-container /bin/sh    # For Alpine-based containers

# Run as a specific user
docker exec -u root my-container whoami

# Set environment variables
docker exec -e MY_VAR=value my-container env

# Set working directory
docker exec -w /app my-container ls

Image Commands

bash
# List local images
docker images
docker image ls

# Pull an image
docker pull nginx:1.25
docker pull --platform linux/amd64 nginx:1.25

# Build an image
docker build -t my-app:1.0 .
docker build -f Dockerfile.prod -t my-app:prod .
docker build --no-cache -t my-app:1.0 .
docker build --build-arg VERSION=2.0 -t my-app:2.0 .

# Tag an image
docker tag my-app:1.0 myuser/my-app:1.0
docker tag my-app:1.0 registry.example.com/my-app:1.0

# Push an image
docker push myuser/my-app:1.0

# Remove an image
docker rmi my-app:1.0
docker image rm my-app:1.0

# Remove unused images
docker image prune            # Dangling images only
docker image prune -a         # All unused images

# Inspect an image
docker image inspect nginx:1.25

# View image history (layers)
docker image history nginx:1.25

# Save an image to tar archive
docker save -o my-app.tar my-app:1.0

# Load an image from tar archive
docker load -i my-app.tar

# Search Docker Hub
docker search nginx

Volume Commands

bash
# Create a volume
docker volume create my-data

# List volumes
docker volume ls

# Inspect a volume
docker volume inspect my-data

# Remove a volume
docker volume rm my-data

# Remove unused volumes
docker volume prune

Network Commands

bash
# Create a network
docker network create my-network
docker network create --driver bridge --subnet 172.20.0.0/16 my-network

# List networks
docker network ls

# Inspect a network
docker network inspect my-network

# Connect a container to a network
docker network connect my-network my-container

# Disconnect a container
docker network disconnect my-network my-container

# Remove a network
docker network rm my-network

# Remove unused networks
docker network prune

System Commands

bash
# View system-wide information
docker info

# View Docker version details
docker version

# View disk usage
docker system df
docker system df -v      # Verbose

# Remove all unused data
docker system prune
docker system prune -a              # Include unused images
docker system prune -a --volumes    # Include volumes

# View real-time events
docker events
docker events --filter event=start
docker events --since 1h

Docker Compose Commands

bash
# Start services
docker compose up
docker compose up -d                  # Detached
docker compose up --build             # Rebuild images

# Stop services
docker compose down
docker compose down -v                # Remove volumes
docker compose down --rmi all         # Remove images

# List running services
docker compose ps

# View logs
docker compose logs
docker compose logs -f web            # Follow specific service

# Scale services
docker compose up -d --scale web=3

# Execute command in a service
docker compose exec web /bin/sh

# Build services
docker compose build

# Pull images
docker compose pull

# Restart services
docker compose restart

Command Cheat Sheet

TaskCommand
Run a containerdocker run -d -p 80:80 nginx
List containersdocker ps -a
Stop a containerdocker stop <name>
View logsdocker logs -f <name>
Shell into containerdocker exec -it <name> sh
Build an imagedocker build -t app:1.0 .
Push an imagedocker push user/app:1.0
Remove everythingdocker system prune -a --volumes
Check disk usagedocker system df
Inspect anythingdocker inspect <name>

Next Steps

基于 MIT 许可发布