Communicating between multiple Compose environments
If you build a system composed of multiple independent services and/or applications, you will very likely want to keep their code in multiple independent code repositories (projects). The docker-compose.yml files for every Compose application are usually kept in the same code repository as the application code. The default network that was created by Compose for a single application is isolated from the networks of other applications. So, what can you do if you suddenly want your multiple independent applications to communicate with each other?
Fortunately, this is another thing that is extremely easy with Compose. The syntax of the docker-compose.yml file allows you to define a named external Docker network as the default network for all services defined in that configuration. The following is an example configuration that defines an external network named my-interservice-network:
version: '3'
networks:
default:
external:
name: my-interservice-network
services:
webserver:
build: .
ports:
- "80:80"
tty: true
environment:
- DATABASE_HOSTNAME=database
- DATABASE_PORT=5432
database:
image: postgres
restart: always
Such external networks are not managed by Compose, so you'll have to create it manually with the docker network create command, as follows:
docker network create my-interservice-network
Once you have done this, you can use this external network in other docker-compose.yml files for all applications that should have their services registered in the same network. The following is an example configuration for other applications that will be able to communicate with both database and webserver services over my-interservice-network, even though they are not defined in the same docker-compose.yml file:
version: '3'
networks:
default:
external:
name: my-interservice-network
services:
other-service:
build: .
ports:
- "80:80"
tty: true
environment:
- DATABASE_HOSTNAME=database
- DATABASE_PORT=5432
- WEBSERVER_ADDRESS=http://webserver:80
Let's take a look at popular productivity tools in the next section.