Container security
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 . /appRestrict 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-onlymakes the root filesystem read-only. Give writable paths explicitly with--tmpfsor volumes.--cap-drop ALLremoves Linux capabilities. Add back only what is needed, for example--cap-add NET_BIND_SERVICE.no-new-privilegesblocks 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.