appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Container security

Lesson 1 of 412 minAdvanced

Drop privileges, restrict the filesystem and never run as root.

A container is a process isolated by the kernel with namespaces and cgroups. It shares the host kernel, so it is not as strongly isolated as a virtual machine. Reduce what a compromised container could do.

Do not run as root

FROM node:22-slim
RUN useradd --system --uid 10001 app
USER 10001
COPY --chown=10001 . /app

Restrict at run time

docker run -d \
  --read-only --tmpfs /tmp \
  --cap-drop ALL \
  --security-opt no-new-privileges \
  --pids-limit 200 \
  --memory 512m --cpus 1 \
  myapp:1.4.2
  • --read-only makes the root filesystem read-only. Give writable paths explicitly with --tmpfs or volumes.
  • --cap-drop ALL removes Linux capabilities. Add back only what is needed, for example --cap-add NET_BIND_SERVICE.
  • no-new-privileges blocks privilege escalation through setuid binaries.
  • Resource limits stop one container from starving the host.

CarefulAvoid --privileged and mounting /var/run/docker.sock into a container. Either gives the container (and anyone who breaks into it) control over the host.

Secrets

Do not put passwords in the image or in ENV lines of the Dockerfile: they are visible in docker inspect and in the layer history. Pass them at run time through secrets files (/run/secrets/...) or your orchestrator's secret store.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Why is a container less isolated than a virtual machine?
2. What does --cap-drop ALL do?
3. Why is mounting /var/run/docker.sock into a container dangerous?

Key terms