Skip to main content
In this tutorial, we’ll show you how to automatically enforce Dockerfile security best practices using Open Policy Agent’s Conftest. You’ll learn to:
  1. Review key Dockerfile guidelines
  2. Understand Kubernetes’ default container user
  3. Install and configure Conftest
  4. Write and run Rego policies against your Dockerfile
  5. Integrate policy checks into a CI/CD pipeline
  6. Remediate common security violations

Table of Contents


Dockerfile Security Best Practices

Follow Docker’s official guidelines to reduce vulnerabilities: Example: building a minimal BusyBox image
Good vs. avoid:
To run as non-root:
The image shows a webpage from Docker documentation, specifically focusing on Dockerfile best practices, with sections on USER, WORKDIR, and ONBUILD instructions. The browser window also displays multiple open tabs and a taskbar with various applications.

Default Container User in Kubernetes

By default, containers run as root in Kubernetes pods1. Verify with:
Running containers as root increases risk of privilege escalation. Always switch to a non-root user in your Dockerfile.

Installing OPA Conftest

Conftest evaluates your Dockerfile against custom policies written in Rego. Linux
macOS
Windows (Scoop)
Alternatively, use the official Docker image:
docker pull openpolicyagent/conftest

Writing Rego Policies

Create a file opa-docker-security.rego containing rules like:

Scanning a Dockerfile with Conftest

Given Dockerfile:
Run:
Output:

CI/CD Integration

Add a Conftest scan to your Jenkins pipeline:
A Conftest failure will halt the pipeline and highlight policy violations.

Fixing Policy Violations

  1. Trusted base images – comment or adjust the rule if using a private registry.
  2. Replace ADD with COPY.
  3. Create and switch to a non-root user.

Adjusted Rego (disable trusted-base-image rule)

Revised Dockerfile

Commit and push your changes, then rerun the pipeline.

Verifying the Fixes

Deploy to Kubernetes and confirm non-root:

References

Watch Video

Footnotes

  1. Kubernetes inherit root privileges unless overridden by securityContext.