3

I've been breaking my head over an issue I have when Dockerizing my ASP Dotnet application. I've been going through StackOverflow without any success.

Basically what I am trying to achieve is to run my ASP dotnet application (MVC API) in a Docker-container. I also want my Postgresql instance to run in a container in the same network.

I've created a docker-compose file like so:

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

My Dockerfile looks like the following

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"]

Lastly, I have configured my main application to accept environment variables so that I can override the 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();
                });

When I run docker-compose up --build && docker-compose logs -f in my directory that contains the docker-compose.yml file, the following error occurs in the app container:

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

At first I thought this was an issue with the networks, but when I execute a ping command in my app-container, I can find the postgres container. I also tried to install psql in the app-container, and even then I can access my postgres database.

I'm quite clueless. Does anyone have an idea what's the issue?

5
  • You exposed 5433 but defined 5432 as port. ` - "5433:5432" ` Try to change that. Commented Mar 13, 2021 at 16:25
  • @MustafaGüler Thank you for your response. It was my understanding that by adding "5433:5432" I only bind 5433 as externally approachable port. As stated in my post, I can connect to the postgres container by pinging (and by psql-connecting) to the 5432 port. I changed the port in the connectionstring, but it didn't solve it sadly. Commented Mar 13, 2021 at 16:29
  • Can you share also ConnectionStrings / DbContext . Commented Mar 13, 2021 at 16:42
  • Two questions: 1. You use the default Postgres image which I think you don't have the Postgres database 2. If you use a custom image with Postgres db try to reload the app after 2 minutes, I suppose that the Db is not fully started when you try to connect from the web app. Commented Mar 13, 2021 at 19:41
  • @Max I'm not sure I follow your first question. I am using postgres:9.6.21 (I used postgres:9.6.21-alpine in my example, which I later concluded I don't really need). This is the postgres base image that houses a database, right? I verified the database was up by connecting to it from my local machine and that seemed to work. As for your second question, that can very well be the case. I see that my app crashes in the logs of Docker-compose and afterwards the docker-compose logs show that the database has finished starting up. Do you have any recommendations how I can let the app reload? Commented Mar 14, 2021 at 11:43

2 Answers 2

1

This answer on stackoverflow fixed it for me, the database didn't boot up completely.

Sign up to request clarification or add additional context in comments.

Comments

0

this helps me a lot

if anyone ask for more details on how to do it in net minmal API

use the same docker file configured above with the solution link(using service_healthy check) then I modified the following on Program.cs

    builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
    {
        config.AddJsonFile("appsettings.json").
        AddJsonFile($"appsettings.docker.json", 
    true).AddEnvironmentVariables();
    });

    var connectionString = builder.Configuration.GetConnectionString("Default")
        ?? "Host = localhost; Database = xxxxx; Username = xxxxx; Password = 
        xxxx; Pooling = true; ";

    builder.Services.AddDbContext<DbContext>(opt =>
            opt.UseNpgsql(connectionString));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.