Skip to main content
In this lesson you’ll learn how to run containers in the foreground and background (detached mode), how to list running and exited containers, and how to remove containers you no longer need. These are essential Docker basics for managing container lifecycles on development and production hosts.

Running a container in the foreground (no -d)

By default, docker run attaches your terminal to the container’s STDOUT/STDERR. This is useful for debugging or when you want to see process output in real time. However, interrupting your terminal (for example with Ctrl+C) sends a termination signal to the container and causes it to exit. Example: running the official nginx image in the foreground
When you need a running container to continue after you close the terminal, run it in detached mode.

Running a container in the background (detached mode)

Add the -d flag to docker run to start the container detached. Docker prints the container ID and returns you immediately to the shell; the container continues running in the background. Example:
The long hex string printed is the full container ID. You can use a short, unique prefix of that ID with most Docker commands.

List running containers

To see containers that are currently running, use:
Example output:
Notes about IDs and names
  • The full container ID is 64 hex characters; most commands accept the short form (first 4–12 characters) as long as it is unique.
  • Docker assigns a human-readable container name (e.g., adoring_zhukovsky) if you don’t provide one. You can set a custom name with --name <name> when running the container.

Stopping a running container

Use docker stop followed by the container ID, its short unique prefix, or its name. Example:
After stopping, docker ps will not list that container:

List all containers (including exited)

To view every container on the host — running and exited — use docker ps -a. Example:

Removing containers

Exited containers remain on disk until you explicitly remove them. Use docker rm to delete container metadata and its writable layer. You can pass multiple IDs or names in one command. Remove a single container (short ID):
Remove multiple containers at once:
After removal, docker ps -a will list only the containers that remain:

Quick reference — common container lifecycle commands

Detached containers still run in the background and produce logs. Use docker logs <container> to inspect output, and docker exec -it <container> /bin/sh (or /bin/bash) to open an interactive shell inside a running container.
Be careful when removing containers: docker rm deletes container metadata and filesystem changes made in that container. If you need to preserve data, consider using volumes or committing the container to an image before removal.

Watch Video