Back to tools
Common docker run options
- -d, --detach: Run in background
- --rm: Remove container on exit
- -p host:container: Map ports
- -v host:container: Mount volumes
- -e KEY=VALUE: Environment variables
- --name: Container name
- --network: Network to use
- --restart: Restart policy (always, on-failure)
- -u: User (UID:GID)
- -w: Working directory
- --memory: Memory limit
- --cpus: CPU limit
Frequently Asked Questions
How to run an Nginx container with docker run mapping ports and volumes?
To run Nginx with docker run: `docker run -d --name nginx-web -p 80:80 -p 443:443 -v /host/html:/usr/share/nginx/html:ro -v /host/nginx.conf:/etc/nginx/nginx.conf:ro nginx:alpine`. The `-d` flag runs in detached mode, `-p 80:80` maps host port 80 to container port 80, `-v` mounts host directories as volumes with `:ro` for read-only, and `--name` assigns a human-readable name. The nginx:alpine image is significantly smaller than the standard nginx image.
How to set environment variables with docker run for PostgreSQL?
To run PostgreSQL with docker run: `docker run -d --name postgres-db -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=myapp -p 5432:5432 -v pgdata:/var/lib/postgresql/data postgres:16-alpine`. The `-e` flags configure user, password and initial database. Use a named volume (`pgdata`) instead of a bind mount so Docker manages storage location. Add `--restart unless-stopped` for automatic restart.
What is the difference between docker run -d and -it and when to use each?
`docker run -d` (detached) runs the container in the background and returns control immediately. Best for servers like Nginx, PostgreSQL or Redis that run persistently. `docker run -it` (interactive + TTY) keeps the session open for direct interaction, such as `docker run -it ubuntu bash` to get a shell. For ephemeral tasks add `--rm` to auto-remove the container on exit. You can combine both: start with -d then attach with `docker exec -it container bash`.
How to limit memory and CPU for a container with docker run flags?
To limit container resources with docker run: `docker run -d --memory=512m --memory-reservation=256m --cpus=1.5 --cpuset-cpus=0-1 nginx`. `--memory` caps maximum RAM usage (512 MB), `--memory-reservation` sets a soft limit. `--cpus` throttles CPU usage (1.5 cores) and `--cpuset-cpus` pins to specific physical cores. Docker leverages Linux kernel control groups (cgroups) to enforce these limits. Without resource constraints a single container can consume all host resources.