Learn Docker · 10/12

Docker Security Fundamentals

8 min read

Course: Docker

Topic: Docker Security Fundamentals 🛡️

Security in Docker is often treated like flossing—everyone knows they should do it, but many only start after something painful happens. By default, Docker focuses on making it incredibly easy to get your applications running. However, "easy to run" usually means "easy to exploit."

In this guide, we are going to lock down our containers. We will look at industry-standard practices to ensure your applications remain fortress-like without complicating your daily workflow.


1. Principle of Least Privilege: Running as Non-Root Users 👤

Definition: The Principle of Least Privilege is a security concept requiring that a user, program, or process be granted only the minimum access permissions necessary to perform its function.

Problem: By default, processes inside a Docker container run as the root user (User ID 0). If an attacker finds a vulnerability in your application (like a remote code execution flaw), they execute their malicious code as root inside the container. If there is a misconfiguration or a flaw in the container runtime itself, they might "break out" of the container and gain root access to your actual host server.

The "Hotel Keycard" Explanation:
Imagine you manage a large hotel (the host server). You have many guests (the containers). By default, Docker gives every guest a master keycard that can theoretically open the vault, the manager's office, and the electrical room. If a guest turns out to be a thief, they have full access. Applying the principle of least privilege means giving the guest a keycard that only opens their specific room and the ice machine. If they turn out to be a thief, they can only steal their own towels.

Solution: Create a dedicated, unprivileged user inside your Dockerfile and switch to that user before running your application.

Industry Standard Practice:
In the industry, we use the RUN command to create a group and a user, and then use the USER directive to switch contexts. Many official images (like Node.js) already have a non-root user built-in, but for base images like Alpine or Ubuntu, you must create one.

Practical Example:
Here is how you secure a standard Node.js application running on Alpine Linux.

dockerfile
# 1. Start with an Alpine-based Node image
FROM node:20-alpine

# 2. Set the working directory
WORKDIR /app

# 3. Copy application files and set ownership to the pre-existing 'node' user
# The --chown flag prevents the files from being owned by root
COPY --chown=node:node package*.json ./
RUN npm install

COPY --chown=node:node . .

# 4. Switch from the default 'root' user to the 'node' user
USER node

# 5. Run the application
CMD ["node", "server.js"]

If you are using a barebones Ubuntu image where a default user does not exist, you create one like this:

dockerfile
FROM ubuntu:24.04

# Create a group and a user named 'appuser'
RUN groupadd -r appuser && useradd -r -g appuser appuser

WORKDIR /app
COPY --chown=appuser:appuser . .

USER appuser
CMD ["./my-compiled-app"]

2. Image Scanning: Identifying and Patching Vulnerabilities 🔍

Definition: Image scanning is the process of analyzing the contents of a Docker image to identify known security vulnerabilities (CVEs - Common Vulnerabilities and Exposures) in its operating system packages and application dependencies.

Problem: When you start a Dockerfile with FROM python:3.11, you are not just getting Python. You are getting a miniaturized Linux distribution with hundreds of installed packages (like curl, openssl, or bash). Over time, security researchers find critical bugs in these packages. If you build and deploy this image without checking, you are knowingly deploying vulnerable software.

The "Car Assembly" Explanation:
Imagine you are building a custom car using parts from various suppliers around the world. You assume all the parts are perfectly safe. However, the manufacturer of the brake pads just issued a global recall because the brakes fail at high speeds. If you do not actively check the global recall list (the vulnerability database) before selling your car, your customer is going to have a very bad time. Image scanning is your automated factory inspector checking every part against the recall list.

Solution: Use an image scanning tool to check your images before pushing them to production. Docker Scout is the modern, built-in standard for Docker (replacing Docker Scan/Snyk). Trivy by Aqua Security is another massive open-source industry standard used in CI/CD pipelines.

Industry Standard Practice:
You don't need to fix every single "Low" vulnerability—that is an endless game of whack-a-mole. Industry focus is strictly on fixing Critical and High vulnerabilities, primarily by updating the base image to a newer, patched version.

Practical Example (Using Docker Scout CLI):

  1. Analyze a local image for vulnerabilities:
bash
docker scout cves my-app:latest
  1. Filter for things that actually keep security engineers awake at night (Critical/High severity):
bash
docker scout cves my-app:latest --only-severity critical,high
  1. Ask Docker Scout for the solution (it will recommend a better base image):
bash
docker scout recommendations my-app:latest

Output Example:

Recommended: upgrade base image from node:20.5 to node:20.11-alpine (fixes 15 vulnerabilities).


3. Resource Limits: Restricting CPU and Memory Usage 🚧

Definition: Resource limiting is the enforcement of strict boundaries on the amount of RAM and CPU cycles a specific container is allowed to consume from the host machine.

Problem: By default, a Docker container has no resource constraints. It can use as much of the host machine's memory and CPU as it wants. If an application inside a container has a memory leak, or gets trapped in an infinite loop, it will consume 100% of the host's resources. This crashes the host server and takes down every other container running alongside it. This is famously known in the industry as the "Noisy Neighbor" problem.

The "Shared Credit Card" Explanation:
Imagine you give a shared company credit card to five employees for a business trip. There is no spending limit on the card. Four employees buy modest meals, but the fifth employee decides to buy a solid gold Rolex. The credit card is instantly maxed out and declined. Now, the other four employees cannot even buy a bottle of water. To prevent this, you must issue cards with strict individual spending limits.

