我一直在为将ASP Dotnet应用程序做成Docker容器的问题而苦恼。我已经在StackOverflow上寻找了很长时间,但没有成功。
基本上,我要实现的目标是在Docker容器中运行我的ASP Dotnet应用程序(MVC API),并且我也希望我的Postgresql实例在同一个网络中运行。
我创建了一个像这样的docker-compose文件:
version: '3'
networks:
asp-dotnet-network:
driver: bridge
services:
postgres:
image: postgres:9.6.21-alpine
container_name: postgres
ports:
- "5433:5432"
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=postgres
networks:
- asp-dotnet-network
app:
build: ../.
container_name: app
ports:
- "5000:5000"
- "5001:5001"
environment:
- ConnectionStrings__Default=Host=postgres;Username=postgres;Port=5432;Password=postgres;Database=postgres;Pooling=true;
depends_on:
- postgres
networks:
- asp-dotnet-network
我的 Dockerfile 如下所示
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /app
COPY *.sln .
COPY Data/Data.csproj ./Data/
COPY Application/Application.csproj ./Application/
COPY WebApi/WebApi.csproj ./WebApi/
RUN dotnet restore
COPY Data/. ./Data/
COPY Application/. ./Application/
COPY WebApi/. ./WebApi/
WORKDIR /app/WebApi
RUN dotnet publish -c Release -o out
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS runtime
WORKDIR /app
COPY --from=build /app/WebApi/out ./
ENTRYPOINT ["dotnet", "WebApi.dll"]
最后,我已经配置了我的主要应用程序以接受环境变量,这样我就可以覆盖appsettings:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("appsettings.json").
AddJsonFile($"appsettings.docker.json", true).AddEnvironmentVariables();
});
当我在包含docker-compose.yml文件的目录中运行
docker-compose up --build && docker-compose logs -f
命令时,应用程序容器会发生以下错误:app | fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
app | An error occurred using the connection to database 'postgres' on server 'tcp://postgres:5432'.
app | fail: Microsoft.EntityFrameworkCore.Query[10100]
app | An exception occurred while iterating over the results of a query for context type 'DatabaseContext'.
app | System.InvalidOperationException: An exception has been raised that is likely due to a transient failure.
app | ---> Npgsql.NpgsqlException (0x80004005): Exception while connecting
app | ---> System.Net.Sockets.SocketException (111): Connection refused
一开始我以为这是网络问题,但是当我在我的应用容器中执行ping命令时,我可以找到postgres容器。我还尝试在应用容器中安装psql,即使这样我也可以访问我的postgres数据库。
我很茫然,有人知道问题出在哪里吗?
- "5433:5432"
- Mustafa Güler