Makefile中docker.*伪目标含义及%通配符作用咨询
docker.% Phony Target and Pattern Matching in Makefile Let’s break down your question into clear, actionable parts to demystify what’s happening here.
1. What does the docker.% phony target mean?
First, .PHONY is a Makefile directive that tells Make: "This target isn’t a real file on your system." Even if a file named docker.my-app exists in your directory, Make will still execute the rule for this target instead of checking if the file is "up-to-date."
The docker.% is a pattern phony target—it’s not a single fixed target, but a template that matches any target starting with docker. (like docker.api, docker.test-service, or docker.my-app). This lets you reuse the exact same rule logic for multiple Docker-related tasks without writing duplicate code for each one.
2. What is % and how does it work in this rule?
The % is Make’s pattern-matching wildcard. Here’s how it operates in your rule:
- When you run a command like
make docker.my-app, the%indocker.%captures the part afterdocker.—so in this case,my-app. - Make stores this captured text in the automatic variable
$*, which you can reference later in the rule’s commands.
Let’s walk through the full execution flow when you run make docker.my-app:
- First, it runs
go mod tidyto sync and clean up your Go module dependencies. - Next,
docker build -t $* .expands todocker build -t my-app .—this builds a Docker image taggedmy-appusing the Dockerfile in your current directory. - Finally, the
docker runcommand becomes:
Thedocker run -p 5751:5751 -v $(pwd)/:/work my-app /work/config.yaml$$(pwd)is an escape for$(since Make uses$for variables), so the shell receives$(pwd)—this mounts your current working directory into the container’s/workfolder. The container runs themy-appimage, uses/work/config.yamlas its config file, and maps port 5751 between your host machine and the container.
Quick example
If you run make docker.hello-world, the rule will:
- Run
go mod tidy - Build an image tagged
hello-world - Spin up a container from that image with the port mount and config file specified
This pattern is incredibly handy because it lets you define one rule that works for any number of Docker images—just append your desired image name to docker. when you run make.
内容的提问来源于stack exchange,提问作者Behrang Saeedzadeh

