什么会阻止在 Docker 容器中运行的代码连接到单独服务器上的数据库?

2021-11-24 00:00:00 docker networking sql-server .net-core

我有一个 .NET Core 1.1 应用在 Ubuntu 14.04 上的 Docker 容器中运行,但它无法连接到在单独服务器上运行的 SQL Server 数据库.

I have a .NET Core 1.1 app running in a Docker container on Ubuntu 14.04, and it fails to connect to the SQL Server database running on a separate server.

错误是:

未处理的异常:System.Data.SqlClient.SqlException:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误.服务器未找到或无法访问.验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接.(提供者:TCP 提供者,错误:25 - 连接字符串无效)

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)

  1. 我在另一台 Ubuntu 14.04 服务器上使用相同的命令行部署了相同的映像,并且连接正常.
  2. 在问题服务器(Docker 外部)上运行的控制台应用可以使用相同的连接字符串进行连接.

就我从文档中看到的,在容器中运行的应用程序默认可以访问外部网络,那么是什么阻止了这种连接?

As far as I can see from the documentation, an app running in a container has access to the external network by default, so what could be blocking this connection?

推荐答案

运行在容器中的应用默认可以访问外网

an app running in a container has access to the external network by default

只有为容器分配了有效的 IP 地址,它才能访问.有时 Docker 为容器选择的 IP 会与外部网络发生冲突.

It could have access only if a valid IP address is assigned to the container. Sometimes the IP which Docker choose for the container can conflict with external networks.

默认情况下,容器运行在bridge网络中,所以看看它:

By default, containers run in bridge network, so look at it:

docker network inspect bridge

找到容器并检查其 IP.

Find the container and check its IP.

要解决冲突,可以自定义 bridge 网络并设置 bip 参数以更改网络的 IP 范围(配置文件位置取决于主机的操作系统):

To resolve conflicts, it is possible to customize bridge network and set bip parameter to change the network's IP range (config file location depends on host's OS):

"bip": "192.168.1.5/24"

或者创建一个新的docker网络.

Or create a new docker network.

或者尝试使用 net=host 选项:docker 运行网络设置

Or experiment with net=host option: docker run network settings

相关文章