CoursesDocker for beginnersWorking with containers

The core commands

run, ps, stop, rm, images.

Beginner12 min · lesson 5 of 16
In plain terms
Managing containers is like managing appliances in a room: switch one on (run), glance at what’s currently on (ps), switch it off (stop), and haul the dead one out (rm). A handful of switches covers almost everything.

You can get a very long way with a handful of commands, and they are worth building into reflexes: run to start a container, ps to list what is running, stop to stop it, rm to remove it, images to list images, and rmi to remove them. Everything fancier is a variation on these. Start with the simplest possible run and watch it appear in ps.

terminal
$ docker run -d --name web nginx:1.27 # start a container in the background
7f8e9d0a1b2c...
$ docker ps # what is running now
CONTAINER ID IMAGE STATUS NAMES
7f8e9d0a1b2c nginx:1.27 Up 3 seconds web

Running versus stopped

docker ps shows only running containers; add -a to see stopped ones too, which is how you find the container that exited immediately because of an error. docker stop asks the process to shut down gracefully — it sends SIGTERM, waits about ten seconds, then SIGKILL if it has not exited. That grace period matters for apps that need to finish in-flight work, and it is worth knowing so a stop that “hangs for ten seconds” does not surprise you.

terminal
$ docker stop web # graceful: SIGTERM, then SIGKILL after ~10s
web
$ docker ps -a # still listed, now Exited
CONTAINER ID IMAGE STATUS NAMES
7f8e9d0a1b2c nginx:1.27 Exited (0) 4 seconds ago web
$ docker rm web # now remove it
web

Cleaning up

Stopped containers and unused images pile up quietly and eat disk. rm removes containers and rmi removes images, but the fastest cleanup is the prune family, which removes everything unused in one go. Get in the habit early, because a laptop that has been running Docker for a month can easily be carrying tens of gigabytes of dead layers.

terminal
$ docker container prune # remove all stopped containers
$ docker image prune -a # remove all images not used by a container
$ docker system df # see what Docker is using on disk