Traefik is unable to resolve network when the network name in docker-compose file uses a template variable

As per this github issue I am moving the problem here.

I have a docker-compose.yml file with a servic that connects to the traefik network:-

version: '3.9'

services:
  sqlserver:
    image: mcr.microsoft.com/mssql/server:2022-latest    
    deploy:      
      replicas: 1      
      restart_policy:        
        condition: any
        delay: 5s
      labels:
        traefik.tcp.services.sqlserver.loadbalancer.server.port: 1433
        traefik.tcp.routers.sqlserver.entrypoints: "mssql"
        traefik.tcp.routers.sqlserver.rule: "HostSNI(`*`)"
        traefik.tcp.routers.sqlserver.tls: "false"
        # traefik.tcp.routers.sqlserver.service: sqlserver
        traefik.enable: "true"
        # traefik.docker.network: "reverse-proxy-${TRAEFIK_NETWORK_NAME}"  
    # ports:
    #   - '1433:1433'
    environment:
      ACCEPT_EULA: "Y"
      MSSQL_SA_PASSWORD: "${MSSQL_PASSWORD}"
    networks:
      - sqlserver
      - traefik-net

networks:   
  sqlserver:
    name: sqlserver   
    driver: overlay
    attachable: true  

  traefik-net:
    name: reverse-proxy-${TRAEFIK_NETWORK_NAME}
    driver: overlay
    external: true    
    

When this is deployed using docker stack deploy note that the environment variable ${TRAEFIK_NETWORK_NAME} is used in the template for the network name.

I then see errors in traefic logs:

67eem time="2023-07-03T13:41:27Z" level=warning msg="Could not find network named 'reverse-proxy-${TRAEFIK_NETWORK_NAME}' for container 'mystack_sqlserver.1'! Maybe you're missing the project's prefix in the label? Defaulting to first available network."

However if I uncomment this label in the compose file and re-deploy

- traefik.docker.network=reverse-proxy-${TRAEFIK_NETWORK_NAME}

Note: still using an environment variable

This error goes away.

As you can see I have established a solution. However my question is whether this should be considered a bug with traefik. i beleive that traefik should be able to work out the network name without this label being needed? It seems like whatever code in the first scenario is discovering the network from the compoose file is seeing the use of an environment variable with an un-substituted variable, and treating that as the literal network name which it is ofcourse unable to find such a network.

For me the question is if this template substitution should be handled by Docker or Traefik.

Maybe Docker doesn’t handle it in all cases? Use docker inspect to see what’s used inside the service configuration.