Docker Images and Containers
You have heard "just run the Docker image". To do that confidently you need two words straight, image and container, and a handful of commands that start, inspect and clean up.
The rule
An image is a read-only template; a container is one running copy of it.
An image is a packaged, read-only filesystem plus metadata saying what to run. It is identified by a name and a tag, such as python:3.12-slim or notes-api:1.0. Images come from a registry such as Docker Hub or your company's private one.
A container is created from an image and adds a thin writable layer on top. You can start many containers from one image, just as you can run many processes from one program.
docker pull nginx:1.27 # download an image
docker run -d --name notes -p 8080:8000 notes-api:1.0 # start a container in the background
docker ps # running containers (-a includes stopped)
docker logs -f notes # follow its output
docker exec -it notes sh # open a shell inside it
docker stop notes && docker rm notes # stop, then removeRead -p 8080:8000 as host:container: traffic to port 8080 on the host goes to port 8000 inside the container, where notes-api listens.
The writable layer disappears with docker rm. Anything that must survive, such as a database's files or uploaded notes, belongs in a volume mounted into the container:
docker run -d --name notes -p 8080:8000 -v notes-data:/data notes-api:1.0Settings go in as environment variables with -e, so the same image runs in testing and production with different configuration.
The shortcut
Treat containers as disposable and images as the thing you keep. Need a change? Build a new image, then replace the container. Never fix a running container by hand: the fix vanishes the next time it is recreated.
Get the new image
docker pull registry.example.com/notes-api:1.1.
The trap: storing data in the container's own filesystem. It works until the first docker rm, and then the data is gone.
Drills
Answer fast — trust the rule.
What is the relationship between an image and a container?
In docker run -p 8080:8000 notes-api:1.0, which port does the app listen on inside the container?
You run docker rm on a container that saved uploads to its own filesystem. What happens to the uploads?
Which command opens an interactive shell inside the running container named notes?
Remember
- An image is a read-only template; a container is one running copy of it.
- Shortcut: images are kept, containers are disposable. Change the image, replace the container.
- Trap: keeping data inside the container instead of a volume;
-pis host:container.
