Docker Security Best Practices
Containers isolate processes, but a careless image or run command can undo most of that protection. These practices close the common gaps.
1. Don't run as root
RUN addgroup -S app && adduser -S app -G app
USER app
If an attacker exploits your app, they get the app user's permissions, not root inside the container.
2. Use minimal, trusted base images
- Official or verified publisher images only.
- Slim, Alpine or distroless variants: fewer packages, fewer vulnerabilities.
- Pin versions and rebuild regularly to pick up security patches.
3. Scan images
docker scout cves my-api:latest # Docker's built-in scanner
trivy image my-api:latest # popular open-source scanner
Run scans in CI and fail the build on critical vulnerabilities that have a fix available.
4. Keep secrets out of images
- Never
COPY .envor useENV API_KEY=...; anyone with the image can read it. - Use BuildKit secret mounts for build-time secrets.
- Inject runtime secrets via environment variables or files from your orchestrator's secret store.
5. Restrict the running container
docker run -d \
--read-only --tmpfs /tmp \
--cap-drop ALL \
--security-opt no-new-privileges \
--memory 512m --cpus 1 \
my-api:latest
--read-only: the app can't modify its own files.--cap-drop ALL: remove Linux capabilities the app doesn't need.- Resource limits stop one container from starving the host.
- Never use
--privilegedor mount/var/run/docker.sockinto an app container; both effectively give root on the host.
6. Sign and verify
Sign images in CI (for example with cosign) and verify signatures before deploying, so only images built by your pipeline can run.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.