Read and write a Dockerfile
In this task you'll read a Dockerfile and know what each line does.
A container image packages an app with everything it needs to run. A Dockerfile is the recipe: start FROM a base image, COPY files in, RUN commands at build time, set ENV variables and say what to run with CMD or ENTRYPOINT.
Each line makes a layer that's cached, so put things that rarely change (installing packages) before things that change often (your code). Multi-stage builds compile in one image and copy only the result into a small final one.
Example. SS Kaiser's API used to ship a 1.2 GB image with the whole build toolchain. A multi-stage Dockerfile brought it down to 90 MB and removed tools an attacker could have used.
Before you start
You need: Nothing. Time: 15 minutes.
Where to look
- Dockerfile
- FROM
- COPY
- RUN
- CMD
Steps
- Read the example Dockerfile in Commands line by line and say what each does.
- Spot the two-stage pattern: the build stage has the SDK, the final stage only the runtime.
- Notice USER: the final image runs as a non-root user.Kubernetes' restricted standard (lab K8) requires it.
- You'll build it without installing Docker in the next task, with ACR Tasks.
Commands
# A two-stage Dockerfile for a small Node.js app
FROM node:20-alpine AS build
WORKDIR /src
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
COPY --from=build /src/dist ./dist
COPY --from=build /src/node_modules ./node_modules
USER node
EXPOSE 8080
CMD ["node", "dist/server.js"]
Watch out for
- Cost
- Free.
- Security
- Use small, trusted base images from known registries, pin their versions, and don't bake secrets into layers: they stay in the image.
- Common mistakes
- Using latest tags, running as root, and copying the whole folder (including .git and .env) into the image. Add a .dockerignore.
Clean up
Nothing to clean up.
Words to know
- Image
- The packaged app: read-only layers plus settings.
- Container
- A running instance of an image.
- Tag
- A label on an image, such as 1.4.2. Use versions, not latest.
- Multi-stage build
- A Dockerfile with several FROM lines; only the last stage ends up in the image.
Tick off each step and track your progress in the guide.
Open this task in DevOps, Hands On