Images & containers
The whole lifecycle in five verbs: pull, run, ps, stop, rm. Know which object each one touches.
key idea / Docker itselfcontainer / good pathhost / watch outproblem / blockedneutral
The container lifecycle
A container moves through a few states, and a different command moves it between each.
Tags are labels, not versions
Without a tag, Docker assumes latest, which can change under you.
Removing things
Containers and images are separate objects with separate remove commands.
| Command | Removes | Fails when |
|---|---|---|
docker rm | a container | it is still running (use stop first) |
docker rmi | an image | any container, even stopped, still uses it |
docker ps -a | (lists) | shows stopped containers that still exist |
Try it yourself
-
Step 1 · Pull a pinned tag
$ docker pull nginx:1.27 1.27: Pulling from library/nginx Status: Downloaded newer image for nginx:1.27 -
Step 2 · The image is local
$ docker images nginx REPOSITORY TAG IMAGE ID CREATED SIZE nginx 1.27 1b8b7c4a0c1a 2 weeks ago 192MB -
Step 3 · Run creates and starts a container
-dreturns the terminal immediately.--name webis the name you will use next.$ docker run -d --name web nginx:1.27 a91c0e2f4b10… $ docker ps CONTAINER ID IMAGE STATUS NAMES a91c0e2f4b10 nginx:1.27 Up 3 seconds web -
Step 4 · Stop hides it from docker ps
$ docker stop web web $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ docker ps -a CONTAINER ID IMAGE STATUS NAMES a91c0e2f4b10 nginx:1.27 Exited (0) 2 seconds ago web -
Step 5 · rm deletes the container, rmi deletes the image
The second command fails while
webstill exists. Remove the container, then the image.$ docker rmi nginx:1.27 Error: conflict: unable to delete nginx:1.27 (must be forced) - container a91c0e2f4b10 is using its referenced image $ docker rm web web $ docker rmi nginx:1.27 Untagged: nginx:1.27 Deleted: sha256:1b8b7c4a0c1a…
Recap
pulldownloads an image,runcreates and starts a container from it.docker psshows running containers;-aadds the stopped ones.rmdeletes a container;rmideletes an image.- Always pin a tag.
latestis a moving target.
Quick check
Why does
docker rmi nginx:1.27 fail even though docker ps is empty?Show answer
A stopped container still references the image. docker ps -a lists it; remove it with docker rm, then the image.