DEV Community

Vidyasagar SC Machupalli
Vidyasagar SC Machupalli

Posted on • Originally published at Medium on

Container to container communication with bridge network

In this post, you will learn how to establish container to container communication by creating a Docker bridge network.

source:https://unsplash.com/photos/SxQn-Or41ok

The back story

Currently, I am working on a sample code that includes a frontend (web) and a backend (API). The frontend provides UI to upload an image and passes the image to the backend for external storage. So, I decided to go with to container images as per user requirement.

Built the individual container images

docker build . -t <DockerID>/frontend
docker build . -t <DockerID>/backend
Enter fullscreen mode Exit fullscreen mode

Time to create containers from the respective images. But, before doing that we need to establish communication between these two containers.

The frontend talks to the backend through the backend URL set as an environment variable in the frontend. So, we need to create the backend first and set the frontend env variable with the backend URL.

The climax

To do that, the option I am aware was using –link flag. But, as I hit the documentation, I could see that the option is now deprecated and tagged as legacy.

Digging through Docker’s documentation, I landed on the ne_t_working page. Where on of the options is bridge network

bridge: The default network driver. If you don’t specify a driver, this is the type of network you are creating. Bridge networks are usually used when your applications run in standalone containers that need to communicate. See bridge networks.

https://docs.docker.com/network/

So, here’s how I established the communication between the frontend and backend containers

Create a bridge called mybridge:

docker network create -d bridge mybridge
Enter fullscreen mode Exit fullscreen mode

Run the backend container by adding it to the bridge. Don’t forget to give a –name:

docker run -p 3001:3001 --name=backend --network=mybridge -d <DockerID>/backend
Enter fullscreen mode Exit fullscreen mode

Run the frontend container also by adding it to the bridge:

docker run -p 3000:3000 --name=frontend --network=mybridge -d <DockerID>/frontend
Enter fullscreen mode Exit fullscreen mode

The env variable on the frontend will be set to http://backend:3001/ and Hola! everything works.


Top comments (0)