.NET 8.0 / EF Core 在 Docker 中更新数据库

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

如何在docker SQL Server中完成数据库迁移? Dockerfile 由 IDE 生成。我需要在该 DockerFile 中添加数据库迁移。另外,我需要在 docker 之外公开 Swagger url。我的项目基于.NET 8.0。

这是 DockerFile:

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["QWiz.csproj", "."]
RUN dotnet restore "./QWiz.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./QWiz.csproj" -c $BUILD_CONFIGURATION -o /app/build

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

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "QWiz.dll"]
docker docker-compose dockerfile .net-8.0 asp.net-core-8
1个回答
0
投票

Ola,fiz um projeto que faz exatamente isso,coloquei no meu github pode dar uma olhada。 https://github.com/LeonardoQueres/Integration-Docker---.NET---SQL-SERVER

没有 arquivo 程序。cs adicione a linha de codigo abaixo

builder.Services.AddHttpsRedirection(options =>
{
    options.RedirectStatusCode = Status308PermanentRedirect;
    options.HttpsPort = 3001;
});

在此输入图片描述

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();

    var application = app.Services.CreateScope().ServiceProvider.GetRequiredService<ApplicationDbContext>();

    // Utilizando o migration a execução do container docker não é necessario as linhas abaixo
    var pendingMigrations = await application.Database.GetPendingMigrationsAsync();
    if (pendingMigrations != null)
        await application.Database.MigrateAsync();
}

在此输入图片描述

Atualize seu arquivo dockerfile 确认 codigo abaixo adicionando 作为 linhas 进行迁移

# Esta fase é usada durante a execução no VS no modo rápido (Padrão para a configuração de Depuração)
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 3000
EXPOSE 3001


# Esta fase é usada para compilar o projeto de serviço
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["project/project.csproj", "project/"]
COPY ["Thunders_Repositories/Thunders_Repositories.csproj", "Thunders_Repositories/"]
COPY ["Thunders_Borders/Thunders_Borders.csproj", "Thunders_Borders/"]
COPY ["Thunders_UseCases/Thunders_UseCases.csproj", "Thunders_UseCases/"]
RUN dotnet restore "./project/project.csproj"
COPY . .
WORKDIR "/src/project"
RUN dotnet tool install --global dotnet-ef 
ENV PATH="$PATH:/root/.dotnet/tools"
RUN dotnet build "./project.csproj" -c $BUILD_CONFIGURATION -o /app/build
CMD dotnet ef database update --environment Development --project src/project_Repositories

# Esta fase é usada para publicar o projeto de serviço a ser copiado para a fase final
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./project.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# Esta fase é usada na produção ou quando executada no VS no modo normal (padrão quando não está usando a configuração de Depuração)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "project.dll"]

O codigo abaixo pertence a docker-compose, atualize o seu conne necessidade.

services:
  project:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_HTTP_PORTS=3000
      - ASPNETCORE_HTTPS_PORTS=3001
    container_name: project
    image: ${DOCKER_REGISTRY-}project
    build:
      context: .
      dockerfile: project/Dockerfile   
    ports:
      - "3000:3000"
      - "3001:3001"
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro
    networks:
      - compose-bridge
    depends_on:
      sqlserver:
        condition: service_healthy

  sqlserver:
    image: mcr.microsoft.com/mssql/server:2022-preview-ubuntu-22.04
    container_name: sqlserver    
    ports:
      - "1433:1433"
    environment:
      - SA_PASSWORD=passwork 'não pode ser uma senha fraca, sql nao funciona. nada de usar 123456 hehehehe'
      - ACCEPT_EULA= Y       
    volumes:
      - ./sqlserver/data:/var/opt/mssql/data
      - ./sqlserver/log:/var/opt/mssql/log   
    networks:
      - compose-bridge 
    healthcheck:
      test: /opt/mssql-tools/bin/sqlcmd -S localhost -U SA -P "leoQueres123" -Q "SELECT 1" -b -o /dev/null
      interval: 10s
      timeout: 3s
      retries: 10
      start_period: 10s  

volumes: 
  sqlserver:

networks:
  compose-bridge:
    driver: bridge
  

Espero ter ajudado。

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