Docker Compose enables us to create and start all services from the configuration in a single YAML file and each container for a service can be reachable by other containers and discoverable by them at a hostname identical to the container name. Normally, different microservices for an application have their own repositories and each microservice has its own Docker Compose file. When the container for service1 started by using a Docker Compose file wants to talk to the container for service4 started by using another Docker Compose file, can both of them be reachable and discoverable by each other in the same way as mentioned earlier?
The answer is yes and no. Yes, you can reference another service by its name defined in the Docker Compose file. No, it will not work without some extra work.
I think it is worthwhile to explain why it works with no extra work for service containers spun up by using a single Docker Compose file. When Docker Compose spins up these services, a network is also created and started. The name of the network can be specified in the Docker Compose file, or a default network will be created by Docker Compose. Each container for a service joins the network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
After understanding this, now you may presume that as long as we let all the containers created by different Docker Compose files join the same network, they can be reachable and discoverable by each other.
Congratulations! You are absolute right. The extra work we need to do is to put all the containers in the same network and let me show you how we can achieve this:
Create a docker network by running following command in your CLI
docker network create YOUR_NETWORK_NAME
In all your Docker Compose files, let all services join the network created in step 1. Let me put 2 sample Compose files below:
command: ['yarn', 'run', 'start:dev']
Then, service1, service2, service3 and service4 can communicate with each by just referencing each other’s container name in the Compose file.