Running Containers
You run an image as a container with docker run. Common flags control detached vs interactive mode, port mapping, volumes, and environment variables.
Basic Run
Section titled “Basic Run”# Run once; use default CMDdocker run nginx:alpine
# Run in background (detached)docker run -d nginx:alpine
# Run interactively with a TTY (e.g. shell)docker run -it alpine:3.19 shCommon Flags
Section titled “Common Flags”| Flag | Short | Purpose |
|---|---|---|
| —detach | -d | Run in background. |
| —interactive | -i | Keep stdin open. |
| —tty | -t | Allocate a pseudo-TTY. Use -it for an interactive shell. |
| —publish | -p | Map host port to container port (e.g. -p 8080:80). |
| —volume | -v | Mount a volume or bind mount (e.g. -v /data:/app/data). |
| —env | -e | Set environment variable (e.g. -e NODE_ENV=production). |
| —name | Give the container a name for easier reference. | |
| —rm | Remove the container when it exits. |
Examples
Section titled “Examples”# Run nginx, publish host 8080 → container 80, remove on exitdocker run -d --rm --name web -p 8080:80 nginx:alpine
# Run with env var and bind mountdocker run -d -e DB_HOST=db -v $(pwd)/config:/app/config myapp:1.0
# Interactive shell in a running imagedocker run -it --rm alpine:3.19 shLifecycle
Section titled “Lifecycle”docker start <container> # Start a stopped containerdocker stop <container> # Stop (SIGTERM then SIGKILL)docker restart <container>docker rm <container> # Remove (must be stopped unless -f)docker ps # List running containersdocker ps -a # List all containersLogs and Exec
Section titled “Logs and Exec”# Follow logsdocker logs -f <container>
# Run a command in a running containerdocker exec -it <container> shdocker exec <container> envKey Takeaways
Section titled “Key Takeaways”- Use -d for background, -it for interactive shell, -p for port mapping, -v for volumes, -e for env vars.
- docker start/stop/rm manage lifecycle; docker logs and docker exec inspect and run commands in running containers.