Allow two Docker containers to communicate with each other

To allow two Docker containers to communicate with each other, you can use a Docker network. Here's how to set it up:

Step 1: Create a Docker Network

First, create a user-defined network. This allows containers on the network to communicate with each other by their container names.

docker network create my_network

Step 2: Run Containers on the Same Network

When starting each container, specify the network you created.

For example:

docker run -d --name container1 --network my_network my_image1 docker run -d --name container2 --network my_network my_image2

Now, container1 and container2 are both on my_network and can communicate.

Step 3: Access Each Other by Container Name

Within container1, you can access container2 by its name, container2, and vice versa. For instance, you could use ping:

docker exec -it container1 ping container2

Or connect through a service port (e.g., for HTTP):

curl http://container2:port

Additional Tips:

  • Ports: If your containers expose services on specific ports (e.g., HTTP on port 80), make sure those services are listening on the correct port within the container.
  • DNS Resolution: Docker's network handles the DNS resolution automatically, so using container names as hostnames works seamlessly in user-defined networks.
  • Inspect Network : Run docker network inspect my_network to verify that both containers are connected.
相关推荐
亚空间仓鼠7 小时前
Docker容器化高可用架构部署方案(六)
docker·容器·架构
前端老曹7 小时前
Docker 从入门到放弃:完整指南
运维·docker·容器
咖啡里的茶i8 小时前
在Docker环境中安装Hadoop cluster 实验报告一
hadoop·docker·容器
汪汪大队u8 小时前
续:从 Docker Compose 到 Kubernetes(2)—— 服务优化与排错
网络·后端·物联网·struts·容器
rabbit_pro9 小时前
Docker compose部署Ollama使用模型
linux·运维·docker
ILL11IIL9 小时前
k8s的pod管理及优化
云原生·容器·kubernetes
咖啡里的茶i10 小时前
在Docker环境中安装Hadoop cluster 实验报告三
docker
笑洋仟10 小时前
docker的overlay2目录占用磁盘空间很大,清理办法
运维·docker·容器
木雷坞11 小时前
2026 年 5 月国内可用 Docker 镜像源列表与配置方法
运维·docker·容器
咖啡里的茶i13 小时前
从云端数据分析平台数据图实验报告
docker