我无法将我的postgresql docker容器连接到.NET 6容器

tvmytwxo  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(3)|浏览(178)

我已经实现了一个应用程序与REST接口在C#上.NET 6.当URL被调用,然后从PostgreSQL数据库中获取数据并返回.应用程序是作为代码实现的第一.这意味着表是因为我的应用程序创建.这一切都工作到目前为止.
现在我尝试将应用程序和数据库分别放入Docker容器中并将它们连接在一起。为此,我有一个Dockerfile:

#build stage
FROM mcr.microsoft.com/dotnet/sdk:6.0 as build
WORKDIR /src
COPY . .
RUN dotnet restore "./Notification/Notification.csproj" --disable-parallel
RUN dotnet publish "./Notification/Notification.csproj" -c release -o /app --no-restore

#Serve stage
From mcr.microsoft.com/dotnet/sdk:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "Notification.dll"]

字符串
一个docker-compose.yaml:

version: '3'

networks:
  mynetwork:
    driver: bridge

services:

   notification:
      build: .
      ports:
      - "8080:80"
      - "8081:443"
      environment:
         ASPNETCORE_URLS: "https://+;http://+"
         ASPNETCORE_HTTPS_PORT: "8001"
         ASPNETCORE_Kestrel__Certificates__Default__Password: "1234"
         ASPNETCORE_Kestrel__Certificates__Default__Path: "/https/notification.pfx"
      volumes:
         - ${USERPROFILE}\.aspnet\https:/https/
      depends_on:
         - postgres
      networks:
         - mynetwork 

   postgres:
      image: postgres:9.6.21-alpine
      container_name: postgres
      ports:
      - "5432:5432"
      environment:
         - POSTGRES_USER=postgres
         - POSTGRES_PASSWORD=1234
         - POSTGRES_DB=mail
      networks:
         - mynetwork


我的C#应用程序中的AppSettings:

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "../Logs/log.txt" }
      }
    ]
  },
  "AllowedHosts": "*",
  "AppSettings": {
    "ConnectionStrings": {
      "MailDb": "Server=postgres; Database = mail;  User Id = postgres; Password = 1234"
    },
    "MailServers": [
      {
        "Type": "ethereal",
        "URL": "smtp.ethereal.email",
        "Port": 587
      }
    ],
    "SlackChannels": [
      {
        "Channel": "Slackbot",
        "URL": "https://hooks.slack.com/services/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"
      }
    ]
  }
}


我的Program.cs

using Microsoft.EntityFrameworkCore;
using Notification.Helper;
using Notification.Models;
using Notification.Service.EMail;
using NotificationService.Database;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

//Der ähnliche Code muss da stehen, da es ein anderes Objekt ist
var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .Build();

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .CreateLogger();

var appSettings = new AppSettings();
builder.Configuration.GetSection("AppSettings").Bind(appSettings);

// Add services to the container.
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddScoped<IMessageService, MessageService>();

builder.Services.AddDbContext<MailContext>(
    o => o.UseNpgsql(appSettings.ConnectionStrings.MailDb)
    );

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseAuthorization();
app.MapControllers();

app.Run();


当我运行docker-compose -f docker-compose.yaml up时,两个容器都设置好了。但是,在postgresql容器中没有创建表,只有数据库邮件。当我通过Swagger发送GET请求时,我得到以下错误消息:
失败:Microsoft. MicrosoftFrameworkCore.Database.Connection[20004] notification-notification-1|
使用与服务器“”上的数据库“mail”的连接时出错。
通知-通知-1|失败:Microsoft. faultyFrameworkCore.Query[10100]
通知-通知-1|循环访问上下文类型“NotificationService.Database. MailContext”的查询结果时发生异常。
Microsoft.AspNetCore.Server.Kestrel[13] notification-notification-1|连接ID“0 HMUMN 18 UPCED”,请求ID“0 HMUMN 18 UPCED:0000001”:应用程序引发了未处理的异常。
通知-通知-1| System.InvalidOperationException:引发了异常,可能是由于暂时性故障。
通知-通知-1|异常(0x 80004005):找不到网络连接所需的资源[::1]。

jdgnovmf

jdgnovmf1#

尝试将连接字符串更改为:“MailDb”:“服务器=postgres;数据库=邮件;用户ID = postgres;密码= 1234; TrustServerCertificate=True;”

js81xvg6

js81xvg62#

好吧,我是Docker的新手,刚开始学习它。这就是为什么这是一个愚蠢的错误。我删除了我的镜像,创建了一个新的镜像,并运行Docker compose。这解决了连接错误。然而,一个新的错误弹出:
:Microsoft. MicrosoftFrameworkCore.Database.Command[20102] notification-notification-1|执行DbCommand失败(43毫秒)[参数=[],CommandType =“Text”,CommandType =“30”] notification-notification-1| SELECT n.“NotificationId”,n.“Message”,n.“Platform”,n.“Message”,n.“SendDate”,n.“Message”,n.“Subject”notification-notification-1| FROM notification AS n notification-notification-1|失败:Microsoft. faultyFrameworkCore.Query[10100] notification-notification-1|迭代上下文类型“NotificationService.Database. MailContext”的查询结果时发生异常。notification-notification-1| Npgsql.PostgresException(0x 80004005):数据库“notification”不存在
这可能是因为数据库没有被迁移。如果有人能告诉我们如何做到这一点,那就太好了,但我认为这样就解决了连接问题

p5cysglq

p5cysglq3#

但是,postgresql容器中不会创建表,只会创建数据库邮件。
您还没有将migrations应用到数据库中。您可以通过编程的方式完成此操作,如下所示:
第一个月
更多的Ways to run your Migrations
因此,在您的情况下,它将是:

using (var scope = app.Services.CreateScope())
{
    var _context= scope.ServiceProvider.GetRequiredService<MailContext>();

    _context.Database.Migrate();
}

字符串

相关问题