Introduction
Docker provides a bridge network on every service that defined in docker-compose file. On default, if we don’t specify the networks configuration, it will generate automatically based on project directory with _default suffix and each service will be in same network and can directly communicate. However, the problem comes when we have different container stack with new docker-compose file and we want to connect to existing services in the same network.
Docker Compose Networks
The idea is to connect different service in the pre-existing network is using this boilerplate configuration, and set the options external : true
.
services:
# ...
networks:
- app_network
networks:
app_network:
name: my-pre-existing-network
external: true
Instead of attempting to create a network called [projectname]_default
, Compose looks for a network called my-pre-existing-network
and connects your app’s containers to it.
Demo
Assume we have 2 docker-compose file for different project.
Project A : docker-compose.yml
services:
db:
image: mariadb:latest
container_name: app-db
ports:
- '3306:3306'
networks:
- app-network
networks:
app-network:
driver: bridge
name: project-A-network
This will create db service that loads mariadb image that expose port 3306 and connected in app-network named project-A-network.
Project B : docker-compose.yml
services:
app:
image: my-app
container_name: main-app
ports:
- '80:80'
networks:
- app-network
networks:
app-network:
name: project-A-network
external: true
This will create dummy app service that running our apps that expose to port 80. It will connect to project-A-network and can communicate each others with IP or service name.
Conclusion
This post has shown you how to connect various Docker Compose services together over a single network. They can join an already-established network or we can build a network from a service definition.
Leave a Reply