Skip to main content

Using existing Docker network error in Docker Compose

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Following our guide to set up Traefik, Docker, and Compose with multiple networks, I ran into a problem:

a network with name customer_staging_default exists but was not created for project "customer_staging"
Set `external: true` to use an existing network

network customer_staging_default was found but has incorrect label com.docker.compose.network set to "staging_default"

While looking for a solution, I found a similar issue on the Docker Compose GitHub repository. Docker Compose version 2.19.1 seems to have introduced a stricter check when connecting containers to networks for security reasons.

Previously, a Docker Compose configuration like the one below worked like a charm:

version: '3.7'

services:
api:
image: nexus3.loc/customer/application:${TAG:-latest}
networks:
- customer

With Docker Compose version 2.19.1, the Compose configuration has to look like this:

version: '3.7'

services:
api:
image: nexus3.loc/customer/application:${TAG:-latest}
networks:
- customer

networks:
customer:
name: "${COMPOSE_PROJECT_NAME}_default"
external: true

The key "customer" in the service network definition refers to the same key in the networks section where you can mark the network as being "external".

Since we are using the ${COMPOSE_PROJECT_NAME} variable in the network name definition, we can dynamically set the name of the network in our GitLab CI pipeline configuration for the staging and production deployments, respectively:

deploy:stage:
stage: deploy
only:
- tags
environment:
name: staging
url: https://staging.loc
script:
- export TAG="${CI_COMMIT_TAG}"
- export COMPOSE_PROJECT_NAME="customer_staging"
- docker compose -f docker-compose.deploy.yml pull
- docker compose -f docker-compose.deploy.yml stop || true
- docker compose -f docker-compose.deploy.yml up -d
allow_failure: false