DEV Community

panfan
panfan

Posted on

Docker - 基本的网络操作

实际上,大多数项目都将有一个或多个容器,这些容器需要相互通信。在这种情况下,Docker 提供了一些选项,以便容器可以相互通信。

假如现在有一个简单的应用程序,它由两个容器组成:一个 web 容器和一个数据库容器。web 容器需要与数据库容器通信,以便它可以从数据库中检索数据。

解决方案

  • 使用暴露的端口访问数据库容器
  • 使用 ip 和默认端口访问数据库容器

第一种方法设计从数据库容器中暴露端口,web 容器通过该端口连接,假设数据库容器的端口为 3306,那么 web 容器就可以通过 http://localhost:3306 访问数据库容器。

第二种方法使用 container inspect 命令来获取数据库容器的 IP 地址,然后使用该 IP 地址和默认端口访问数据库容器,假设数据库容器的 id 为 postgres,通过以下命令获得 IP 地址:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' postgres
# 172.17.0.2
Enter fullscreen mode Exit fullscreen mode

现在可以通过http://172.17.0.2:5432访问数据库容器。

两种方法都有缺点,因为它们都依赖于容器的 IP 地址,如果容器的 IP 地址发生变化,那么就需要更新 web 容器的配置。

正确的方式是放在一个网络中,这样就可以通过容器名称访问数据库容器,而不是通过 IP 地址。

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more