Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ jobs:
exit 1
fi

- name: Vet
run: go vet ./...

- name: Run tests with coverage
run: go test ./... -coverprofile=coverage.out -covermode=atomic

Expand Down
38 changes: 31 additions & 7 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.1.0] - 2026-10-24
## [0.1.1] - 2026-10-24

First release. The Changed, Removed and Fixed sections describe differences from
the unreleased code on `main` before this version, for anyone who built it from
source.
First published release. The Changed, Removed and Fixed sections describe
differences from the code on `main` before it, for anyone who built it from
source. Version 0.1.0 was tagged but never published.

### Added
- Dockerfile parser with multi-stage build support
Expand Down Expand Up @@ -53,7 +53,13 @@ source.
- The GitHub Action lints several paths or patterns (one per line) and takes a
`config` input
- `--version` falls back to the version Go records in the binary, so builds from
`go install github.com/devblac/docker-lint/cmd/docker-lint@v0.1.0` report it
`go install github.com/devblac/docker-lint/cmd/docker-lint@v0.1.1` report it
- Flags may follow the paths (`docker-lint Dockerfile --json`), `--` ends the
flags, and `-` reads stdin
- The GitHub Action installs the docker-lint release matching the tag it is used
at (`@v0.1.1` installs v0.1.1), so pinning the action pins the linter
- Tests that every rule reports a real-world example of its problem, alongside
the corpus that guards against false positives

### Changed
- **Breaking:** rule IDs move from `DLxxxx`, which collide with hadolint's IDs for
Expand All @@ -79,6 +85,12 @@ source.
- DKL404 (missing HEALTHCHECK) and DKL202 (consecutive RUN) are now `info`: on the
corpus they fired on 51 and 39 of 52 files, and Kubernetes ignores HEALTHCHECK
- DKL103 judges only the base of the final image
- DKL203 reports the whole build context copied before installing dependencies
(`COPY . .` then `npm ci`, `pip install -r` or `go mod download`), and
recognises many more installers (npm ci, pnpm, bun, yarn, uv, poetry, pipenv,
bundle, composer, cargo fetch, dotnet restore, mvn dependency:go-offline)
- Directory searches skip Dockerfile templates, backups and docs
(`Dockerfile.template`, `.j2`, `.bak`, `.md`); name such a file to lint it

### Removed
- Hand-written Dockerfile lexer (`internal/parser/lexer.go`), superseded by BuildKit
Expand Down Expand Up @@ -106,6 +118,18 @@ source.
- DKL203 flagged the recommended pattern of copying dependency manifests first
(`COPY go.mod go.sum ./`, `COPY package*.json ./`) because it inspected the
destination instead of the sources
- DKL304 flagged `ADD --checksum=...`, which Docker recommends for remote files,
and `ADD` of a Git repository; DKL305 said COPY could replace `ADD git@...`
- DKL201 ignored `PIP_NO_CACHE_DIR` set with ENV or for the command
- `exclude` patterns are relative to the configuration file, so they also apply
when docker-lint runs from a subdirectory or is given absolute paths

## [0.1.0] - 2026-10-24

Tagged but never published. A review of the draft release found the problems
fixed in 0.1.1, and the tag could not be moved because the Go module proxy had
already cached it. Use 0.1.1 instead.

[Unreleased]: https://github.com/devblac/docker-lint/compare/v0.1.0...HEAD
[0.1.0]: https://github.com/devblac/docker-lint/releases/tag/v0.1.0
[Unreleased]: https://github.com/devblac/docker-lint/compare/v0.1.1...HEAD
[0.1.1]: https://github.com/devblac/docker-lint/releases/tag/v0.1.1
[0.1.0]: https://github.com/devblac/docker-lint/tree/v0.1.0
8 changes: 6 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ release, so nothing is public until a maintainer publishes it.
1. Make sure `main` is green and `goreleaser release --snapshot --clean` builds locally
(CI also runs it on every pull request).
2. In `CHANGELOG.md`, rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD`, add a new
empty `## [Unreleased]` above it, and merge that change to `main`.
empty `## [Unreleased]` above it, update the comparison links at the bottom, and
merge that change to `main`.
3. Tag the merge commit and push the tag:

