What You'll Learn
Beginner
- What a Docker image is (and how it differs from a container)
- How layers work and why they save disk space
- The difference between read-only image layers and the writable container layer
Docker image layers — read-only stack with a writable top layer per container
Image vs Container
| Image | Container |
|---|---|
| Read-only template | Running instance of an image |
| Stored on disk, doesn't change | Created when you docker run |
| Can be shared, pushed, pulled | Has a writable layer on top |
| Like a class in OOP | Like an object (instance) |
How Layers Work
Each instruction in a Dockerfile creates one layer:
Dockerfiledockerfile
FROM ubuntu:22.04 # Layer 1: base image (77 MB)
RUN apt-get install curl # Layer 2: adds curl (8 MB)
COPY app /app # Layer 3: adds your code (12 MB)
CMD ["./app/run"] # No new layer — metadata onlyWhen you run docker run myapp, Docker stacks these read-only layers and adds a thin writable layer on top. Any changes the container makes go to this writable layer — the image is never modified.
Why Layers Matter
Three big benefits
- Sharing: Two containers from the same image share all layers — no duplication.
- Caching: If a layer hasn't changed, Docker reuses it during builds — faster builds.
- Efficiency: Only changed layers are pushed/pulled — not the whole image.
Common Docker Image Commands
Terminalbash
docker images # List local images
docker pull nginx # Download an image
docker rmi nginx # Remove an image
docker image prune # Remove unused images
docker image inspect nginx # View image details
docker tag nginx myrepo/nginx:v1 # Tag an imageImage Naming Convention
Image name formatbash
[registry/]repository[:tag]
# Examples:
nginx # Docker Hub, official, latest
ubuntu:22.04 # Docker Hub, official, version 22.04
myuser/myapp:v1.0 # Docker Hub, user repo, version v1.0
ghcr.io/org/repo:latest # GitHub Container RegistryAlways pin versions
Don't use latest in production. It's a moving target — your image changes without warning. Pin to a specific version: nginx:1.25.3 instead of nginx:latest.Practical Exercise
Run
docker pull nginx:alpineRun
docker images — see the image and its sizeRun
docker history nginx:alpine — see each layer and its sizeRun
docker run -d --name web nginx:alpineRun
docker exec web touch /tmp/test — writes to the container's writable layerRun
docker stop web && docker rm web — the writable layer is deletedKey Takeaways
- An image is a read-only template. A container is a running instance with a writable layer on top.
- Each Dockerfile instruction creates one layer.
- Layers are shared across containers from the same image — saves disk and download time.
- Layer caching speeds up builds — unchanged layers are reused.
- Always pin image versions (
nginx:1.25.3), avoidlatest> in production.
Comments
Comments
Post a Comment