How to connect multiple Docker Containers?

How to connect multiple Docker Containers?

Docker networking is a complex problem for beginners and there is a lot to take.

You can easily start one container and access it using http://localhost:{port} but you can’t call a service running inside a container from another container.

Reason

Let’s assume you have two services: Data-Provider and Data-Consumer running on ports 8081 and 8082 respectively . If you try to call Data-Provider on 8081 from inside the Data-Consumer using http://localhost:8081 then it won’t able to connect on this port because localhost’s context is limited to Data-Provider container, and it won’t be able to see anything outside of it’s scope.

Same as you can’t call anything on other network using localhost. Right?

OK — so how do we fix this issue?

In order to fix this issue there are a couple of options:

1. Manual Docker Networking

To use this option, first we will create a network, and then connect both the containers to this network.

Below options will create and then attach the containers at the startup.

doker network create my-data-network
docker run --name=data-provider --net=my-data-network -p 8081:8081 data-provider-image
docker run --name=data-consuer --net=my-data-network -p 8082:8082 data-consumer-image

You can also use docker network connect command to connect to existing containers.

docker network connect my-data-network data-provider

2. Docker-Compose file

If you specify all the services in a docker file then docker-compose utility will automatically create a default network and put all the services in there.

However, it’s recommended to specify networks property and then use in all the services.

2.1 Networks Property

2.2 depends_on property

Another option is to use depends_on property. Although not strictly needed but this ensures all the applications are able to communicate automatically.

Finally

Now just go to your data-consumer application and use docker-provider hostname instead of localhost.

Before in data-consumer

http://localhost:8081

After in data-consumer

http://data-provider:8081

Also, look at my repo to get the working application.