I try to containerise my ASP.NET WebAPI with a PostgreSQL database with Docker but it won’t.
I have this connection string definition in appsettings.json
:
"ConnectionStrings": {
"EShopConnectionString": "Host=eshop.database;Port=5432;Database=eshop;User Id=postgres;Password=superuser;"
}
Dockerfile for WebAPI project is
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 5000
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["EShop.Web/EShop.Web.csproj", "EShop.Web/"]
COPY ["EShop.Application/EShop.Application.csproj", "EShop.Application/"]
COPY ["EShop.Domain/EShop.Domain.csproj", "EShop.Domain/"]
COPY ["EShop.Infrastructure/EShop.Infrastructure.csproj", "EShop.Infrastructure/"]
RUN dotnet restore "./EShop.Web/EShop.Web.csproj"
COPY . .
WORKDIR "/src/EShop.Web"
RUN dotnet build "EShop.Web.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "EShop.Web.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "EShop.Web.dll"]
And my docker-compose file looks like this:
services:
eshop.web:
image: eshop.backend:v1
container_name: EShop.Backend
restart: always
build:
context: .
dockerfile: ./Dockerfile
ports:
- 5000:5000
networks:
- eshop_network
depends_on:
- eshop.database
environment:
# - ConnectionStrings__EShopConnectionString=Host=eshop.database;Port=5432;Database=eshop;User Id=postgres;Password=superuser;
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_HTTP_PORTS=5000
eshop.database:
image: postgres:latest
container_name: EShop.Database
environment:
- POSTGRES_DB=eshop
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=superuser
volumes:
- ./.containers/eshop-db:/var/lib/postgresql/data
ports:
- 5432:5432
networks:
- eshop_network
You can notice that I made a comment on a line in the docker-compose
file with connection string. If I try to run containers this way my WebAPI says Failed to connect to 127.0.0.1:5432
. But if I uncomment that line and left the connection string in appsettings.json
like “”, WebAPI will successfully connect to the database. Why so?