🎓 A1Learner
🔍
0 of 51 lessons completed

Kubernetes: Security Basics

Kubernetes security basics are a few small habits that make a cluster hard to break into. Run as non-root, scan your images, and keep secrets out of image layers.

Run as a non-root user

A container that runs as root can do anything on the host if it breaks out. A non-root user with no privilege escalation is a much smaller target.

securityContext:
  runAsNonRoot: true
  runAsUser: 1000
  allowPrivilegeEscalation: false

Scan the image before you ship it

A scan checks the image layers for known flaws. A clean scan is a good sign, not a guarantee. Scan again when the base image changes.

docker scan web:1.0

Set a namespace baseline

Pod security standards set a floor for a namespace. The baseline level blocks the worst habits, like running as root. A stricter level can follow later.

kubectl label namespace default pod-security.kubernetes.io/enforce=baseline

Example

kubectl apply -f web-secure.yaml
kubectl get pods -l app=web

Key points

  • Run containers as a non-root user, so a break-in has less power
  • Scan images for known flaws before you deploy them
  • An image is built in layers, one step per layer, and every layer keeps its history.
  • Never bake a secret into an image layer, because layers keep their history
  • Use a Secret for passwords and keys, not an env var in a Dockerfile
  • Use pod security standards to set a baseline for every namespace

In this example, the first command creates a Deployment that runs as a non-root user from the file. The second command reads the pods back. Both pods are running, which proves the app works without root.

Note

security is a habit, not a single setting, so check each new image and each new pod

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Why should a container run as a non-root user?