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

DirectiveDescriptionSyntax Example
FROMSets base parent imageFROM node:18-alpine
WORKDIRSets current working directory inside containerWORKDIR /app
COPYCopies files from host to container filesystemCOPY package*.json ./
RUNExecutes build-time terminal commands (Layered)RUN npm install --only=production
EXPOSEDocuments network port exposed by containerEXPOSE 3000
ENVSets environment variablesENV NODE_ENV=production
CMDDefault command executed when container startsCMD ["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 →