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.
相关推荐
隔窗听雨眠5 小时前
生产级Kubernetes集群部署完全指南:从kubeadm到高可用架构落地
容器·架构·kubernetes
小小洋洋5 小时前
OpenWrt 从U盘迁移到内置 eMMC,并完成扩容与 Docker 安装
java·docker·eureka
Eloudy6 小时前
docker build 与 docker buildx build 的应用场景
docker·构建
瞬间&永恒~6 小时前
【Docker】(三)联合文件系统UnionFS + Overlay2
docker·云原生·容器
数据知道9 小时前
主机入侵检测(HIDS):OSSEC / Wazuh 部署与规则编写
安全·网络安全·docker
逐光老顽童10 小时前
第 5 章:搞懂 K8s Service:从 ClusterIP 到负载均衡
docker·云原生·容器
花生了什么事o12 小时前
Docker 部署 SpringBoot:从镜像构建到服务器运行
服务器·spring boot·docker
Eloudy12 小时前
国内加速 docker pull 下载 docker images,特别是 nvidia 的cuda image
docker·gpu·rdma
Chief_fly12 小时前
ARM 麒麟系统服务器构建docker镜像
运维·服务器·docker
yj_xqj1 天前
Docker 基础应用与介绍
运维·docker·容器