Cloud Intermediate
Dockerfile Best Practices¶
DockerDockerfileOptimization 3 min read
Dockerfile optimization for smaller images, faster builds and security.
Multi-stage build¶
# Build stage
FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
Best Practices¶
- Use alpine base images
- Separate COPY package.json from COPY . (layer caching)
- Add a .dockerignore
- Run as non-root user
- Use specific tags, not :latest
- Minimize the number of layers
.dockerignore¶
node_modules
.git
.env
*.md
Dockerfile
docker-compose.yml
Summary¶
A proper Dockerfile = small image, fast build, secure runtime. Multi-stage builds are the foundation.
Need Help with Implementation?¶
Our team has experience designing and implementing modern architectures. We’re happy to help.