🎓 A1Learner
🔍
0 of 50 lessons completed

Docker Security Basics

Docker security basics are three habits: do not run as root inside the image, scan images before use, and never bake secrets into layers.

Run as a named user

A USER line switches the image away from root.

FROM python:3.12-slim
RUN useradd -m app
USER app

Pass a secret at run time

An environment variable carries the secret at run time, not build time.

docker run -e API_KEY=secret123 myapp:1.0

Example

docker build -t g4-secure:1.0 -f Dockerfile.secure . >/dev/null
docker run --rm g4-secure:1.0

Key points

  • Run as a named user inside the image, with a USER line in the Dockerfile.
  • Scan images for known flaws before running them in production.
  • Never bake a secret into a layer. A layer stays in the image history forever.
  • Pass secrets at run time, with environment variables or a secrets store.
  • Use official images from Docker Hub, and check the image name before pulling.

In this example, Docker builds an image that creates a user called app and switches to it, then runs the image. Python prints its version as app, not as root. The version line proves the image still runs after the switch.

Note

The docker group is nearly root, so only trusted users belong in it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why must a secret never be baked into an image layer?