Phony targets: the DevOps reality
Why .PHONY exists
Most DevOps targets don't produce a file named after themselves — test, lint, deploy, clean. If a file or directory with that name ever appears (a test/ directory is extremely common!), make sees "target exists and has no newer prerequisites" and silently does nothing:
$ make test
make: 'test' is up to date.
Declare such targets phony so they always run and make doesn't look for files:
.PHONY: help build test lint docker-build docker-push deploy clean
There's no global "all targets are phony" switch; list them (many teams put .PHONY: name right above each target so it's not forgotten).
Mixing real-file and phony targets
The best Makefiles use both: phony targets as the human interface, real file targets for expensive steps so they're skipped when nothing changed:
.PHONY: build
build: bin/orders # human-friendly name
bin/orders: $(shell find . -name '*.go') go.mod go.sum
go build -o $@ ./cmd/orders # rebuilt only if Go sources changed
Order-only prerequisites
A prerequisite after | must exist before the target is built, but its timestamp doesn't trigger rebuilds. Perfect for output directories (a directory's mtime changes whenever a file inside it changes, which would cause needless rebuilds):
build/app: main.go | build
go build -o $@ .
build:
mkdir -p build
Diagnosing "always runs" vs "never runs"
| Symptom | Cause |
|---|---|
| Target never reruns after code changes | A file/dir with the target's name exists and is newer — mark it .PHONY; or the real prerequisites aren't listed |
| Target always reruns though nothing changed | It's phony (fine for tasks), or its recipe doesn't create a file exactly matching the target name, or a prerequisite is phony (phony prerequisites are always "newer") |