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.
相关推荐
tzhou6445216 小时前
Docker 部署 Nginx HTTPS 服务(CentOS 7)
nginx·docker·https
iconball16 小时前
个人用云计算学习笔记 --32 Docker和docker swarm
运维·笔记·学习·docker·容器·云计算
摇滚侠16 小时前
镜像容器相关命令,docker export/import/save/load/commit,导出容器给别人使用
运维·docker·容器
逸巽散人17 小时前
云边协同:基于 Docker 与 FRP 的家庭实验室全栈内网穿透指南
云原生·eureka
回忆是昨天里的海17 小时前
docker Compose-安装wordpress
运维·docker·容器
key2world17 小时前
Dockerfile 制作镜像和推送
docker·dockerfile·docker push
我可以将你更新哟17 小时前
【linux】配置 Docker 国内镜像源, centos7安装docker-ce,docker相关命令,永久配置 DNS
linux·运维·docker
云雾J视界17 小时前
年终复盘2.0:NLP自动萃取经验教训,构建可执行策略库
人工智能·docker·nlp·复盘·技术架构·工业级设计
machunlin~18 小时前
centos 系统安装相关
linux·运维·docker·centos
孤岛悬城18 小时前
47 Dockerfile场景化:公司内网业务上线(分角色/分模块)
docker·容器·云计算