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.
相关推荐
独隅9 分钟前
PyTorch 模型部署的 Docker 配置与性能调优深入指南
人工智能·pytorch·docker
赵丙双20 分钟前
多网卡微服务注册 IP/host 问题
微服务·eureka·nacos·consul·多网卡
yuzhuanhei3 小时前
docker常用命令
运维·docker·容器
我叫张小白。3 小时前
Dify系列(一):平台安装部署+界面操作
docker·ai·语言模型·大模型·dify·智能体
anarckk3 小时前
docker volume 导入导出命令
运维·docker·容器
Brandon汐4 小时前
从0开始搭建一主两节点k8s集群对接Ceph集群
ceph·容器·kubernetes
杨浦老苏4 小时前
音乐和有声读物播放器AudioDock
docker·群晖·多媒体·音乐·有声读物
青春不流名4 小时前
Portainer CE(社区版)部署 & 运行
云原生·eureka