docker-compose如何在容器之间通信?

huangapple go评论58阅读模式
英文:

How docker-compose communicate between containers?

问题

I would like to communicate between two containers. I've read that networks should be configured either locally or in bridge mode. However, in this example below, adminer has access to mysql, but no network were configured.

我想要在两个容器之间进行通信。我已经阅读到networks应该在本地或桥接模式下进行配置。然而,在下面的示例中,adminer可以访问mysql,但没有配置网络。

I tried to add another service ubuntu, install nmap, and docker-compose run ubuntu nmap 127.0.0.1, but MySQL isn't accessible. How does adminer can reach db container in this example?

我尝试添加另一个服务 ubuntu,安装 nmap,并运行 docker-compose run ubuntu nmap 127.0.0.1,但是无法访问 MySQL。在这个示例中,adminer如何能够访问 db 容器?

英文:

I would like to communicate between two containers. I've read that networks should be configured either locally or in bridge mode. However, in this example below, adminer has access to mysql, but no network were configured.

I tried to add another service ubuntu install nmap and docker-compose run ubuntu nmap 127.0.0.1, but MySQL isn't accessible. How does adminer can reach db container in this example?

version: '3.1'

services:

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

  db:
    image: mysql:5.6
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: example

答案1

得分: 2

在这个示例中,"adminer" 容器可以在不配置网络的情况下访问 db 容器,因为它们都在由docker-compose创建的同一默认网络中定义。docker-compose会自动为在同一docker-compose.yml文件中定义的容器创建一个桥接网络。

当容器连接到同一网络时,它们可以使用其服务名称作为主机名相互通信。在这种情况下,adminer容器可以通过使用主机名"db"作为MySQL服务器地址来访问db容器。

关于ubuntu服务和使用nmap扫描127.0.0.1,这将不起作用,因为127.0.0.1指的是ubuntu容器本身的环回接口。它无法使用127.0.0.1访问db容器。如果您想测试容器之间的网络连通性,应该在同一网络中使用服务名称或容器名称作为主机名。

英文:

In this example, the "adminer" container can reach out the db container without configuring a network because they are both defined within the same default network created by docker compose. docker-compose automatically creates a bridge network for the containers defined in the same docker-compose.yml file.

When containers are connected to the same network, they can communicate with each other using their service names as hostnames. In this case, the adminer container can reach the db container by using the hostname db as the MySQL server address.

Regarding the ubuntu service and using nmap to scan 127.0.0.1, it will not work because 127.0.0.1 refers to the loopback interface of the ubuntu container itself. It won't be able to reach the db container using 127.0.0.1. If you want to test network connectivity between containers, you should use the service names or container names as hostnames within the same network.

huangapple
  • 本文由 发表于 2023年5月25日 22:32:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定