```bash
Expand All @@ -112,7 +113,10 @@ release, so nothing is public until a maintainer publishes it.
4. The Release workflow runs the tests, takes the release notes from the version's
`CHANGELOG.md` section (it fails if there is none) and uploads the binaries and
`checksums.txt` to a draft release.
5. Review the draft on the Releases page and publish it.
5. Review the draft on the Releases page: check its notes, download an archive and
verify it against `checksums.txt`, then publish it. Avoid `go install ...@vX.Y.Z`
before publishing: the Go module proxy caches a tag's contents permanently, so the
tag can no longer be moved if the release needs fixing.

## Questions?

Expand Down
40 changes: 27 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ A minimal, production-grade CLI tool for statically analyzing Dockerfiles to det
- **Static Analysis**: Purely static analysis - never executes Docker builds
- **Real Dockerfile Syntax**: Parsing is delegated to BuildKit, the parser `docker build` itself uses, so heredocs (`RUN <<EOT`), parser directives (`# syntax`, `# escape`), `RUN --mount` flags and line continuations are understood exactly as Docker understands them
- **Single Binary**: Compiles to a single Go binary with no runtime dependencies
- **CI/CD Ready**: Clear exit codes (0, 1, 2) and JSON output for pipeline integration
- **Configurable**: Ignore specific rules via CLI flags or inline comments
- **CI/CD Ready**: Clear exit codes (0, 1, 2); text, JSON, SARIF and GitHub annotation output; a GitHub Action
- **Whole Repositories**: Lint every Dockerfile under a directory or matching a glob in one run
- **Configurable**: A `.docker-lint.yaml` file, CLI flags or inline comments to ignore rules or change their severity
- **Security Focused**: Detects secrets in ENV/ARG without exposing actual values
- **Multi-stage Support**: Correctly analyzes multi-stage Dockerfiles with per-stage rule evaluation
- **Comprehensive Rules**: 18 built-in rules covering Dockerfile structure, base images, layer optimization, security, and best practices
Expand All @@ -24,7 +25,7 @@ Prebuilt binaries for Linux, macOS and Windows (amd64 and arm64) are attached to

```bash
# Linux amd64; replace the version and platform as needed
VERSION=0.1.0
VERSION=0.1.1
curl -sSLO "https://github.com/devblac/docker-lint/releases/download/v${VERSION}/docker-lint_${VERSION}_linux_amd64.tar.gz"
curl -sSLO "https://github.com/devblac/docker-lint/releases/download/v${VERSION}/checksums.txt"
sha256sum --check --ignore-missing checksums.txt
Expand Down Expand Up @@ -58,10 +59,13 @@ docker-lint [flags] [path ...]
```

Each path is a Dockerfile, a directory, or a glob pattern. A directory is searched recursively for files named
`Dockerfile`, `Containerfile`, `Dockerfile.*` or `*.Dockerfile` (skipping `.git` and `node_modules`). Patterns
`Dockerfile`, `Containerfile`, `Dockerfile.*` or `*.Dockerfile` (skipping `.git` and `node_modules`, and templates,
backups and docs such as `Dockerfile.template`, `Dockerfile.j2` or `Dockerfile.bak`, which name a file explicitly
to lint). Patterns
support `**` for any number of directories and are expanded by docker-lint itself, so quote them to make them
work the same in every shell, including on Windows. A directory or pattern that matches no Dockerfile is a fatal
error, so a CI job cannot pass without linting anything. With no path, docker-lint reads from stdin.
error, so a CI job cannot pass without linting anything. With no path, or with `-`, docker-lint reads from stdin.
Flags may come before or after the paths; use `--` before a path that starts with `-`.

### Flags

Expand Down Expand Up @@ -142,8 +146,9 @@ strict: true
# Hide informational findings (same as --quiet).
quiet: false

# Skip matching files when a directory or pattern is expanded. A pattern without
# a slash matches a file or directory name anywhere, as in .gitignore.
# Skip matching files when a directory or pattern is expanded. Patterns are
# relative to this file's directory; one without a slash matches a file or
# directory name anywhere, as in .gitignore.
exclude:
- vendor
- "examples/**"
Expand All @@ -169,7 +174,7 @@ the exit code is then 2.
docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are grouped by category in hundreds:
`DKL0xx` structure, `DKL1xx` base image, `DKL2xx` layers, `DKL3xx` security, `DKL4xx` best practices.

