Sub topic 1
The Container Lifecycle: Created, Running, Stopped, Removed
Prerequisites
Assume Docker is installed, the Docker daemon is running, and you know the difference between an image and a container. A container is a runnable instance of an image.
Lifecycle States
A container moves through these states:
- Created: Docker has made the container from an image, but its process has not started.
- Running: The container's main process is active.
- Stopped: The main process has exited. Docker keeps the container so you can inspect or start it again.
- Removed: Docker has deleted the container's metadata and writable layer.
docker run normally creates and starts a container in one operation. docker create creates one without starting it.
Referring to Containers by Name and ID
Each container has a generated or assigned name and a unique ID. Names are easier to read in commands. IDs are useful when names are unknown. Docker accepts a unique prefix of an ID.
docker run -d --name web nginx:alpine
docker ps
docker ps -aThe -d option runs the container in the background. docker ps shows running containers. The -a option includes stopped and created containers.
> Callout note > A stopped container still exists. Removing it is a separate operation.
Listing, Filtering, and Formatting
Use docker ps to inspect lifecycle state. The STATUS column shows whether a container is running or exited.
| Command | Purpose |
|---|---|
| `docker ps` | List running containers |
| `docker ps -a` | List all containers |
| `docker ps -a --filter "status=exited"` | List only stopped containers |
Filters reduce the result set. Formatting makes output suitable for scripts or quick inspection.
docker ps -a \
--filter "status=exited" \
--format "table {{.Names}}\t{{.Status}}\t{{.Image}}"The --format template selects fields instead of printing Docker's full table. Common fields include .Names, .ID, .Status, and .Image.
Exercise
Which command lists stopped containers while keeping them available for a later restart?
Show answer
docker ps -a --filter "status=exited" lists stopped containers without removing them.