Beginner LevelDocker & Deployment
Why should you include the USER instruction in production Dockerfiles?
❓ Interview Prompt: Explain container root user security risks, the USER instruction, UID/GID assignment, and least-privilege container execution.
By default, Docker containers run all processes as root (UID 0). While this root user is confined to the container's namespace, it still presents serious security risks:
Security Risks of Running as Root:
1
Container Breakout: Kernel vulnerabilities (e.g., runc CVEs) can allow a root container process to escape and gain real host root access.
2
Volume Mount Escalation: Files written by root in a container are owned by root on the host volume — modifiable only by host root.
3
Principle of Least Privilege Violation: Root inside a container has all Linux capabilities by default.
The USER Instruction:
Creates or switches to a non-root user for all subsequent RUN, CMD, and ENTRYPOINT instructions.
Best Practice:
Create a dedicated system user with a fixed UID (1001+) and no login shell. Never use UID 0.
Code Implementation Example
dockerfile
FROM node:20-alpine
WORKDIR /app
# Install dependencies as root (required for npm ci)
COPY package*.json ./
RUN npm ci --only=production
COPY . .
# Create non-root system user and group
RUN addgroup --system --gid 1001 nodejs && \
adduser --system --uid 1001 --ingroup nodejs --no-create-home appuser
# Set ownership of app files
RUN chown -R appuser:nodejs /app
# Switch to non-root user for runtime
USER appuser
EXPOSE 3000
# Process now runs as UID 1001, not root
CMD ["node", "server.js"]💡Create a system user with fixed UID 1001, set file ownership, then switch with USER before CMD.
🎯 Interview Key Takeaway
Always switch to a non-root USER before CMD/ENTRYPOINT in production. Root containers can escalate privileges via kernel exploits — least-privilege is non-negotiable.
#Docker#Security#USER#Non-Root#Least Privilege#Beginner
Back to all Docker & Deployment Questions→