Docker Tip #98: Nested Variable Interpolation with Docker Compose v2
![blog/cards/docker-tips-and-tricks.jpg](/assets/blog/cards/docker-tips-and-tricks-92efa4f3cccffb29a7369417a3f9e884a77a918d152a0d2c1636c064a4dd2169.jpg)
This can be handy if you want one of your environment variables to default to the value of another variable which has its own default.
Prefer video? Here’s a recorded version of this tip on YouTube which covers this topic.
I remember wanting to do this way back with Docker Compose v1 but it wasn’t supported. Nowadays if you’re running a recent version of Docker Compose v2 it works in a similar way as your shell.
For example, let’s say you have port forwarding set up for a web service:
ports:
- "${DOCKER_WEB_PORT_FORWARD:-127.0.0.1:8000}:${PORT:-8000}"
You can use nested variable interpolation for the forwarded port like this:
ports:
- "${DOCKER_WEB_PORT_FORWARD:-127.0.0.1:${PORT:-8000}}:${PORT:-8000}"
If PORT
is optional you still can’t escape needing to update the 8000
default in 2 spots but the above approach does let you update a single PORT
environment variable definition in your .env
if you want to use a different port.
With that said, I wouldn’t do that in the above case since I like having my container’s port decoupled from the forwarded port but you may want to use nested interpolation for something else. This brings an awareness to the feature.