Connect two docker deployments
Sometimes you have to connect two docker deployments together, so today we will look at how to achieve that connection using docker networks.
The problem
Sometimes you have to connect two docker deployments together, so today we will look at how to achieve that connection using docker networks.
In this example we will have two deployments, backend.yml
and frontend.yml
The backend.yml
looks like this:
# backend.yml
version: '3'
services:
application:
image: "application"
container_name: "application"
restart: unless-stopped
And the frontend.yml
looks like this:
# frontend.yml
version: '3'
services:
webserver:
image: nginx:1.23.3-alpine
container_name: webserver
restart: unless-stopped
ports:
- "80:80"
- "443:443"
Now, the problem is that if we try to route traffic from the nginx on the frontend.yml
deployment to let's say
the "application" container from the backend.yml all those packages will fail.
The solution
To solve this, we will need to create a docker network. We do this by modifying backend.yml
to look like this
# backend.yml
version: '3'
services:
application:
image: "application"
container_name: "application"
restart: unless-stopped
networks:
- app-network
networks:
app-network:
external: false
As you can see we are declaring an explicit network that will be created by docker for us when we do docker-compose up
Now we need to tell the frontend.yml
that such network exists and that the nginx container can have access to it.
By doing this:
# frontend.yml
version: '3'
webserver:
image: nginx:1.23.3-alpine
container_name: webserver
restart: unless-stopped
ports:
- "80:80"
- "443:443"
networks:
- app-network_backend
networks:
app-network_backend:
external: true
See how the name of the network is not the same as we defined on the backend.yml file, that is because docker creates a unique name for every network (unless you explicitly define one), so please make sure to use the following command to check your networks
Which gives the following output:
NETWORK ID NAME DRIVER SCOPE
f3b539b9ccd2 bridge bridge local
e82e0b83d27f host host local
0af007240301 none null local
93e728e8ec71 app-network_backend bridge local
And after restarting both deployments, ngnix will be able to route traffic to the containers on the backend.yml