Opscraft
Makefile · Lesson 2 of 7 · 3 min read

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).

Enlarge diagramWithout .PHONY.PHONY: testA test/ directory existsmake: 'test' is up to date.Your tests silently never runmake ignores any file named testThe recipe always runsList every task target
Figure 1. Why .PHONY matters: a folder called test/ makes make think the test target is already built.
Swipe sideways to see all of it, or tap to open it full screen.

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
Enlarge diagrambuild/appmain.gonewer → rebuildbuild/after |: must exist only
Figure 2. Order-only prerequisites: the build directory must exist, but its changing timestamp does not force rebuilds.
Swipe sideways to see all of it, or tap to open it full screen.

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")