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.
相关推荐
相顾若初见20 分钟前
Ansible部署k8s
容器·kubernetes·ansible
不灭的程序员阿澄12 小时前
在飞牛 NAS 上用 Docker 运行 DeepSeek Harness
运维·docker·容器
虎王物联13 小时前
Docker Compose编排物联网平台后端:Nginx+PHP-FPM+EMQX+InfluxDB一键部署实战
物联网·nginx·docker
林浅不想努力13 小时前
k8s集群部署的方法原理
云原生·容器·kubernetes
輝太くん14 小时前
k8s中的pod管理
云原生·容器·kubernetes
潘正翔15 小时前
k8s高级_调度器Deployment
linux·运维·云原生·容器·kubernetes·jenkins·devops
勇往直前plus16 小时前
Docker PostgreSQL 16 部署要点(Ubuntu 22)
ubuntu·docker·postgresql
angushine17 小时前
Docker部署镜像管理
运维·docker·容器
潘正翔17 小时前
jenkins构建cicd流水线
运维·服务器·ci/cd·容器·自动化·jenkins·cicd
Lost of 程序猿17 小时前
Kubernetes 排障实战:从 CrashLoopBackOff 到网络不通
网络·容器·kubernetes