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.
相关推荐
用户13573999256602 小时前
Windows 从 0 搭建 WSL2 原生 AI 开发环境:Codex + Docker + VSCode
docker
vi_h3 小时前
在 macOS 上通过 Docker 安装并运行 Ollama(详细可执行教程)
macos·docker·ollama
黑心老魔4 小时前
通过 Docker 创建开发环境
docker·开发环境
冬奇Lab17 小时前
一天一个开源项目(第41篇):Workout.cool - 现代化开源健身教练平台,训练计划与进度追踪
docker·开源·资讯
天朝八阿哥1 天前
使用Docker+vscode搭建离线的go开发调试环境
后端·docker·visual studio code
阿虎儿2 天前
Docker安装(非sudo用户可用)
docker
fetasty3 天前
rustfs加picgo图床搭建
docker
蝎子莱莱爱打怪4 天前
GitLab CI/CD + Docker Registry + K8s 部署完整实战指南
后端·docker·kubernetes
小p5 天前
docker学习7:docker 容器的通信方式
docker
小p5 天前
docker学习5:提升Dockerfile水平的5个技巧
docker