Lesson 26 / 26

Security Basics

Don't run as root, and keep base images minimal and up to date.

Don't run as root

By default, a container's process runs as root inside it. Create and switch to a non-root user so a container breakout has far less power.

FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm install --production

RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

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

Minimal base images

Fewer installed packages means fewer known vulnerabilities. Prefer alpine or distroless bases, and rebuild regularly to pick up security patches.

Quick check: Why should a container avoid running its process as root?

  • It makes the image build faster
  • It limits the damage if an attacker breaks out of the container
  • Root users can't use volumes
Answer

It limits the damage if an attacker breaks out of the container — Running as a non-root user reduces the privileges available if the container is compromised.