Dockerfile
A Dockerfile is a text file of instructions used to build a Docker image. Each instruction creates a layer; order and caching matter for fast rebuilds.
Essential Instructions
Section titled “Essential Instructions”| Instruction | Purpose |
|---|---|
| FROM | Base image (e.g. FROM alpine:3.19 or FROM node:20-slim). Must be the first non-comment line. |
| RUN | Run a command in the image (e.g. RUN apt-get update && apt-get install -y curl). Chain with && to reduce layers. |
| COPY | Copy files from the build context into the image (e.g. COPY . /app). Prefer over ADD unless you need URL or tar extraction. |
| WORKDIR | Set the working directory for subsequent instructions and for the running container (e.g. WORKDIR /app). |
| ENV | Set environment variables (e.g. ENV NODE_ENV=production). |
| EXPOSE | Document which port the container listens on (e.g. EXPOSE 8080). Does not publish the port; use docker run -p to publish. |
| CMD | Default command when the container starts (e.g. CMD ["node", "server.js"]). Only one CMD; use exec form ["exec", "arg"]. |
| ENTRYPOINT | Fixed executable; CMD becomes arguments. Use for “image as command” (e.g. ENTRYPOINT ["/app/entry.sh"]). |
Example Dockerfile
Section titled “Example Dockerfile”FROM node:20-slimWORKDIR /appCOPY package*.json ./RUN npm ci --omit=devCOPY . .ENV NODE_ENV=productionEXPOSE 8080CMD ["node", "server.js"]Multi-Stage Builds
Section titled “Multi-Stage Builds”Use multiple FROM blocks to build in one stage and run in a smaller one. Build tools stay out of the final image:
# Build stageFROM node:20 AS builderWORKDIR /appCOPY . .RUN npm ci && npm run build
# Production stageFROM node:20-slimWORKDIR /appCOPY --from=builder /app/dist ./distCOPY --from=builder /app/node_modules ./node_modulesCOPY package*.json ./EXPOSE 8080CMD ["node", "dist/server.js"].dockerignore
Section titled “.dockerignore”A .dockerignore file (same syntax as .gitignore) excludes files from the build context. This speeds up builds and avoids copying secrets or node_modules:
node_modules.git.env*.logDockerfile.dockerignoreKey Takeaways
Section titled “Key Takeaways”- Use FROM, RUN, COPY, WORKDIR, ENV, EXPOSE, CMD (and ENTRYPOINT when the image is a single command).
- Prefer multi-stage builds to keep the final image small and free of build tools.
- Use .dockerignore to shrink context and avoid leaking sensitive or unneeded files.