Skip to content

Running Containers

First PublishedByAtif Alam

You run an image as a container with docker run. Common flags control detached vs interactive mode, port mapping, volumes, and environment variables.

Terminal window
# Run once; use default CMD
docker 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 sh
FlagShortPurpose
—detach-dRun in background.
—interactive-iKeep stdin open.
—tty-tAllocate a pseudo-TTY. Use -it for an interactive shell.
—publish-pMap host port to container port (e.g. -p 8080:80).
—volume-vMount a volume or bind mount (e.g. -v /data:/app/data).
—env-eSet environment variable (e.g. -e NODE_ENV=production).
—nameGive the container a name for easier reference.
—rmRemove the container when it exits.
Terminal window
# Run nginx, publish host 8080 → container 80, remove on exit
docker run -d --rm --name web -p 8080:80 nginx:alpine
# Run with env var and bind mount
docker run -d -e DB_HOST=db -v $(pwd)/config:/app/config myapp:1.0
# Interactive shell in a running image
docker run -it --rm alpine:3.19 sh
Terminal window
docker start <container> # Start a stopped container
docker stop <container> # Stop (SIGTERM then SIGKILL)
docker restart <container>
docker rm <container> # Remove (must be stopped unless -f)
docker ps # List running containers
docker ps -a # List all containers
Terminal window
# Follow logs
docker logs -f <container>
# Run a command in a running container
docker exec -it <container> sh
docker exec <container> env
  • 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.