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.
相关推荐
LaughingZhu1 小时前
Product Hunt 热榜 2026-12-05:SoduWork、finerd split、Otari by Mozilla AI
java·人工智能·docker·chatgpt·容器
小敬爱吃饭4 小时前
PgHero轻量PostgreSQL监控:Docker部署、连接统计与执行计划
数据库·docker·postgresql
遨游DATA6 小时前
容器退出码 126 排查:静态资源镜像层如何改写目录权限
linux·docker·kubernetes·文件权限
有个傻瓜6 小时前
容器里时间凭空差 8 小时:naive 与 aware 时区混用排错复盘与四种方案实测
python·docker·springboot·时区排错·naive/aware
江湖有缘10 小时前
Anchor私有化部署实战:Docker搭建专属个人笔记服务
笔记·docker·容器
吴声子夜歌12 小时前
Kubernetes进阶实战——Ingress与服务发布(二)
云原生·容器·kubernetes
万里侯14 小时前
生产环境故障自愈的审计溯源:构建基于区块链或不可篡改日志的自愈证据链
人工智能·微服务·ai·容器·k8s
Decay__15 小时前
配置与密钥管理 —— ConfigMap、Secret、热更新边界与 KMS 加密
运维·云原生·容器·kubernetes·k8s
奔跑的大白啊15 小时前
对比Dockerfile的copy和docker cp的区别
docker·容器·copy·docker cp·复制文件
جيون داد ناالام ميづ15 小时前
【MQ与中间件】容器内Java服务发不出邮件:docker network connect与JVM的DNS负缓存
java·docker·中间件