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.
相关推荐
L汐8 分钟前
02 K8s双主安装
java·容器·kubernetes
shane-u26 分钟前
阿里云Docker镜像加速配置指南
阿里云·docker·云计算
斯文by累2 小时前
解锁DeepSeek潜能:Docker+Ollama打造本地大模型部署新范式
运维·docker·容器
lichuangcsdn4 小时前
【springcloud学习(dalston.sr1)】Eureka服务端集群的搭建(含源代码)(二)
学习·spring cloud·eureka
意倾城10 小时前
Docker数据卷
docker·容器
whgjjim10 小时前
docker迅雷自定义端口号、登录用户名密码
运维·docker·容器
爱吃芝麻汤圆14 小时前
k8s之Kubebuilder 的设计哲学
云原生·容器·kubernetes
裁二尺秋风15 小时前
k8s(12) — 版本控制和滚动更新(金丝雀部署理念)
云原生·容器·kubernetes
项目題供诗15 小时前
黑马k8s(六)
云原生·容器·kubernetes
Why not try?!18 小时前
Centos7 中 Docker运行配置Apache
运维·docker·容器