The Dockerfile
~290 words ยท 2 min read
The Dockerfile
A Dockerfile is a recipe that tells Docker how to build an image. Each instruction adds a layer โ a diff on top of the previous one.
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
CMD ["node", "server.js"]
Common instructions
FROMโ the base image to start from.RUNโ run a shell command at build time (e.g. install deps).COPYโ copy files from your machine into the image.WORKDIRโ set the working directory for later instructions.ENVโ set an environment variable.
CMD vs ENTRYPOINT
Both define what runs when the container starts, but they differ in flexibility:
- CMD โ the default command; easily overridden.
docker run myimage shreplaces the CMD withsh. - ENTRYPOINT โ the fixed executable; arguments are appended. Great for tools that always run the same binary.
Rule of thumb: use CMD for general-purpose images where users pass their own command. Use ENTRYPOINT when the image IS a specific tool.
Layers and caching
Each instruction creates a layer, and Docker caches each one. Rebuilds skip unchanged layers โ so order matters. Copy files that change rarely (like package.json) before files that change often (your source):
# Fast rebuilds โ deps only reinstall when package.json changes
COPY package*.json ./
RUN npm install
COPY . . # source changes don't bust the install layer
.dockerignore
Like .gitignore, it excludes files from the build context (node_modules, .git, .env) โ speeding up builds and keeping secrets out of images.