Skip to main content

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

FlagCategoryDescription
-d, --detachLifecycleRun in background (detached mode).
--nameLifecycleAssign a custom name (e.g., --name my-db).
--rmLifecycleAutomatically remove the container when it exits.
-p, --publishNetworkMap host port to container port (e.g., -p 80:80).
-v, --volumeStorageMount a volume or bind mount (e.g., -v data:/data).
-e, --envConfigSet environment variable (e.g., -e POSTGRES_PASSWORD=secret).
--restartLifecycleRestart policy (no, always, unless-stopped).
-itInteractiveallocate 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

PolicyBehaviorBest For
noDo not restart automatically.One-off jobs.
on-failureRestart only if exit code != 0.Batch processing workers.
alwaysAlways restart.Production services.
unless-stoppedRestart 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