Card 04/ 06

ExampleDifficulty: Intermediate1 min

Why a Container Exited: docker ps -a and docker logs

A container that vanished from the list is still there, and it left a message.

When a container stops on its own, two commands tell you why: docker ps -a, which lists stopped containers as well as running ones, and docker logs, which shows what the program printed. Together they take you from "it is gone" to the error that stopped it.

You start a container in the background, and by the time you look for it, docker ps shows nothing:

bash
docker run -d --name api my-api
3c8f0a1d5b62
docker ps
CONTAINER ID   IMAGE   STATUS   NAMES

docker ps lists what is running. A container that exited is still there, and -a is what shows it.

bash
docker ps -a --format '{{.Names}}\t{{.Status}}'
api	Exited (1) 6 seconds ago

The status shows exit code 1. A non-zero exit code means the program did not finish successfully. A code of 1 usually means the program reported an error itself; 137 and 143 mean it was killed or stopped from outside. Whatever it printed before stopping is kept with the container:

bash
docker logs api
Error: DATABASE_URL is not set

The container exiting is almost never the problem itself. It is the program inside reporting one, here a missing setting, and docker logs is where it said so. So when a container disappears, run those two commands before changing anything.