YAML anchors are fine while everything sits in one file. When two services share a base and each overrides a few keys, I find extends easier to read.
A service names the service it builds on, and its own keys win:
services:
common:
image: busybox
environment:
TZ: Europe/Amsterdam
PORT: 80
cli:
extends:
service: common
environment:
PORT: 8080
The cli service ends up with the image and TZ from the base, and PORT: 8080 from itself. The base can also live in another file:
extends:
file: common.yml
service: webapp
Without file, the base has to be in the same compose file. Lists such as security_opt are combined with duplicates removed, and single values like image are replaced. Mappings like environment merge key by key, which is why only PORT changes above.
Caveats: a base in the same file is a normal service, so docker compose up starts it too. Put it in its own file with file: if you only want a template. Circular references give an error, and extends is not supported with docker stack deploy.
I would use anchors for a tiny shared snippet and extends once several stacks share a base file.
Further reading: Compose services: extends