Lab 03 - Docker images and Dockerfile

Lab 03 - Docker images and Dockerfile

Goal: understand layers by watching the build cache work. Cheat sheet: Docker

# 1 - pull and inspect
sudo docker pull nginx:1.27
sudo docker images
sudo docker history nginx:1.27       # one line per layer, with sizes

history is the image’s build recipe read backwards. Most layers are 0 B - metadata only. The big one is the base filesystem.

# 2 - layer sharing
sudo docker pull nginx:1.27-alpine
sudo docker images | grep nginx

Compare the sizes. Alpine images are small because the base is small, not because nginx is different.

Build your own

# 3 - a build context
mkdir -p ~/myweb && cd ~/myweb
echo '<h1>Hello from support01</h1>' > index.html

cat > Dockerfile <<'DOCKERFILE'
FROM nginx:1.27-alpine
LABEL maintainer="student@k8s.lab"
COPY index.html /usr/share/nginx/html/index.html
EXPOSE 80
DOCKERFILE

Everything in the current directory is sent to the build daemon as the build context. Keep it small - this is what .dockerignore is for.

# 4 - build and run
sudo docker build -t myweb:1.0 .
sudo docker images | grep myweb
sudo docker run -d --name myweb -p 8081:80 myweb:1.0
curl -s localhost:8081

Watch the build output: each instruction is a step, and each step produces a layer.

# 5 - change one line, rebuild, watch the cache
echo '<h1>Version 1.1</h1>' > index.html
sudo docker build -t myweb:1.1 .     # "CACHED" on FROM/LABEL, rebuild from COPY
sudo docker history myweb:1.1 | head -5

The cache is invalidated at the first changed instruction and everything below it is rebuilt. That is why the rule is: least-changing instructions first, COPY of your application last.

# 6 - tags are labels on an image ID
sudo docker tag myweb:1.1 myweb:latest
sudo docker images | grep myweb      # same IMAGE ID, three names

Two tags pointing at one ID is why :latest is dangerous - it says nothing about which build you are running.

Clean up

# 7 -
sudo docker rm -f myweb
sudo docker rmi myweb:1.0 myweb:1.1 myweb:latest