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.
相关推荐
Wzx1980121 天前
doker深学习
学习·docker
好奇心害死薛猫1 天前
docker_tailscale
docker·容器
一只懒鱼a1 天前
docker部署nacos (版本2.3.2)
运维·docker
青衫客361 天前
浅谈Kubernetes在systemd cgroup模式下的Slice/Scope组织结构
云原生·容器·kubernetes
王九思1 天前
Podman 介绍
docker·云原生·kubernetes·podman
运维螺丝钉1 天前
docker安装应用
运维·docker·容器
optimistic_chen1 天前
【Docker入门】cgroups 资源控制
linux·运维·ubuntu·docker·容器·cgroup
林九生1 天前
【MySQL/PostgreSQL】MySQL 到 PostgreSQL 数据迁移:Docker + pgloader
mysql·docker·postgresql
芥子沫1 天前
书签管理工具使用:Readeck-Docker部署和使用技巧
运维·docker·容器·书签管理
ba_pi1 天前
每天写点什么2026-01-19-docker如何使用GPU
运维·docker·容器