乐闻世界logo
搜索文章和话题

How to reach docker containers by name instead of IP address?

1个答案

1

To access Docker containers by name instead of IP address, we can utilize Docker's built-in networking features, particularly user-defined networks. This approach enables containers to communicate with each other using their names rather than IP addresses, simplifying network configuration and making service interconnection more intuitive. Below are the specific steps:

Step 1: Create a User-Defined Network

First, we need to create a user-defined network. Docker offers several network types, but the bridge type is the most commonly used. We can create a network named my-network using the following command:

bash
docker network create --driver bridge my-network

This command establishes a bridge type network named my-network.

Step 2: Start Containers and Connect to the Network

Next, we need to start the containers and connect them to the newly created network. Suppose we want to start two containers: one running a Redis service and another running a web application. We can do this as follows:

bash
docker run -d --name redis-server --network my-network redis docker run -d --name my-web-app --network my-network my-web-image

Here, the redis-server container runs the Redis service, and the my-web-app container runs our web application. Both containers are connected to the my-network network.

Step 3: Communicate Using Container Names

Once all containers are connected to the same network, they can communicate with each other using container names. For example, if my-web-app needs to connect to redis-server to retrieve data, it can simply use redis-server as the hostname. In the web application's configuration, we can set the Redis address as:

plaintext
REDIS_HOST=redis-server

Example Demonstration

Suppose we have a Python web application that needs to connect to a Redis server. In the Python code, we can connect to Redis using the following approach:

python
import redis r = redis.Redis(host='redis-server', port=6379)

Since both containers are on the same network my-network, redis-server will be resolved to the IP address of the Redis container.

Summary

By leveraging Docker's user-defined networks, we can easily communicate between containers using container names instead of IP addresses. This method significantly simplifies network configuration and makes service interconnection more straightforward and manageable.

2024年8月12日 19:48 回复

你的答案