Communication in Containers
We choose dockers because of isolation and separation. But no application is complete without communication. By communication, I mean APIs. Communication can be outside(web), localhost, or between containers.
Say we built an application with a database like MySQL, Django as backend, and React as frontend. When we containerize the app, we containerize the database/backend/frontend separately. That’s the practice, and in fact, hard to configure a container that does more than one task.
Overall this app needs to be communicated with the database-backend-frontend. Also, there comes the situation you need to communicate with a public API like a bank/government to fetch details. Therefore communication remains an integral part of any app and hence the environment technologies like dockers/containers.
When your container wants to communicate with any world wide web — we don’t need to reconfigure anything in container settings.
When you want to communicate with a local machine, replace ‘localhost’ in the URL with ‘host. docker. internal’.This is the use case primarily used in the development phase.
Communication between containers is the most widely used case because that is in alignment with the docker technology use case.
This communication can be done in two ways:
1)Manually find an IP address through the ‘inspect’ command and get the IP address. We can’t do it every time because containers are replaced and recreated. Hence the IP address will become dynamic, and every time we need to inspect to find the IP address
2)Using the Docker network command and putting all the containers in the same network. This can be done by
docker network create [network_name] docker run -network [network_name] -name [container_name_1] [image_name_1] docker run -network [network_name] -name [container_name_2] [image_name_2]
Here both containers will be on the same network. Use just container name for communication. Docker resolves IP address automatically.
Originally published at https://www.pansofarjun.com on May 10, 2022.