Docker Containers
What is a Container?
A container is a running instance of a Docker image. When you run an image, Docker creates a container from it - a live, isolated process with its own filesystem, network, and process space.
Image (blueprint) -> Container (running app)
nginx:latest -> container-1 (port 8080, running)
nginx:latest -> container-2 (port 8081, stopped)
nginx:latest -> container-3 (port 8082, running)
One image can create many containers. Each container is isolated from the others.
Container Lifecycle
| State | Meaning |
|---|---|
| Created | Container exists but has not started |
| Running | Container is actively running |
| Paused | Processes inside are frozen, memory preserved |
| Stopped/Exited | Container stopped, state preserved on disk |
| Deleted/Removed | Container is gone permanently |
All Docker Container Commands
docker run - Create and Start a Container
The most important command. It creates a container from an image and starts it.
# Basic run - runs in foreground (attached mode)
docker run nginx
# Run in detached mode (background)
docker run -d nginx
# Run with a custom name
docker run -d --name my-nginx nginx
# Map port: host:container
docker run -d -p 8080:80 nginx
# Map multiple ports
docker run -d -p 8080:80 -p 443:443 nginx
# Run interactively with a terminal
docker run -it ubuntu bash
# Run and remove container automatically when it exits
docker run --rm hello-world
# Set environment variable
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# Set multiple environment variables
docker run -d -e MYSQL_ROOT_PASSWORD=secret -e MYSQL_DATABASE=mydb mysql
# Mount a volume
docker run -d -v my-volume:/data nginx
# Bind mount a local folder
docker run -d -v C:/myapp:/app nginx
# Set working directory inside container
docker run -d -w /app node
# Override the default command
docker run ubuntu echo "Hello World"
# Run as a specific user
docker run --user 1000:1000 nginx
# Set hostname
docker run -d --hostname my-server nginx
# Connect to a specific network
docker run -d --network my-network nginx
# Set memory limit
docker run -d --memory 512m nginx
# Set CPU limit
docker run -d --cpus 1.5 nginx
# Set restart policy
docker run -d --restart always nginx
docker run -d --restart unless-stopped nginx
docker run -d --restart on-failure:3 nginx
# Add a DNS server
docker run -d --dns 8.8.8.8 nginx
# Set labels
docker run -d --label app=web nginx
# Run with all common flags combined
docker run -d \
--name my-web \
-p 8080:80 \
-e APP_ENV=production \
-v my-data:/data \
--restart unless-stopped \
--memory 256m \
nginx
Restart Policy Options:
| Policy | Behavior |
|---|---|
no | Never restart (default) |
always | Always restart, even on Docker daemon restart |
unless-stopped | Restart unless you manually stopped it |
on-failure | Restart only on failure (non-zero exit code) |
on-failure:3 | Restart on failure, max 3 times |
docker ps - List Containers
# List only running containers
docker ps
# List ALL containers (running + stopped)
docker ps -a
docker ps --all
# Show only container IDs
docker ps -q
# Show all container IDs
docker ps -aq
# Show last N created containers
docker ps -n 5
# Show the last created container
docker ps -l
# Custom format
docker ps --format "{{.Names}}\t{{.Status}}\t{{.Ports}}"
docker ps --format "table {{.Names}}\t{{.Image}}\t{{.Status}}"
# Filter by status
docker ps --filter "status=running"
docker ps --filter "status=exited"
docker ps --filter "status=paused"
# Filter by name
docker ps --filter "name=nginx"
# Filter by ancestor image
docker ps --filter "ancestor=nginx"
# Filter by network
docker ps --filter "network=my-network"
docker start - Start a Stopped Container
# Start by name
docker start my-nginx
# Start by container ID
docker start a1b2c3d4e5f6
# Start multiple containers
docker start container1 container2 container3
# Start and attach to output
docker start -a my-nginx
# Start with interactive mode
docker start -ai my-container
docker stop - Stop a Running Container
Sends SIGTERM to the main process - allows graceful shutdown.
# Stop by name
docker stop my-nginx
# Stop by container ID
docker stop a1b2c3d4e5f6
# Stop multiple containers
docker stop container1 container2
# Stop with a custom timeout (seconds before force kill)
docker stop --time 30 my-nginx
docker stop -t 30 my-nginx
# Stop all running containers
docker stop $(docker ps -q)
docker restart - Restart a Container
Stops and then starts a container.
# Restart by name
docker restart my-nginx
# Restart with a wait timeout
docker restart -t 10 my-nginx
# Restart multiple containers
docker restart container1 container2
# Restart all running containers
docker restart $(docker ps -q)
docker kill - Force Stop a Container
Sends SIGKILL immediately - no graceful shutdown.
# Kill by name
docker kill my-nginx
# Kill with a specific signal
docker kill --signal SIGTERM my-nginx
docker kill --signal 9 my-nginx
# Kill multiple containers
docker kill container1 container2
# Kill all running containers
docker kill $(docker ps -q)
> Use docker stop for normal shutdown. Use docker kill only when stop doesn't work.
docker pause / docker unpause - Pause and Resume
Freezes all processes inside the container without stopping it. Memory is preserved.
# Pause a container
docker pause my-nginx
# Pause multiple containers
docker pause container1 container2
# Unpause (resume) a container
docker unpause my-nginx
# Unpause multiple containers
docker unpause container1 container2
docker rm - Remove a Container
Deletes a container. The container must be stopped first (unless using -f).
# Remove a stopped container
docker rm my-nginx
# Force remove a running container
docker rm -f my-nginx
# Remove multiple containers
docker rm container1 container2
# Remove and delete its anonymous volumes
docker rm -v my-nginx
# Remove all stopped containers
docker rm $(docker ps -aq)
docker container prune
# Remove with confirmation
docker container prune
# Remove without confirmation
docker container prune -f
# Remove containers that exited more than 24h ago
docker container prune --filter "until=24h"
docker exec - Run a Command Inside a Running Container
Runs a new command in an already-running container.
# Run a single command
docker exec my-nginx ls /etc/nginx
# Run an interactive bash shell
docker exec -it my-nginx bash
# Run sh (for containers that don't have bash)
docker exec -it my-nginx sh
# Run as a specific user
docker exec -u root -it my-nginx bash
# Set environment variable for the command
docker exec -e DEBUG=true my-nginx printenv
# Run in a specific directory
docker exec -w /etc/nginx my-nginx cat nginx.conf
docker attach - Attach to a Running Container's Output
Connects your terminal to the main process of a running container.
# Attach to a container
docker attach my-nginx
# Detach without stopping: press Ctrl+P then Ctrl+Q
> docker exec -it is usually preferred over docker attach because exec opens a new process and won't accidentally stop the container.
docker logs - View Container Output
Shows the stdout/stderr output of a container.
# View all logs
docker logs my-nginx
# Follow logs in real time (like tail -f)
docker logs -f my-nginx
docker logs --follow my-nginx
# Show last N lines
docker logs --tail 100 my-nginx
docker logs -n 50 my-nginx
# Show logs with timestamps
docker logs -t my-nginx
docker logs --timestamps my-nginx
# Show logs since a time
docker logs --since 1h my-nginx
docker logs --since 2024-01-01 my-nginx
# Show logs until a time
docker logs --until 30m my-nginx
# Combine options
docker logs -f -t --tail 50 my-nginx
docker inspect - Detailed Container Info
Returns detailed JSON info about a container.
# Full inspect
docker inspect my-nginx
# Get the container IP address
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-nginx
# Get the container's mounted volumes
docker inspect -f '{{json .Mounts}}' my-nginx
# Get environment variables
docker inspect -f '{{json .Config.Env}}' my-nginx
# Get port bindings
docker inspect -f '{{json .NetworkSettings.Ports}}' my-nginx
# Get the restart count
docker inspect -f '{{.RestartCount}}' my-nginx
# Get container status
docker inspect -f '{{.State.Status}}' my-nginx
# Get start time
docker inspect -f '{{.State.StartedAt}}' my-nginx
docker stats - Live Resource Usage
Shows real-time CPU, memory, and network usage for containers.
# Stats for all running containers (live)
docker stats
# Stats for a specific container
docker stats my-nginx
# Stats for multiple containers
docker stats container1 container2
# One-time snapshot (not live)
docker stats --no-stream
# Custom format
docker stats --format "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"
Example output:
NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O
my-nginx 0.01% 3.5MiB / 7.8GiB 0.04% 6.5kB / 0B 0B / 0B
docker top - Show Processes Inside Container
# List processes inside a container
docker top my-nginx
# With ps options
docker top my-nginx aux
docker rename - Rename a Container
docker rename old-name new-name
docker rename my-nginx web-server
docker cp - Copy Files Between Container and Host
# Copy from container to host
docker cp my-nginx:/etc/nginx/nginx.conf ./nginx.conf
# Copy from host to container
docker cp ./index.html my-nginx:/usr/share/nginx/html/index.html
# Copy a directory
docker cp my-nginx:/etc/nginx ./nginx-config
# Copy to a running or stopped container
docker cp ./app.js my-app:/app/app.js
docker diff - Show Changes to Container Filesystem
Shows what files were added (A), changed (C), or deleted (D) since the container started.
docker diff my-nginx
Output:
C /etc
C /etc/nginx
A /etc/nginx/custom.conf
D /var/log/nginx/access.log
docker commit - Create Image from Container
Creates a new image from the current state of a container. Useful for saving manual changes.
# Create image from container
docker commit my-nginx my-custom-nginx
# Add a message and author
docker commit -m "Added custom config" -a "Irfan" my-nginx my-custom-nginx:1.0
# Pause container while committing
docker commit --pause my-nginx my-custom-nginx
> Using Dockerfiles is preferred over docker commit. Use commit only for quick experiments.
docker port - Show Port Mappings
# Show all port mappings
docker port my-nginx
# Show a specific container port
docker port my-nginx 80
Output:
80/tcp -> 0.0.0.0:8080
docker wait - Wait for Container to Stop
Blocks until the container stops, then prints the exit code.
docker wait my-nginx
docker export / docker import - Export Container Filesystem
Export saves the container's filesystem (not the image, just the files).
# Export container filesystem to tar
docker export my-nginx > nginx-fs.tar
docker export -o nginx-fs.tar my-nginx
# Import as a new image
docker import nginx-fs.tar my-imported-image
docker import nginx-fs.tar my-image:latest
> docker save/load is for images. docker export/import is for container filesystems.
docker update - Update Container Configuration
Updates resource limits of a running container without restarting it.
# Update memory limit
docker update --memory 512m my-nginx
# Update CPU limit
docker update --cpus 2 my-nginx
# Update restart policy
docker update --restart always my-nginx
# Update multiple containers
docker update --memory 256m container1 container2
Container Commands Quick Reference
| Command | What it does |
|---|---|
docker run -d nginx | Run container in background |
docker run -it ubuntu bash | Run interactive shell |
docker run --rm hello-world | Run and auto-delete |
docker ps | List running containers |
docker ps -a | List all containers |
docker start <name> | Start stopped container |
docker stop <name> | Gracefully stop container |
docker restart <name> | Restart container |
docker kill <name> | Force stop container |
docker pause <name> | Freeze container |
docker unpause <name> | Resume frozen container |
docker rm <name> | Delete stopped container |
docker rm -f <name> | Force delete running container |
docker exec -it <name> bash | Open shell in container |
docker logs -f <name> | Follow container logs |
docker inspect <name> | Show detailed info |
docker stats | Live resource usage |
docker top <name> | Show container processes |
docker rename <old> <new> | Rename container |
docker cp <src> <dest> | Copy files in/out |
docker diff <name> | Show filesystem changes |
docker commit <name> <image> | Save container as image |
docker port <name> | Show port mappings |
docker update <name> | Update resource limits |
FAQ
Should I memorize every Docker command?+
No. Memorize the core workflow first: build, run, list, inspect, logs, exec, stop, remove, and clean up. Then learn specialized commands when you need them.
Is Docker only for developers?+
No. Docker is useful for system administrators, infrastructure engineers, DevOps engineers, cloud engineers, support engineers, and learners who want repeatable labs.
What should I do after reading this guide?+
Run the examples, write down what each command changes, rebuild the workflow with Docker Compose, and then add one CI/CD step that builds the image automatically.
Need help applying Docker in a real project?
Work directly with Muhammad Irfan Aslam for Docker, Linux, DevOps, CI/CD, cloud deployment, or infrastructure troubleshooting support.
Hire Me for Support