Solution: Apply --memory and --cpus flags to your containers. If a container tries to exceed its memory limit, Docker will politely (or abruptly) kill it with an OOMKilled (Out Of Memory) error, saving the host machine.

Industry Standard Practice:
While you can set this via the Docker CLI, the industry standard is to define these limits declaratively inside a docker-compose.yml file or Kubernetes manifests.

Practical Example:

Via Docker CLI:

bash
# Limits the container to 512 Megabytes of RAM and 1.5 CPU cores
docker run -d --name myapp --memory="512m" --cpus="1.5" my-app:latest

Via Docker Compose (Industry preferred):

yaml
services:
  web:
    image: my-app:latest
    deploy:
      resources:
        limits:
          cpus: '0.50'      # Max half of a CPU core
          memory: 512M      # Max 512 MB of RAM
        reservations:
          cpus: '0.10'      # Guarantee at least 10% of a core
          memory: 128M      # Guarantee at least 128 MB of RAM

4. Keeping Secrets Safe in Docker Environments 🤫

Definition: Secrets management in Docker involves securely passing sensitive data (like database passwords, API keys, and private SSH keys) to a container without exposing that data in the application's source code or the container's image layers.

Problem: Applications need passwords to connect to databases. If you write ENV DB_PASSWORD=supersecret in your Dockerfile, or copy a .env file into the image, that secret is permanently baked into the image's history. Anyone who downloads your image can run docker inspect or docker history and read your passwords in plain text.

The "ATM Envelope" Explanation:
Imagine you need to deposit cash at an ATM, and the machine requires you to put the cash in an envelope. If you write your bank PIN directly on the outside of the envelope, the bank teller will be able to process the transaction, but every single person who handled that envelope during transit also saw your PIN. You need a secure, invisible way to hand the PIN directly to the teller without writing it down anywhere.

Solution: Handle secrets differently based on when you need them.

  1. Build-time secrets: Use Docker BuildKit's secret mounts.
  2. Runtime secrets: Use environment variables passed at runtime, or Docker Swarm/Compose secrets.

Industry Standard Practice:
Never, ever use ARG or ENV in a Dockerfile for sensitive data. Use RUN --mount=type=secret for things needed during the build (like an NPM token to download private packages). Use a .env file injected via docker run --env-file for things needed while the app is running.

Practical Example (Build-Time Secret):
Let's say we need an API token just to download a private package during the build, but we don't want the token saved in the final image.

  1. Create a file named token.txt on your local machine containing your secret.
  2. Write your Dockerfile using the --mount=type=secret syntax:
dockerfile
# syntax=docker/dockerfile:1
FROM ubuntu:24.04

RUN apt-get update && apt-get install -y curl

# The secret is temporarily mounted to /run/secrets/api_token
# Once this RUN command finishes, the secret vanishes completely!
RUN --mount=type=secret,id=api_token \
    TOKEN=$(cat /run/secrets/api_token) && \
    curl -H "Authorization: Bearer $TOKEN" https://api.mycompany.com/secure-data > data.json
  1. Build the image, passing the secret securely from your host terminal:
bash
docker build --secret id=api_token,src=./token.txt -t my-secure-app .

(Note: BuildKit is the default builder in Docker 23.0+. For older versions, prefix the command with DOCKER_BUILDKIT=1).

Practical Example (Runtime Secret):
For database passwords needed when the container is actually running:

bash
# Provide secrets via an ignored .env file at runtime
docker run -d --name myapp --env-file .env my-app:latest

Summary

Docker security doesn't require paranoia; it just requires good habits. By running processes as non-root users, keeping an eye out for CVEs with Docker Scout, putting a hard cap on resource hoarding, and keeping your secrets out of your image layers, you mitigate 95% of the most common container exploits in the industry today.


📚 References & Extra Reading

Challenge

You have been tasked with securing a Dockerfile for a critical Python application. The current file works, but it contains several common security flaws that violate company policy. Your goal is to rewrite the Dockerfile from the editor to incorporate modern security best practices discussed in the summary.

Your revised Dockerfile must:

  1. Update the Base Image: An image scan revealed that the latest tag is insecure. Change the base image from python:latest to a more secure and specific version, python:3.11-slim.
  2. Implement Principle of Least Privilege: Create a dedicated group and user named appuser with a UID and GID of 1001. Ensure the application directory is owned by this new user and that the container's main process runs as this non-root user.
  3. Secure Build-Time Secrets: The application requires a secret token to install private packages from requirements.txt. Modify the pip install command to use Docker BuildKit's secret mounting (--mount=type=secret). Assume the secret has an ID of pypi_token and will be mounted at the default path. You must write the RUN instruction to use this secret securely without leaking it into an image layer. Do NOT use ARG or ENV for the secret token.

Expected result

Your final Dockerfile should correctly implement all the required security measures. A correct solution will contain the following key elements:

  • The FROM instruction specifies python:3.11-slim.
  • RUN instructions are used to add a group and a user, both named appuser, with a specific UID/GID of 1001.
  • Files copied into the /app directory have their ownership changed to appuser:appuser using chown.
  • The pip install command is executed within a RUN instruction that utilizes --mount=type=secret,id=pypi_token to securely access the secret token. The install command itself should reference the mounted secret file to authenticate.
  • The USER instruction is used to switch the context to appuser before the final CMD instruction is declared.
  • The insecure ARG PYPI_TOKEN instruction has been removed entirely.
dockerfile

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.