> **Renamed rule IDs.** Before v0.1.0, rules used `DLxxxx` IDs, which collide with
> **Renamed rule IDs.** Before v0.1.1, the first release, rules used `DLxxxx` IDs, which collide with
> [hadolint](https://github.com/hadolint/hadolint)'s IDs for different rules. The old IDs are not accepted;
> passing one to `--ignore` prints its replacement. See the [CHANGELOG](CHANGELOG.md) for the full mapping.

Expand All @@ -193,7 +198,7 @@ docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are gr
|----|----------|------|-------------|
| DKL201 | Warning | Package manager cache not cleaned | Clean package manager cache in the same RUN instruction to reduce image size. `apt-get dist-clean` and `--mount=type=cache` count as clean |
| DKL202 | Info | Consecutive RUN instructions | Combine consecutive RUN instructions to reduce the number of layers |
| DKL203 | Warning | Suboptimal layer ordering | Place instructions that change less frequently earlier to optimize layer caching |
| DKL203 | Warning | Suboptimal layer ordering | Place instructions that change less frequently earlier to optimize layer caching, e.g. copy only the dependency manifests before `npm ci`, `pip install -r` or `go mod download`, not the whole build context |
| DKL204 | Warning | Package update without install | Combine package update with install in the same RUN instruction to avoid cache issues |

### Security Rules
Expand All @@ -203,7 +208,7 @@ docker-lint includes 18 built-in rules. Rule IDs use the `DKL` prefix and are gr
| DKL301 | Warning | Potential secret in ENV | Avoid storing secrets in ENV instructions as they persist in the image layers |
| DKL302 | Warning | Potential secret in ARG | Avoid storing secrets in ARG instructions as they are visible in image history |
| DKL303 | Warning | Final image runs as root | The final image should not run as root; set a non-root USER in the final stage. Build stages are not checked, and a USER inherited from an earlier stage counts |
| DKL304 | Warning | ADD with URL | Using ADD with URLs is discouraged; use curl or wget in RUN for better control |
| DKL304 | Warning | ADD with URL | An unverified download: pin it with `ADD --checksum=sha256:...` or fetch it in RUN. Git repositories (`ADD https://.../repo.git#ref`) are not reported |
| DKL305 | Warning | ADD where COPY would suffice | Use COPY instead of ADD when not extracting archives or fetching URLs |

### Best Practice Rules
Expand Down Expand Up @@ -283,7 +288,7 @@ the pull request diff with the findings:

```yaml
- uses: actions/checkout@v7
- uses: devblac/docker-lint@v0.1.0
- uses: devblac/docker-lint@v0.1.1
with:
dockerfile: Dockerfile
```
Expand All @@ -298,7 +303,7 @@ permissions:

steps:
- uses: actions/checkout@v7
- uses: devblac/docker-lint@v0.1.0
- uses: devblac/docker-lint@v0.1.1
with:
dockerfile: |
Dockerfile
Expand All @@ -312,13 +317,22 @@ steps:
|-------|---------|-------------|
| `dockerfile` | `Dockerfile` | Files, directories or glob patterns to lint, one per line |
| `config` | | Configuration file (default: `.docker-lint.yaml` at the repository root) |
| `version` | `latest` | docker-lint release to install, e.g. `v0.1.0` |
| `version` | action's tag | docker-lint release to install: by default the one matching the action's tag (`@v0.1.1` installs v0.1.1), or the latest release when the action is used from a branch. Also `latest` or a tag such as `v0.1.1` |
| `format` | `github` | Log output: `github` (annotations), `text`, `json` or `sarif` |
| `strict` | `false` | Fail on warnings, not only on errors |
| `quiet` | `false` | Hide informational findings |
| `ignore` | | Comma-separated rule IDs to ignore |
| `sarif-file` | | Also write a SARIF report here (`docker-lint.sarif` when uploading) |
| `upload-sarif` | `false` | Upload the SARIF report to GitHub code scanning |
| `github-token` | `github.token` | Token used to download the docker-lint release |

| Output | Description |
|--------|-------------|
| `exit-code` | docker-lint's exit code: `0` clean, `1` lint errors (or warnings with `strict`), `2` fatal error |
| `sarif-file` | Path of the SARIF report, when one was written |

Pinning the action pins the linter: `@v0.1.1` installs docker-lint v0.1.1. When you pin the action to a commit
SHA, also set `version` to the matching tag; otherwise the latest release is installed.

The action fails the step with docker-lint's exit code and exposes it as the `exit-code` output. A SARIF
report is still written and uploaded when the lint fails, and covers every Dockerfile that could be parsed;
Expand Down
26 changes: 22 additions & 4 deletions action.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: docker-lint
description: Lint Dockerfiles for inefficiencies, anti-patterns and security issues, with pull request annotations and SARIF for code scanning
description: Lint Dockerfiles for anti-patterns, inefficiencies and security issues; annotates pull requests and outputs SARIF
author: devblac
branding:
icon: check-square
Expand All @@ -19,9 +19,12 @@ inputs:
default: ""
version:
description: >-
docker-lint release to use: "latest" or a tag such as "v0.1.0". "source"
builds the action's own checkout instead (needs Go; used to test the action).
default: latest
docker-lint release to use. By default, the release matching the tag the
action is used at (uses: devblac/docker-lint@v1.2.3 installs v1.2.3), or
the latest release when the action is used from a branch or commit. Also
accepts "latest", a tag such as "v0.1.1", or "source" to build the
action's own checkout (needs Go; used to test the action).
default: ""
format:
description: >-
Output format for the job log: "github" (annotations on the pull request
Expand Down Expand Up @@ -70,6 +73,7 @@ runs:
VERSION: ${{ inputs.version }}
GH_TOKEN: ${{ inputs.github-token }}
ACTION_PATH: ${{ github.action_path }}
ACTION_REF: ${{ github.action_ref }}
run: |
set -euo pipefail

Expand All @@ -90,6 +94,20 @@ runs:
bin_dir="$RUNNER_TEMP/docker-lint-bin"
mkdir -p "$bin_dir"

# Pinning the action pins the linter: by default, install the release
# whose tag the action is used at. The runner checks the action out
# under .../_actions/<owner>/<repo>/<ref>, which also gives the ref when
# github.action_ref is empty, as it is in some nested composite actions.
if [ -z "$VERSION" ]; then
ref="${ACTION_REF:-$(basename "$ACTION_PATH")}"
if printf '%s' "$ref" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$'; then
VERSION="$ref"
else
VERSION=latest
fi
fi
echo "docker-lint: installing $VERSION"

if [ "$VERSION" = source ]; then
(cd "$ACTION_PATH" && go build -o "$bin_dir/docker-lint$exe" ./cmd/docker-lint)
else
Expand Down
48 changes: 44 additions & 4 deletions cmd/docker-lint/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"os"
"path/filepath"
"runtime/debug"
"strings"

Expand Down Expand Up @@ -72,7 +73,8 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
fs.StringVar(&configPath, "config", "", "")
fs.StringVar(&configPath, "c", "", "")

if err := fs.Parse(args); err != nil {
paths, err := parseArgs(fs, args)
if err != nil {
if errors.Is(err, flag.ErrHelp) {
printUsage(stdout)
return ExitSuccess
Expand Down Expand Up @@ -134,7 +136,13 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
SeverityOverrides: cfg.SeverityOverrides(),
})

reports, single, fatal := lintInputs(fs.Args(), cfg.Exclude, stdin, anlzr, stderr)
// Exclude patterns are relative to the configuration file's directory.
exclude := files.Exclusions{Patterns: cfg.Exclude}
if cfgPath != "" {
exclude.Base = filepath.Dir(cfgPath)
}

reports, single, fatal := lintInputs(paths, exclude, stdin, anlzr, stderr)

out := output{format: outputFormat, quiet: quiet, tool: toolInfo(cfg)}
if formatErr := out.write(reports, single, stdout); formatErr != nil {
Expand All @@ -152,6 +160,28 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
return determineExitCode(all, strict)
}

// parseArgs parses flags wherever they appear, so "docker-lint Dockerfile
// --json" works like "docker-lint --json Dockerfile", and returns the
// positional arguments in order. Everything after "--" is positional.
func parseArgs(fs *flag.FlagSet, args []string) ([]string, error) {
var positional []string
for {
if err := fs.Parse(args); err != nil {
return nil, err
}
rest := fs.Args()
if len(rest) == 0 {
return positional, nil
}
// flag stops at "--" (consuming it) or at the first non-flag argument.
if consumed := len(args) - len(rest); consumed > 0 && args[consumed-1] == "--" {
return append(positional, rest...), nil
}
positional = append(positional, rest[0])
args = rest[1:]
}
}

// loadConfig returns the configuration to use: the file named by --config,
// none with --no-config, or else the nearest .docker-lint.yaml. It also
// returns the path the configuration came from, "" when there is none.
Expand All @@ -177,7 +207,17 @@ func loadConfig(path string, disabled bool) (*config.Config, string, error) {
// paths expand to. A file that cannot be read or parsed is reported on stderr
// and skipped, and fatal is set; the other files are still linted. single is
// true when the input is stdin or one file named directly.
func lintInputs(paths, exclude []string, stdin io.Reader, anlzr *analyzer.Analyzer, stderr io.Writer) (reports []formatter.Report, single, fatal bool) {
func lintInputs(paths []string, exclude files.Exclusions, stdin io.Reader, anlzr *analyzer.Analyzer, stderr io.Writer) (reports []formatter.Report, single, fatal bool) {
if len(paths) == 1 && paths[0] == "-" {
paths = nil
}
for _, p := range paths {
if p == "-" {
fmt.Fprintln(stderr, "Error: - (stdin) cannot be combined with other paths")
return nil, false, true
}
}

if len(paths) == 0 {
if stdin == nil {
stdin = os.Stdin
Expand Down Expand Up @@ -381,7 +421,7 @@ Usage:

Each path is a Dockerfile, a directory searched recursively for Dockerfiles,
or a glob pattern such as "services/**/Dockerfile". Reads from stdin when no
path is given.
path (or -) is given. Flags may come before or after the paths.

Flags:
-h, --help Show this help message
Expand Down
Loading
Loading