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.
相关推荐
胡八一1 小时前
解决k8s拉取私有镜像401 Unauthorized 问题
云原生·容器·kubernetes
筑梦之路1 小时前
银河麒麟v10 x86架构二进制方式kubeadm+docker+cri-docker搭建k8s集群(证书有效期100年) —— 筑梦之路
docker·容器·kubernetes
不撸先疯。3 小时前
docker镜像源配置、换源、dockerhub国内镜像最新可用加速源(仓库)
运维·docker·容器·dockerhub
Stark-C4 小时前
功能齐全,支持协作 | Docker部署一款支持多人共享的私密浏览器『n.eko』
运维·docker·容器
it噩梦4 小时前
使用EFK收集k8s日志
容器·kubernetes
库库的里昂5 小时前
Linux系统Docker部署开源在线协作笔记Trilium Notes与远程访问详细教程
linux·运维·docker·开源
yunfanleo5 小时前
Docker 容器自动启动设置
云原生·eureka
winfredzhang5 小时前
解决 Docker Desktop 启动报错:Docker Desktop is unable to detect a Hypervisor
docker·desktop·报错解决
右恩7 小时前
Docker 实践与应用举例
python·docker
JunLan~13 小时前
Rocky Linux 系统安装/部署 Docker
linux·docker·容器