asp.netpostgresqldockerdocker-composedocker-network

asp.net Failed to connect to postgres in docker


did docker or Postgres change something because I'm getting this error in all of my projects so I guess maybe because of my local machine and I tested in GitHub Code Spaces and I got the same error again so I tested it for other asp.net and postgres docker repositories and got the same error for them this is my GitHub repository Click here

and here is my project api log

Unhandled exception. Npgsql.NpgsqlException (0x80004005): Failed to connect to 172.19.0.4:5432
 ---> System.Net.Sockets.SocketException (111): Connection refused
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.Connect(NpgsqlTimeout timeout)
   at Npgsql.Internal.NpgsqlConnector.RawOpen(SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.<Open>g__OpenCore|213_1(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken, Boolean isFirstAttempt)
   at Npgsql.Internal.NpgsqlConnector.Open(NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.UnpooledDataSource.Get(NpgsqlConnection conn, NpgsqlTimeout timeout, Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.<Open>g__OpenAsync|42_0(Boolean async, CancellationToken cancellationToken)
   at Npgsql.NpgsqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists(Boolean async, CancellationToken cancellationToken)
   at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.GetAppliedMigrations()
   at Npgsql.EntityFrameworkCore.PostgreSQL.Migrations.Internal.NpgsqlMigrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
   at Products.Api.Extensions.MigrationExtensions.ApplyMigrations(IApplicationBuilder app) in /src/Products.Api/Extensions/MigrationExtensions.cs:line 15
   at Program.<Main>$(String[] args) in /src/Products.Api/Program.cs:line 23
 *  Terminal will be reused by tasks, press any key to close it. 

and here is docker-compose.yml code

version: '3.4'

services:
  products.api:
    image: ${DOCKER_REGISTRY-}productsapi
    container_name: products.api
    build:
      context: .
      dockerfile: Products.Api/Dockerfile
    ports:
      - "5000:5000"
      - "5001:5001"

  products.database:
    image: postgres:latest
    container_name: products.database
    environment:
      - POSTGRES_DB=products
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    volumes:
      - ./.containers/products-db:/var/lib/postgresql/data
    ports:
      - 5432:5432

  products.cache:
    image: redis:latest
    restart: always
    ports:
      - '6379:6379'

and the docker-compose.override.yml

version: '3.4'

services:
  products.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_HTTP_PORTS=5000
      - ASPNETCORE_HTTPS_PORTS=5001
    ports:
      - "5000:5000"
      - "5001:5001"
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/home/app/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/home/app/.aspnet/https:ro

and postgre container log

PostgreSQL init process complete; ready for start up.

2024-05-22 06:09:30.105 UTC [1] LOG:  starting PostgreSQL 16.3 (Debian 16.3-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit
2024-05-22 06:09:30.105 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
2024-05-22 06:09:30.106 UTC [1] LOG:  listening on IPv6 address "::", port 5432
2024-05-22 06:09:30.130 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
2024-05-22 06:09:30.163 UTC [65] LOG:  database system was shut down at 2024-05-22 06:09:29 UTC
2024-05-22 06:09:30.183 UTC [1] LOG:  database system is ready to accept connections
2024-05-22 06:14:30.261 UTC [63] LOG:  checkpoint starting: time
2024-05-22 06:14:34.624 UTC [63] LOG:  checkpoint complete: wrote 45 buffers (0.3%); 0 WAL file(s) added, 0 removed, 0 recycled; write=4.244 s, sync=0.054 s, total=4.363 s; sync files=12, longest=0.016 s, average=0.005 s; distance=260 kB, estimate=260 kB; lsn=0/1953468, redo lsn=0/1953430
 *  Terminal will be reused by tasks, press any key to close it. 

Solution

  • thanks to @David Maze my api was starting earlier than the database so add this to docker-compose.yml products.api section to make sure the API will wait for theDatabase start

     depends_on:
      - products. Database
      - products. Cache