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.
相关推荐
姜鱼问生6 小时前
网页一片白?Docker 跑 Nginx 读不到文件,403 Forbidden 排查实录
nginx·docker·容器
\光辉岁月/7 小时前
2.spring5-IOC
java·容器·ioc·注解
ms72wx7 小时前
Docker 命令学习笔记:从入门到进阶的实战指南
笔记·学习·docker
java_logo7 小时前
Docker 部署 Excalidraw:轻松搭建手绘风格白板
运维·docker·容器·excalidraw·白板·轩辕镜像
海的透彻10 小时前
如何让docker容器启动时用自定义的用户
java·docker·dubbo
程序员清风11 小时前
LibreChat 实战:用 Docker 搭建可扩展的多模型对话平台
运维·docker·容器
Web3&Basketball12 小时前
从0到1落地AI Agent沙箱隔离Docker实战:踩坑全记录
运维·docker·容器·agent·容器安全·沙箱隔离
bluebonnet2712 小时前
【docker】使用regctl免安装docker下载镜像
运维·docker·容器
Java开发追求者1 天前
windows快速安装docker
windows·docker·安装·1024程序员节
骑着蜗牛撵大象3271 天前
飞牛fnOS部署Damselfly:Compose编排、照片目录与7100固定访问
java·docker·rpc·dubbo·fnos·照片管理·damselfly