Join an existing network from a docker container in docker compose
In some scenarios, we might need to connect to an existing network from a docker container instead of create a new network. This would let us allow the resources in the existing network.
To join an existing network, you can define a network under each service and at the end of the docker compose file you can define the network to use the existing external network.
services: service_name: image: image_name:latest restart: always networks: - existing-network networks: existing-network: external: true
version: '3.1' services: postgres: image: postgres:latest restart: always networks: - existing-network volumes: - postgres-data:/var/lib/postgresql/data environment: - 'POSTGRES_PASSWORD=redmine' - 'POSTGRES_DB=redmine' redmine: image: redmine:latest restart: always networks: - existing-network volumes: - redmine-data:/usr/share/redmine/files ports: - 4000:3000 environment: - 'REDMINE_DB_POSTGRES=postgres' - 'REDMINE_DB_DATABASE=redmine' - 'REDMINE_DB_PASSWORD=redmine' volumes: postgres-data: redmine-data: networks: existing-network: external: true
Here I let the postgres and redmine containers to use the existing network.