Chapter 04 • Core Foundations

Essential Docker CLI Commands

Mastering the Docker command-line interface (CLI) is a core prerequisite for DevOps, backend engineering, and modern cloud architectures. This reference covers container creation, runtime flag combinations, in-container debugging, and real-time resource telemetry.

1. Anatomy of the docker run Command

The docker run command is a convenience wrapper combining docker create (allocating container filesystem layers and network endpoints) and docker start (executing the entrypoint process). Production invocations combine multiple runtime flags:

docker run -d \
  --name production-api \
  -p 8080:3000 \
  -e NODE_ENV=production \
  -e DATABASE_URL="postgresql://user:secret@db:5432/app" \
  -v app_data:/app/uploads \
  --restart unless-stopped \
  --memory 512m \
  --cpus 1.5 \
  node:20-alpine
FlagFull NameFunction & Behavior
-d--detachRuns container in the background and prints the container ID hash to terminal.
-p host:container--publishBinds host machine port to the container's internal listening port via iptables / nftables.
--name--name <str>Assigns a unique, friendly identifier (otherwise Docker assigns random adjectives e.g. clever_curie).
-e--env KEY=VALInjects environment variables into the container's PID 1 process environment.
-v host:container--volumeMounts a named volume or host directory for persistent, stateful data storage.
--restart--restart <policy>Automated recovery policy: always, unless-stopped, or on-failure:5.
--rm--rmAutomatically destroys the container and its writable layer once the process exits (ideal for one-off tasks).
-it--interactive --ttyAllocates a pseudo-TTY connected to STDIN for interactive terminal shells.

2. Container Inspection & Monitoring

When diagnosing production workloads, these commands provide real-time visibility into process states and resource utilization:

A. Real-Time Resource Streaming: docker stats

Streams CPU percentage, memory usage, limits, network I/O, and block I/O across all active containers:

# Stream live metrics for all active containers:
docker stats

# Print a one-time snapshot without live streaming:
docker stats --no-stream --format "table {{.Name}}	{{.CPUPerc}}	{{.MemUsage}}"
B. Log Streaming: docker logs

Docker captures everything printed to STDOUT and STDERR by the container's root process:

# Stream logs continuously with timestamps and last 100 lines:
docker logs -f --tail 100 --timestamps production-api
C. Extracting Metadata: docker inspect with Go Templates

Inspect returns the complete JSON state of a container. Use --format to extract specific nested values:

# Extract container private IP address directly:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' production-api

# Check container health status:
docker inspect -f '{{.State.Health.Status}}' production-api

3. Executing Commands Inside Containers

docker exec starts a new process inside an existing, running container's namespaces:

# 1. Open an interactive Bash shell (Debian/Ubuntu based images):
docker exec -it production-api /bin/bash

# 2. For lightweight Alpine Linux images (which lack bash):
docker exec -it production-api /bin/sh

# 3. Execute a one-off database migration without opening a shell:
docker exec production-api npm run db:migrate

# 4. Copy files to or from a running container:
docker cp ./config.json production-api:/app/config.json
docker cp production-api:/app/logs/error.log ./local-error.log

4. Container Termination: docker stop vs docker kill

docker stop (Graceful Shutdown)

Sends the SIGTERM Unix signal to PID 1. The container process has 10 seconds (default grace period) to close open database connections, flush write buffers to disk, and exit cleanly. If the process does not terminate within the timeout, Docker sends SIGKILL.

docker stop -t 30 production-api
docker kill (Forceful Abort)

Immediately sends the SIGKILL Unix signal directly to the kernel to terminate the process without grace. Risk: Uncommitted database transactions or file writes can be corrupted.

docker kill production-api

Next Up: Working with Docker Images

In Chapter 5, discover how Docker images are stored as immutable content-addressable layers, how digests prevent tampering, and how to manage tags.

Chapter 05: Working with Docker Images →

Explore Related Tools

Hand-picked utilities and calculators related to this tool.

Related Tools