Run a container in the foreground (attached)
Runningdocker run nginx without extra flags starts the container in the foreground and attaches your terminal to the container’s stdout/stderr. This is useful for debugging or when you want to interact with the container directly.
Example output (shortened):
Using the
-d flag runs the container in the background (detached mode) and prints the container ID. Note: detached mode does not publish container ports to the host by default — even if the image declares EXPOSE. To make container ports accessible on the host you must explicitly publish them, for example with -p host_port:container_port.Run a container in the background (detached)
Start nginx in detached mode and then list running containers:Understanding docker ps output
docker ps shows only running containers. Here are the key columns and what they mean:
Stop a running container
To stop a running container, usedocker stop with the container ID, name, or a unique prefix:
docker ps will no longer list the container because it shows only running containers. Use docker ps -a to see all containers, including those that have exited.
Remove stopped containers
Over time you may accumulate many stopped (exited) containers. Usedocker rm to remove stopped containers. You can remove one or multiple containers by listing their IDs or names:
docker ps -a will show fewer or no exited containers.
docker rm only removes stopped containers. To delete a running container, stop it first (for example docker stop <container>). To remove all stopped containers at once, use docker container prune (prompts for confirmation) or docker rm $(docker ps -a -q) to remove all containers returned by docker ps -a (this will fail for any running containers). Use these commands with caution.Quick reference — common container lifecycle commands
Links and references
- Docker run reference: https://docs.docker.com/engine/reference/commandline/run/
- Docker ps reference: https://docs.docker.com/engine/reference/commandline/ps/
- Manage containers: https://docs.docker.com/engine/reference/commandline/container/
-d) to run services in the background, docker ps / docker ps -a to inspect, and docker rm or docker container prune to clean up stopped containers.