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.
相关推荐
转身後 默落2 小时前
11.Docker 之分布式仓库 Harbor
分布式·docker·容器
菩提云3 小时前
Deepseek存算分离安全部署手册
人工智能·深度学习·安全·docker·容器
c无序10 小时前
Docker-技术架构演进之路
docker
努力的小T13 小时前
使用 Docker 部署 Apache Spark 集群教程
linux·运维·服务器·docker·容器·spark·云计算
东风微鸣15 小时前
TTRSS 迁移实战
docker·云原生·kubernetes·可观察性
Smile_Gently16 小时前
Docker
云原生·eureka
转身後 默落16 小时前
04.Docker 镜像命令
docker·容器·eureka
IT_张三17 小时前
Docker+Kubernetes_第一章_Docker入门
java·docker·kubernetes
jessezappy17 小时前
记录:Docker 安装记录
docker·安装·ollama·软链接
三天不学习17 小时前
如何在 Ubuntu 上安装 Docker:详细步骤指南
ubuntu·docker·eureka