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.
相关推荐
tonngw1 小时前
【Mac 从 0 到 1 保姆级配置教程 16】- Docker 快速安装配置、常用命令以及实际项目演示
macos·docker·容器·开源·github·docker desktop·orbstack
debug 小菜鸟3 小时前
浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)
docker·云计算·aws
SpikeKing4 小时前
Server - 使用 Docker 配置 PyTorch 研发环境
pytorch·docker·llm
movie__movie5 小时前
Eureka REST 相关接口
eureka·注册中心
斯普信云原生组5 小时前
Docker构建自定义的镜像
java·spring cloud·docker
2201_761199045 小时前
k8s4部署
云原生·容器·kubernetes
小柏ぁ6 小时前
calico/node is not ready: BIRD is not ready: BGP not established with xxx
运维·docker·kubernetes
三劫散仙7 小时前
kubernetes jenkins pipeline优化拉取大仓库性能指定分支+深度
容器·kubernetes·jenkins
西京刀客7 小时前
k8s热更新-subPath 不支持热更新
云原生·容器·kubernetes·configmap·subpath
weixin_434936287 小时前
k8S 命令
linux·容器·kubernetes