Container Security Practices

Hardening container security protects your host system and cloud cluster against container breakouts and vulnerability exploits.

1. Never Run Containers as Root (`USER node`)

By default, Docker containers run commands as the root superuser inside the container. If an attacker breaches the container application, root privilege makes host escalation easier.

FROM node:18-alpine
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

# Switch away from root to low-privilege 'node' user!
USER node

EXPOSE 3000
CMD ["node", "server.js"]

2. Top Security Checklist

  • Use Minimal Alpine / Distroless Base Images: Reduces OS attack surface by omitting unnecessary tools like `curl`, `wget`, or compilers.
  • Scan Images for Vulnerabilities: Run docker scout cves myimage or Trivy to catch CVE vulnerabilities.
  • Never Hardcode Secrets in Dockerfile: Use environment variables or Docker secrets instead of plain text API keys in `ENV`.
  • Read-Only Root Filesystem: Use --read-only flag to prevent malware from modifying container binaries.

Next Up

Learn Environment Variables & Secrets: passing .env files (--env-file), runtime overrides, and secret management.

Next Lesson: Env Variables & Secrets →