Scenario
A Dockerfile at /home/interview/Dockerfile builds a Python web application tagged as myapp:secure. The container runs as the root user (UID 0) with extensive Linux capabilities, violating the principle of least privilege.
Task
Harden the Dockerfile by creating a non-root user appuser with UID 10001, switching to that user for application execution, ensuring application files have appropriate permissions, rebuilding the image with the tag myapp:secure, and verifying the container runs with reduced privileges while maintaining full functionality.
Example
# Before (running as root)
uid=0(root) gid=0(root) groups=0(root)
# After (running as non-root user)
uid=10001(appuser) gid=10001(appuser) groups=10001(appuser)
Reduced capability set present
Application responds with non-root user confirmation
curl http://localhost:5000/health
Response: {"status":"healthy","uid":10001,"user":"appuser"}
Step 1: Check the current user ID
docker run --rm myapp:secure id
Shows UID 0 (root) by default. Docker containers run as root unless explicitly configured otherwise.
Step 2: Edit the Dockerfile to add non-root user
nano /home/interview/Dockerfile
Examine the file and add non-root user creation. The USER instruction must come after operations requiring root privileges (like apt-get, chown):
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ /app/
# Create non-root user with specific UID/GID
RUN groupadd -r -g 10001 appuser && \
useradd -r -u 10001 -g appuser appuser
# Give ownership to non-root user
RUN chown -R appuser:appuser /app
# Switch to non-root user
USER appuser
EXPOSE 5000
CMD ["python", "main.py"]
Save and exit (Ctrl+O, Enter, Ctrl+X). UID 10001 avoids conflicts with system users (0-999).
Step 3: Build the hardened image
docker build -t myapp:secure .
Rebuilds the image with the non-root user configuration.
Step 4: Verify non-root user
docker run --rm myapp:secure id
Should show UID 10001 (appuser), not 0 (root).
Step 5: Check username
docker run --rm myapp:secure whoami
Should show "appuser", confirming the USER instruction worked.
Step 6: Test application functionality
docker run -d -p 5000:5000 --name myapp-test myapp:secure
Starts the container as non-root user.
Step 7: Verify application responds
curl http://localhost:5000/health
Tests that the application works correctly as non-root.