Docker Community Forums

Share and learn in the Docker community.

Multiple networks in a docker compose file: precedence?

In our typical project setup, we are using traefik as a reverse proxy. Therefore, we have an external network in our docker compose file (traefik is running outside of this project and is irrelevant to the issue). Containers that need to be accessible from the internet join traefik’s network next to the project’s default network. Since multiple projects may be running on the same server, it is possible that there are multiple services with the same name connected to the external traefik network.
An example (limited to the network setup):

version: '2'
networks:
  default:
    driver: bridge
  system_traefik:
    external: true

services:
  api:
    networks:
      - default
      - system_traefik
  auth:
    networks:
      - default
      - system_traefik

The COMPOSE_PROJECT_NAME var is set, resulting in a network ${COMPOSE_PROJECT_NAME}_default.
When we’re trying to connect from e.g. api to auth, we’re typically using the service name e.g. http://auth.
What I noticed is that depending on the COMPOSE_PROJECT_NAME this request is resolved to a different network; if COMPOSE_PROJECT_NAME is alphabetically following system_traefik, the system_traefik network is used, otherwise the project’s default network ${COMPOSE_PROJECT_NAME}_default is used. Due to the fact that there may be different auth services from different projects on the system_traefik network, this results in unpredictable behaviour in the former case.

I was wondering if this is intentional? https://docs.docker.com/engine/userguide/networking/ mentions:

When a container is connected to multiple networks, its external connectivity is provided via the first non-internal network, in lexical order.

In the context of a compose project, I would think external connectivity means outside the project, but apparently not? The default network taking precedence regardless of the name seems more logical to me.
If this is intentional, what is the proper way to avoid this? Using links with an alias?

1 Like

I came across with this question too…?
Have you found any answer ?