Basic - Part 3
Containers network communication
Container to Internet
An application running inside of a container might need to send HTTP requests to an API or another website on the Internet. For that, we need our container to be able to communicate with the World Wide Web!
By default, containers can send request to the Internet. For example, to communicate with an external API. No special setting is needed.
Container to localhost
An app running in a container sometime need to communicate with a database, web server or any other services running on our localhost.
In the example below an API running inside of a container try to reach a database running on port 27017 on localhost. However, the code as shown below won't work.
localhost
needs to be replaced byhost.docker.internal
Using this address our application can talk to a service running on our localhost. Docker will transform this address to our IP localhost.
host.docker.internal
Container to container
Method 1 - Hard coding the IP address
Best practices is to use different containers for the application and database it connects to. When developing an application each container should have its own purpose.
We can run a simple mongodb container based on the Official Docker image with this command.
Every container get provided an IP address. To see the IP address of a container run:
This IP address can be use by containers to communicate with another container. For example, if we want our API (inside a container) to communicate with the MongoDB database (inside another container), we can specify the IP address in the source code where the API connects with the database. Port 27017 is the default port of MongoDB.
Method 2 - Network containers
A very useful way for containers to communicate within each others is creating an network and attach all containers to the network.
To create a network
Running a container inside a network
In the command below, the two containers movieapp
and mongodb
will run in the same network and could talk with each other.
To make sure that both containers can talk to each other, we just need to specified the URL with the name of the container we want the API to communicate with. The name of the container can be used as "IP address".
Cross communication between containers does not require to expose any specific ports. Creating a network will ensure all containers can freely communicate with each other.
Last updated