如何让docker容器从外部“看到”主机

问题描述 投票:0回答:1

我在 .NET 8 中有一个 API,它是一个在虚拟机内运行的 Docker 容器,内部 IPv4 地址为 1.1.1.1(例如)。

这个API使用MySQL 8.0.33数据库,这是我的连接字符串:

"ConnectionStrings": {
    "MySQL": "Server=1.1.1.1;Port=3306;initial catalog=db_namel;uid=my-user;pwd=my-pass"
  }

当我在本地运行 API 时(通过将“Server”字段值更改为“localhost”),一切正常。当我对 API 进行 dockerize 并在 Linux 服务器 (Ubuntu 22.04) 中运行它时,就会出现问题。

这是我的 Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["Presentation.Web/Presentation.Web.csproj", "Presentation.Web/"]
RUN dotnet restore "Presentation.Web/Presentation.Web.csproj"
COPY . .
WORKDIR "/src/Presentation.Web"
RUN dotnet build "Presentation.Web.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Presentation.Web.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Presentation.Web.dll"]

当我在 Ubuntu 服务器上为 API 创建容器时,我收到以下错误:

An error occurred using the connection to database '' on server '1.1.1.1'.
Unhandled exception. System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySql' call.
 ---> MySqlConnector.MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.

为了尝试解决该问题,我通过以下命令创建了一个新的

my-user

CREATE USER 'my-user'@'localhost' IDENTIFIED BY 'my-user';

GRANT ALL PRIVILEGES ON *.* TO 'my-user'@'localhost' WITH GRANT OPTION;

FLUSH PRIVILEGES;

值得一提的是,在我的服务器内(通过 SSH),我可以使用命令

mysql -u my-user -p
连接到数据库,没有任何问题。

后来,我删除了 my-user 并尝试使用服务器的内部 IP 地址再次创建它:

CREATE USER 'my-user'@'1.1.1.1' IDENTIFIED BY 'my-user';

GRANT ALL PRIVILEGES ON *.* TO 'my-user'@'1.1.1.1' WITH GRANT OPTION;

FLUSH PRIVILEGES;

正如你所想,这也行不通。

我研究了这个问题,并认为它可能与 Docker 网络有关,因为 根据这个答案,“Docker 网络仅用于容器到容器的通信”。我的问题是:如何让我的容器正确“看到”我的连接字符串?

docker
1个回答
0
投票

我找到了答案。我只需要将连接字符串更改为

localhost
,例如:

"ConnectionStrings": {
    "MySQL": "Server=localhost;Port=3306;initial catalog=db_namel;uid=my-user;pwd=my-pass"
  }

我需要将

--net=host
添加到 docker run 命令,如下所示:

docker run -p 8080:8080 --net=host my-image

这样做,一切正常!

© www.soinside.com 2019 - 2024. All rights reserved.