Skip to main content
When it comes to container security and vulnerability management, linting your Dockerfiles against policy-as-code rules is essential. In this guide, we’ll show you how to use Open Policy Agent (OPA) and Conftest to enforce Docker best practices automatically.

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 the latest 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 named docker.rego in your workspace:
How it works:
  • input[i].Cmd == "from" locates every FROM instruction.
  • 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

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:
On failure, you’ll see output like this:
To fix the failure, update the FROM line:
Re-run the test, and you should see no failures.

Further Reading & References

Watch Video