Security mistake

2 snippets in Docker

DKDocker

Running Containers as Root

DK · Common Mistakes
syntax
# Problem:
FROM node:20
CMD ["node", "server.js"]
# Runs as root by default
example
# Fix:
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node . .
RUN npm ci --omit=dev
USER node
CMD ["node", "server.js"]

Note Most base images default to root. This means if an attacker exploits your application, they have root inside the container — and potentially on the host via privilege escalation. Always add a USER instruction before CMD.

Baking Secrets into Images

DK · Common Mistakes
syntax
# NEVER do this:
ENV DATABASE_URL=postgres://user:pass@host/db
COPY .env /app/.env
example
# Bad — secret is in the image layer history:
ENV API_KEY=sk-abc123...

# Fix — pass secrets at runtime:
docker run -e API_KEY=sk-abc123 myapp:1.0
docker run --env-file .env myapp:1.0

# For build-time secrets (e.g., private npm token):
docker build --secret id=npmrc,src=.npmrc .
# In Dockerfile:
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci

Note ENV values and COPYed files are permanently visible via docker history and docker inspect. Even if you delete them in a later layer, they exist in the previous layer. Use --secret mounts for build-time secrets and runtime env vars or secret managers for runtime secrets.