Skip to main content
This lesson shows how to run containers in the foreground and background, how to view running and stopped containers, and how to remove stopped containers. You’ll see concrete examples and the exact commands to manage lifecycles of Docker containers.

Run a container in the foreground (attached)

Running docker 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):
To detach from the container and return to your shell without stopping the container, run the container in detached mode.
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, use docker stop with the container ID, name, or a unique prefix:
After stopping, 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. Use docker rm to remove stopped containers. You can remove one or multiple containers by listing their IDs or names:
After removal, 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

Summary: use attached mode for interactive debugging, detached mode (-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.

Watch Video