How can I use dynamic names in my Docker Compose file?

0
6
Asked By CuriousCoder01 On

I'm trying to set dynamic names within my Docker Compose file using Traefik for routing. I have some labels defined like this:

labels:
traefik.enable: true
traefik.docker.network: proxy
traefik.http.routers.${TRAEFIK_SERVICE_NAME}.rule: Host(`calibre-web.${DOMAIN}`) || Host(`books.${DOMAIN}`)
traefik.http.routers.${TRAEFIK_SERVICE_NAME}.entrypoints: https
traefik.http.routers.${TRAEFIK_SERVICE_NAME}.tls: true
traefik.http.services.${TRAEFIK_SERVICE_NAME}.loadbalancer.server.port: 8083

However, the variable ${TRAEFIK_SERVICE_NAME} doesn't seem to replace with the value from my .env file as I expected. I've considered an alternative method of defining the labels, but I prefer the current structure for better readability. On a related note, could anyone also explain what the differences are called for the two styles I mentioned?

2 Answers

Answered By CodeNinja88 On

Try running `docker compose config` in the directory with your compose file to see how variable substitution is being handled. This will show you how the labels look post-substitution. Just a tip: the first style you used without the `-` is called a "mapping", while the one with the `-` is a "list". Both are valid, but variable substitution only works for values, not keys in your YAML. This means you'll need to stick with the list format if you want to replace both the key and value.

InsightfulUser34 -

Thanks! That definitely clarifies things for me. I was hoping for a way to change keys dynamically, but sounds like I need to stick with the list to get the substitution I want.

CodingEnthusiast -

This is super helpful! I'll give the `docker compose config` command a whirl to see the substitutions myself.

Answered By TechWhiz92 On

First off, make sure your .env file is named `.env` and located in the same directory as your Docker Compose file. Sometimes if it's named differently or placed in a subdirectory, the variables won't be substituted correctly. Also, double-check that you have `env_file: .env` in your service definition to ensure it picks up the variables. That might resolve your issue!

CleverDev_77 -

Just to clarify, my .env file is correctly named and in the right folder, and the ${DOMAIN} variable works fine. It's only ${TRAEFIK_SERVICE_NAME} that isn't being replaced.

DockerGuru75 -

I noticed you shared your full docker-compose.yml; that helps! Can you confirm both .env and docker-compose.yml are in the same folder?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.