Writing Your First Dockerfile
A friendly walkthrough of the Dockerfile syntax — write a working image for a small web app in 10 minutes.
Series
Docker from Scratch
Writing Your First Dockerfile
A Dockerfile is a text file that lists the steps to build your container image. Think of it as a cooking recipe.
A working example (Node.js)
# 1. Start from a base image that already has Node
FROM node:20-alpine
# 2. Choose a folder inside the container
WORKDIR /app
# 3. Copy dependency files first (for caching)
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
# 4. Copy the rest of the source
COPY . .
# 5. Tell users which port the app listens on
EXPOSE 3000
# 6. Command that runs when the container starts
CMD ["node", "server.js"]
Line by line
- FROM — pick a starting image.
-alpineversions are smaller. - WORKDIR — like
cd /appfor the container. - COPY — bring files from your machine into the image.
- RUN — execute a command during the build (installs packages).
- CMD — the command that runs every time a container starts.
Build and run it
docker build -t my-app .
docker run -p 3000:3000 my-app
Beginner tips
- Order matters — put commands that change less at the top so Docker can cache them.
.dockerignore— like.gitignore; keepnode_modulesand.gitout of the build context.- Small images matter — a 100MB image starts faster than a 900MB one. Use
-alpineor-slimbase images.
Real-world analogy
A Dockerfile is a recipe card. docker build follows the recipe and makes a cake (the image). docker run serves a slice (the container). If you change the recipe, you bake a new cake — you never edit an already-baked cake.
Keep reading
You may also like
devops
Git Handbook – Quick Reference
A complete collection of Git commands and notes, covering setup, commits, branching, merging, conflicts, and advanced workflows. This handbook is designed as a simple, step‑by‑step guide for beginners and professionals to quickly learn and apply Git in real projects.
devops
Kubernetes Explained for Absolute Beginners
The clearest possible introduction to Kubernetes — what it is, why it exists, and the seven words you need to know.
devops
The Perfect Dockerfile for Node.js Apps
Multi-stage builds, layer caching and a 90% smaller image size.
Discussion (0)
No comments yet. Be the first to weigh in.