Docker Run Reference
docker run is the command that launches a container from an image. It combines docker create and docker start into one atomic operation.
Lifecycle Visualization
flowchart LR
Image((Image)) -->|docker run| Container([Running Container])
Container -->|docker stop| Stopped([Stopped Container])
Stopped -->|docker rm| Deleted((Deleted))
Container -->|Crash/Exit| Exited([Exited])
Basic Syntax
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Common Flags Reference
| Flag | Category | Description |
|---|---|---|
-d, --detach | Lifecycle | Run in background (detached mode). |
--name | Lifecycle | Assign a custom name (e.g., --name my-db). |
--rm | Lifecycle | Automatically remove the container when it exits. |
-p, --publish | Network | Map host port to container port (e.g., -p 80:80). |
-v, --volume | Storage | Mount a volume or bind mount (e.g., -v data:/data). |
-e, --env | Config | Set environment variable (e.g., -e POSTGRES_PASSWORD=secret). |
--restart | Lifecycle | Restart policy (no, always, unless-stopped). |
-it | Interactive | allocate a pseudo-TTY and keep stdin open (for shells). |
Examples
1. Run a Web Server (Background)
docker run -d \
--name web-server \
-p 8080:80 \
nginx:alpine
2. Run an Interactive Shell (Foreground)
# This drops you into the container's shell
docker run --rm -it ubuntu:22.04 bash
Note: --rm ensures the container is deleted after you exit the shell.
3. Run a Database with Persistence
docker run -d \
--name db \
-v pgdata:/var/lib/postgresql/data \
-e POSTGRES_PASSWORD=mysecret \
postgres:15
Restart Policies
| Policy | Behavior | Best For |
|---|---|---|
no | Do not restart automatically. | One-off jobs. |
on-failure | Restart only if exit code != 0. | Batch processing workers. |
always | Always restart. | Production services. |
unless-stopped | Restart unless explicitly stopped by user. | Preferred default for services. |
tip
Always use --name in production scripts. Random names like determined_wozniak make debugging impossible.
What's Next
- Continue to Logs, Exec, and Inspect to learn how to debug running containers.