Establishing Communication Between Docker Containers Via Hostname: Step-By-Step Guide
Step 1: Create A Docker network
- Firstly start with creating a Docker network with the following commands, If you need customization you do with using options.
docker network create my-network
Step 2: Run Two Containers On Created Network
- Created the two network with docker run command on providing network name, port numbers, Docker images and other options as follows:
docker run -d --name webserver -p 80 --network my-network nginx
docker run -d --name database -p 3306:3306 --network mysql
Step 3: Configuring The DNS In Docker Internals
- In the webserver container, add the docker.internal DNS to the list of known hosts.
- For making this use the following command:
echo "127.0.0.1 docker.internal" >> /etc/hosts
Step 4: Ping To Database Container
- In the webserver container, try to ping the database container.
- For ping to database container use the following command:
ping database
Step 5: Status Of Ping Command
- You should see that the ping is successful in the following screenshot.
Step 6: Communicating One Container With Other
- You can now communicate between the two containers using the hostname database.
How To Communicate Between Docker Containers Via “Hostname”?
In dealing with containers, Docker easily gets the place of a universal tool for both handling and development of applications. Docker containers are equivalent to isolated environments, therefore, the application of microservices architecture demands no further effort. Among the microservices principles, establishing the proper interaction between containers is a key container and Docker offers multiple tools to support communication between the containers. This article will focus on using hostnames from the host machine to facilitate communication between Docker containers. This will make it easier for users to communicate with various containers.
Contact Us