无法从其他Docker容器连接到Docker中的PostgreSQL

irlmq6kh  于 2023-08-03  发布在  Docker
关注(0)|答案(2)|浏览(176)

我有两个Docker容器,如下所示。我可以通过net6.0 C#控制台应用程序调用Test.Main()方法连接到docker中的PostgreSQL。但是当我尝试从ASP.NET docker容器调用Test.Main()时,我无法连接到PostgreSQL并获得异常Failed to connect to 127.0.0.1:5432

{Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432
 ---> System.Net.Sockets.SocketException (111): Connection refused
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|215_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.<Get>g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()
   at APIDA.DBModels.Test.Main() in Version.cs:line 34}

个字符
ASP.NET DockerFile是

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

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

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

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

测试.主

public class Test
{
    public static void Main()
    {
        string connectionString = "Host=127.0.0.1;Database=postgres;Username=postgres;Password=xxxxx";

        // Create a new PostgreSQL connection
        using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
        {
            try
            {
                // Open the connection
                connection.Open();

                // Check if the connection is open
                if (connection.State == System.Data.ConnectionState.Open)
                {
                    Console.WriteLine("Connected to PostgreSQL!");

                    // Perform your database operations here

                    // Close the connection when you're done
                    connection.Close();
                    Console.WriteLine("Connection closed.");
                }
                else
                {
                    Console.WriteLine("Failed to open the connection.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }

        Console.ReadLine();
    }
}

ogq8wdun

ogq8wdun1#

正如错误消息中提到的,您的应用程序尝试连接到localhost:

{Npgsql.NpgsqlException (0x80004005): Failed to connect to 127.0.0.1:5432
 ---> System.Net.Sockets.SocketException (111): Connection refused
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|215_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.OpenNewConnector(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.PoolingDataSource.<Get>g__RentAsync|28_0(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|45_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()
   at APIDA.DBModels.Test.Main() in Version.cs:line 34}

字符串
数据库在不同的docker中,其IP与127.0.0.1不同。你必须使用URL:

gb-postgres:5432


连接到数据库,其中gb-postgres是运行postgresql的docker的名称。

yptwkmov

yptwkmov2#

对于在容器中运行的应用程序,127.0.0.1将是容器本身,显然没有运行数据库示例。处理这个问题的一种方法是在同一个docker网络中运行两个容器,并使用名称解析(即Host=gb-postgres;Port=5432;),最简单的方法是使用docker-compose-see this answer
如果您的主机操作系统(运行docker的操作系统)是Windows,您可以使用host.docker.internal来访问容器外部,即Host=host.docker.internal;Port=5432;(不确定Linux上是否支持开箱即用,但肯定有workarounds

相关问题