docker run
Create and start a new container from an image. The most common Docker command for launching containers.
Syntax
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Examples
Example 1
docker run nginx
Run nginx in foreground (blocks terminal).
Example 2
docker run -d --name my-app -p 8080:80 nginx
Run in detached mode with custom name and port mapping.
Example 3
docker run -it --rm ubuntu bash
Interactive shell, remove container when it exits.
Example 4
docker run -e NODE_ENV=production -v $(pwd):/app node:20
Set env var and bind-mount current directory.
Common flags
| Flag | Description |
|---|---|
| -d, --detach | Run in background |
| -it | Interactive TTY (combine -i -t) |
| --name | Assign a name to the container |
| -p, --publish | Map host:container ports |
| -v, --volume | Bind mount a volume |
| -e, --env | Set environment variable |
| --rm | Remove container when it exits |
Tips & best practices
- •Use --rm to avoid accumulating stopped containers.
- •Prefer -p 8080:80 over -P when you need a specific host port.
- •Use --read-only for security-sensitive workloads.