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.
相关推荐
木易双人青6 小时前
01-Docker-简介、安装与使用
运维·docker·容器
罗不俷11 小时前
【RH134知识点问答题】第13章:运行容器
容器·rhel
AI大模型13 小时前
基于 Docker 的 LLaMA-Factory 全流程部署指南
docker·llm·llama
春人.13 小时前
PortainerCE 跨云管理:cpolar 内网穿透服务实现多环境统一控制
云原生·eureka
tb_first15 小时前
k8sday11服务发现(2/2)
docker·云原生·容器·kubernetes·k8s
发愤图强的羔羊15 小时前
Docker 搭建 SVN 服务器
docker
为了摸鱼而战15 小时前
Dockerfile知识点梳理,你要搞懂的都在这
docker
Clownseven16 小时前
Docker+Nginx+Node.js实战教程:从零搭建高可用的前后端分离项目
nginx·docker·node.js
zxcxylong16 小时前
almalinux9.6系统:k8s可选组件安装(1)
云原生·容器·kubernetes·metrics·almalinux·hpa·vpa
MANONGMN1 天前
Kubernetes(K8s)常用命令全解析:从基础到进阶
云原生·容器·kubernetes