Hadolint in pre-commit
Problem
Dockerfiles are reviewed by eye. Typical mistakes slip into main: apt-get install without --no-install-recommends, latest tags (FROM python:latest), ADD instead of COPY, RUN without cache cleanup, a container running as root. Then images bloat, CVEs pile up, and a security review finds it six months later.
Solution
Hadolint is "a smarter Dockerfile linter that helps you build best practice Docker images". It parses the Dockerfile into an AST, applies rules on top of it, and uses ShellCheck to lint the Bash code inside RUN instructions. Run it automatically through pre-commit — locally before the commit and in CI. A developer can't commit a Dockerfile that fails the linter.
Example
.pre-commit-config.yaml at the repository root:
repos:
- repo: https://github.com/hadolint/hadolint
rev: v2.13.0
hooks:
- id: hadolint-docker
args:
- --failure-threshold=warning
- --ignore=DL3008 # apt-get pinning — disable if you use your own base
Install and enable once per repo:
pip install pre-commit
pre-commit install
# Run over existing files
pre-commit run --all-files
In GitHub Actions / GitLab CI — the same hook as a separate job:
# .github/workflows/lint.yml
- uses: actions/checkout@v4
- uses: pre-commit/action@v3.0.1
What hadolint catches in a real Dockerfile:
Dockerfile:3 DL3007 warning: Using latest is prone to errors
Dockerfile:5 DL3008 warning: Pin versions in apt-get install
Dockerfile:8 DL3009 info: Delete the apt-get lists after installing
Dockerfile:12 DL3025 warning: Use arguments JSON notation for CMD
When to use
- Any repository with a Dockerfile (from a microservice to an internal utility).
- In a monorepo — one
.pre-commit-config.yamlcovers all Dockerfiles at once.
Source
- veggiemonk/awesome-docker — the Linters section
- hadolint/hadolint — the DL* rules and their rationale
- pre-commit.com — the "fail fast, local first" approach
How to apply it yourself
- Add
.pre-commit-config.yamlwith thehadolint-dockerhook. pre-commit installon dev machines +pre-commit run --all-filesto backfill.- Fix the minimum severity in the team rules (
warningis the sweet spot). - After the first "clean" CI build with the hook enabled — mark it Studied.