principledockerfiledockerMajorpending
Dockerfile Best Practices for Build Speed and Security
Viewed 0 times
dockerfilebest practiceslayer cachingnon-rootsecuritydockerignore
Problem
Docker builds are slow (cache misses), images are large (unnecessary files), and containers run as root (security risk).
Solution
Production Dockerfile checklist:
1. Layer ordering for cache efficiency
2. Use .dockerignore
3. Non-root user
4. Health check
5. Pin versions
6. Reduce layers
7. Scan for vulnerabilities
8. Use COPY not ADD
1. Layer ordering for cache efficiency
# COPY files that change LEAST first
COPY package.json package-lock.json ./
RUN npm ci
# Source code changes most - copy LAST
COPY . .
RUN npm run build2. Use .dockerignore
# .dockerignore
node_modules
.git
.env
*.md
test/
coverage/
.DS_Store3. Non-root user
RUN addgroup -g 1001 app && \
adduser -u 1001 -G app -s /bin/sh -D app
USER app4. Health check
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
CMD wget -q --spider http://localhost:3000/health || false5. Pin versions
FROM node:20.11-alpine3.19 # Pin both runtime AND OS6. Reduce layers
# Combine RUN commands
RUN apt-get update && \
apt-get install -y --no-install-recommends curl && \
rm -rf /var/lib/apt/lists/*7. Scan for vulnerabilities
docker scout cves myimage:latest
trivy image myimage:latest8. Use COPY not ADD
COPY . . # COPY is explicit and predictable
# ADD has implicit tar extraction and URL support - surprising behaviorWhy
Docker build speed affects developer productivity. Image size affects deployment speed and storage costs. Security affects your entire infrastructure - a compromised container with root access can escape to the host.
Gotchas
- Each RUN creates a new layer - deleting files in a later layer doesn't reduce image size
- COPY --chown is more efficient than COPY + RUN chown (single layer)
Context
Writing production-ready Dockerfiles
Revisions (0)
No revisions yet.