What Are OPA and Conftest?
Open Policy Agent (OPA)OPA is a versatile, open-source policy engine that lets you define and enforce policies across your stack. You express rules in the Rego language and integrate OPA with your CI/CD pipelines or CLI tools. Conftest
Conftest is a command-line utility that uses OPA under the hood to test structured configuration files. It supports Dockerfiles, Kubernetes manifests, Terraform code, JSON, YAML, and more. You write Rego policies and run
conftest test to verify compliance.
Sample Dockerfile
Below is a simple Java application Dockerfile. Notice it uses thelatest tag, which we’ll target in our policy:
Using the
latest tag in production images can lead to unpredictable builds and security risks. Always pin to a specific, immutable version.Writing a Rego Policy for Dockerfiles
Create a file nameddocker.rego in your workspace:
input[i].Cmd == "from"locates everyFROMinstruction.split(input[i].Value[0], ":")separates the image name from its tag.contains(lower(val[1]), "latest")checks for the forbidden tag.- When matched, it emits a denial message with the line number.
Common Dockerfile Best Practices
| Best Practice | Rule Identifier | Description |
|---|---|---|
| Pin Base Image Tag | base_image_tag | Prevent use of latest for consistent, reproducible builds |
| Use Minimal Images | minimal_image | Encourage slim or distroless variants |
| Avoid Root User | no_root_user | Enforce a non-root USER for improved container security |
You can extend your Rego file to cover these additional rules or write new policies for other Dockerfile instructions.
Running Conftest
Run the policy against your Dockerfile using the official Conftest Docker image:FROM line: