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.
相关推荐
engchina5 小时前
WSL Ubuntu で Kubernetes v1.34.2 + Docker 環境を構築する
ubuntu·docker·kubernetes
大雨淅淅9 小时前
Eureka从入门到精通:开启微服务架构的钥匙
微服务·云原生·eureka·架构
oMcLin9 小时前
2025年必备的Docker命令指南与实战示例
docker·容器·eureka
qq_404643349 小时前
Eureka 核心概念
微服务·eureka
AtoposのCX3309 小时前
Docker运行hello-world镜像失败或超时
运维·docker
码字的字节9 小时前
Spring Cloud服务注册与发现(一):手把手搭建Eureka Server,详解高可用配置
spring·spring cloud·eureka
sun cat9 小时前
Docker详细介绍(6)
docker·容器·docker-compose
AI架构全栈开发实战笔记9 小时前
Eureka 在大数据环境中的性能优化技巧
大数据·ai·eureka·性能优化
大厂资深架构师9 小时前
Spring Cloud Eureka在后端系统中的服务剔除策略
spring·spring cloud·ai·eureka
AI架构全栈开发实战笔记9 小时前
Eureka 对大数据领域服务依赖关系的梳理
大数据·ai·云原生·eureka