C.W.K.
Stream
Lesson 01 of 03 · published

Non-root + Resource Limits — The Two Defaults

~14 min · security, production

Level 0Container Curious
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Run as non-root, always

By default, processes inside a container run as root. If your app has a vulnerability and an attacker breaks out of the namespace, they're root on the host. Creating a system user and switching to it before CMD costs two lines and removes that escalation path.

Resource limits prevent noisy neighbors

--memory and --cpus tell the kernel how much your container is allowed. Without them, a buggy container can OOM the host, taking everything else down with it.

Code

Dockerfile non-root·dockerfile
FROM python:3.12-slim
WORKDIR /app

# Install everything as root
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# Create system user/group, then switch BEFORE CMD
RUN addgroup --system app && adduser --system --group app
USER app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Runtime resource limits·bash
# Cap memory at 512MB, swap at 1GB total
docker run -d --memory=512m --memory-swap=1g myapp

# Cap CPU at 1.5 cores
docker run -d --cpus=1.5 myapp

# Watch live
docker stats --format 'table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}'

External links

Exercise

Take a Dockerfile that runs as root. Add the system user creation + USER app line. Build, run, and verify with docker exec ... whoami that the process is no longer root. Then run with --memory=128m and watch what happens if your app exceeds it.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.