Writing a Dockerfile
A Dockerfile is a text document containing a sequence of instructions used by the Docker Engine to build a custom container image automatically.
1. Core Dockerfile Directives Reference
| Directive | Description | Syntax Example |
|---|---|---|
FROM | Sets base parent image | FROM node:18-alpine |
WORKDIR | Sets current working directory inside container | WORKDIR /app |
COPY | Copies files from host to container filesystem | COPY package*.json ./ |
RUN | Executes build-time terminal commands (Layered) | RUN npm install --only=production |
EXPOSE | Documents network port exposed by container | EXPOSE 3000 |
ENV | Sets environment variables | ENV NODE_ENV=production |
CMD | Default command executed when container starts | CMD ["npm", "start"] |
2. Production Node.js Web App Dockerfile
Official Production Dockerfile Template:
# 1. Base Image FROM node:18-alpine # 2. Set Working Directory WORKDIR /app # 3. Copy Package Definitions First (Optimizes Layer Caching!) COPY package.json package-lock.json ./ # 4. Install Production Dependencies RUN npm ci --only=production # 5. Copy Application Source Code COPY . . # 6. Expose App Port EXPOSE 3000 # 7. Environment Setup ENV NODE_ENV=production # 8. Start Command (Exec Form) CMD ["node", "server.js"]
3. `CMD` vs `ENTRYPOINT`
`CMD` (Overridable Default):
Specifies default arguments that can easily be overridden at runtime via docker run my-image custom-command.
`ENTRYPOINT` (Fixed Executable):
Configures the container to behave like a standalone binary CLI tool. Additional CLI arguments append to ENTRYPOINT.
Next Up
Learn how to build images with `docker build`, optimize with `.dockerignore`, and publish to Docker Hub.
Next Lesson: Building & Publishing Images →