G
GuideDevOps
Lesson 12 of 13

Docker Security & Best Practices

Part of the Docker tutorial series.

By default, Docker containers are relatively isolated, but without proper configuration, they can be a security risk. Here are the most important security practices for DevOps.

1. Run as a Non-Root User

By default, Docker containers run as the root user. This is dangerous because if a container is compromised, the attacker has root privileges inside the container.

The Correct Way

Action:

# 1. Create a user
RUN groupadd -r appuser && useradd -r -g appuser appuser
 
# 2. Switch to that user
USER appuser
 
# 3. Now run the application
CMD ["python", "app.py"]

Result: The application now runs with limited permissions.


2. Scan for Vulnerabilities

Modern Docker tools have built-in vulnerability scanning.

Using Docker Scout or Trivy

Action:

docker scout quickview python:3.9

Result:

✓ Image stored locally
✓ Indexed 412 packages
 
  Target                  │  python:3.9  │    0C     0H     8M    21L  

(C=Critical, H=High, M=Medium, L=Low vulnerabilities)


3. Read-Only Root Filesystem

Prevent attackers from modifying your application's files by making the container's root filesystem read-only.

Read-Only Mode

Action:

docker run --read-only nginx

Result: The container starts, but any attempt to write to its disk (except to specifically mounted volumes) will fail.


4. Secret Management

NEVER put secrets (API keys, DB passwords) in a Dockerfile or as environment variables in plain text.

Best Practice: Use Docker Secrets (in Swarm) or environment variable files (.env) that are NOT committed to version control.


Summary: Security Checklist

  1. Always use a non-root user (USER).
  2. Scan your images for vulnerabilities (docker scout).
  3. Minimize your base image (alpine, distroless).
  4. Limit resources (--memory, --cpus).
  5. Never hardcode secrets.