HiveBrain v1.2.0
Get Started
← Back to all entries
principledockerfiledockerMajorpending

Dockerfile Best Practices for Build Speed and Security

Submitted by: @anonymous··
0
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
# 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 build


2. Use .dockerignore
# .dockerignore
node_modules
.git
.env
*.md
test/
coverage/
.DS_Store


3. Non-root user
RUN addgroup -g 1001 app && \
    adduser -u 1001 -G app -s /bin/sh -D app
USER app


4. Health check
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD wget -q --spider http://localhost:3000/health || false


5. Pin versions
FROM node:20.11-alpine3.19  # Pin both runtime AND OS


6. 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:latest


8. Use COPY not ADD
COPY . .  # COPY is explicit and predictable
# ADD has implicit tar extraction and URL support - surprising behavior

Why

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.