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.
相关推荐
Dontla1 小时前
Docker run --add-host参数解析(在容器启动时向/etc/hosts文件中添加自定义的主机名与IP映射)(适用于临时调试或测试)
tcp/ip·docker·容器
西西小飞龙1 小时前
Docker和K8S中pod、services、container的介绍和关系
docker·容器·kubernetes
元气满满的热码式1 小时前
Docker数据卷操作实战
linux·运维·docker·云原生·容器
kngines1 小时前
【实战 ES】实战 Elasticsearch:快速上手与深度实践-1.3.1单节点安装(Docker与手动部署)
大数据·elasticsearch·docker
飞火流星0202713 小时前
docker安装etcd:docker离线安装etcd、docker在线安装etcd、etcd镜像下载、etcd配置详解、etcd常用命令、安装常见问题总结
docker·容器·etcd
magrich14 小时前
Docker usage on ubuntu
ubuntu·docker·容器
ZZDICT18 小时前
两台互通的服务器使用Docker部署一主两从MySQL8.0.35
运维·服务器·mysql·docker
程序员没睡醒19 小时前
【小白友好】Docker 入门详解:从零开始学“应用集装箱”
docker·容器·eureka