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.
相关推荐
藥瓿亭3 小时前
K8S认证|CKS题库+答案| 9. 网络策略 NetworkPolicy
linux·运维·docker·云原生·容器·kubernetes·cks
955.3 小时前
k8s从入门到放弃之Pod的容器探针检测
云原生·容器·kubernetes
LFloyue3 小时前
Linux离线(zip方式)安装docker
linux·docker
yunken284 小时前
docker容器保存为不依赖基础镜像的独立镜像方法
java·docker·容器
langmeng1105 小时前
使用docker在3台服务器上搭建基于版本redis 6.x的一主两从模式
运维·redis·docker·容器·集群
leblancAndSherry6 小时前
Gitlab + Jenkins 实现 CICD
linux·运维·docker·kubernetes·gitlab·jenkins
脑瓜嗡9 小时前
Docker部署SpringBoot项目
spring boot·docker·容器
容器魔方10 小时前
KubeCon China 2025 | 与KubeEdge畅聊毕业经验与创新未来
云原生·容器·云计算
杨浦老苏11 小时前
自托管图书搜索引擎Bookologia
docker·群晖·电子书
代码小学僧12 小时前
通俗易懂:给前端开发者的 Docker 入门指南
前端·docker·容器