Docker Containers
6. Docker Containers
Section titled “6. Docker Containers”🚀 What is a Container (Running)?
Section titled “🚀 What is a Container (Running)?”If an image is a recipe, then a container is the cooked meal.
A container is a running instance of an image. You can run multiple containers from the same image, just like cooking the same recipe multiple times.
🕹️ Core Container Commands
Section titled “🕹️ Core Container Commands”# === CREATING AND RUNNING ===
# Run a container (creates + starts)docker run nginx
# Run with a custom namedocker run --name my-nginx nginx
# Run in detached mode (background)docker run -d nginx
# Run interactively (with terminal)docker run -it ubuntu bash
# Run and auto-remove when stoppeddocker run --rm nginx
# === LISTING CONTAINERS ===
# List running containersdocker ps
# List ALL containers (including stopped)docker ps -adocker ps --all
# === STARTING / STOPPING ===
# Stop a running containerdocker stop my-nginx
# Start a stopped containerdocker start my-nginx
# Restart a containerdocker restart my-nginx
# Pause a containerdocker pause my-nginx
# Unpause a containerdocker unpause my-nginx
# === REMOVING ===
# Remove a stopped containerdocker rm my-nginx
# Force remove a running containerdocker rm -f my-nginx
# Remove all stopped containersdocker container prune
# === INSPECTING ===
# View container detailsdocker inspect my-nginx
# View running processes inside containerdocker top my-nginx🔍 Understanding docker ps Output
Section titled “🔍 Understanding docker ps Output”docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESa3f5b2c1d4e8 nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:80->80/tcp my-nginx| Column | Meaning |
|---|---|
| CONTAINER ID | Unique short ID of the container |
| IMAGE | Image used to create the container |
| COMMAND | Process running inside the container |
| CREATED | When the container was created |
| STATUS | Current state (Up, Exited, Paused) |
| PORTS | Port mappings (host:container) |
| NAMES | Human-readable name |
🔄 Container Lifecycle Example
Section titled “🔄 Container Lifecycle Example”# 1. Create and run nginxdocker run -d --name web nginx
# 2. Check it's runningdocker ps
# 3. Stop itdocker stop web
# 4. See it in stopped statedocker ps -a
# 5. Start it againdocker start web
# 6. Remove it (must be stopped first)docker stop webdocker rm web
# Or force remove while runningdocker rm -f web⚠️ Common Container Mistakes
Section titled “⚠️ Common Container Mistakes”- Forgetting
-dand blocking your terminal - Running
docker rmon a running container without-f - Accumulating stopped containers — always clean up with
docker container prune