Home > Software design >  Application not able to connect to PostgreSQL in docker compose
Application not able to connect to PostgreSQL in docker compose

Time:01-22

I have a .net application using a PostgreSQL database, I have a docker compose file which runs the application and PostgreSQL when I try to execute any command I get a db connection error show below

enter image description here

Error appdemo-service | System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. appdemo-service | ---> Npgsql.NpgsqlException (0x80004005): Failed to connect to [::1]:5433 appdemo-service | ---> System.Net.Sockets.SocketException (99): Cannot assign requested address appdemo-service | at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.CreateException(SocketError error, Boolean forAsyncThrow)

This is the code I am using for docker-compose

version: '3.4'

networks:
  dev:
    driver: bridge

services:
  app-demo:
    image: docker.io/library/appdemo
    depends_on:
     - "app_db"
    container_name: appdemo-service
    ports:
      - "5009:80"
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - ConnectionStrings__DefaultConnection=User ID =postgres;Password=postgres;Server=localhost;Port=5433;Database=SampleDriverDb; Integrated Security=true;Pooling=true;
      - ASPNETCORE_URLS=http:// :80
    networks:
      - dev

  app_db:
    image: postgres:latest
    container_name: app_db
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=SampleDriverDb
    ports:
      - "5433:5432"
    restart: always
    volumes:
      - app_data:/var/lib/postgresql/data
    networks:
      - dev
volumes:
  app_data:

CodePudding user response:

In a container context localhost means the container itself. So when you specify localhost as the database host, your program looks for a database inside the app-demo container.

Docker-compose creates a bridge network that it connects the containers to. Containers can talk to each other on that network using either their service names or, if you've set it, the container_name as the host name.

So when your app-demo container wants to talk to the database, it needs to use the name app_db.

Also, when the containers talk to each other on the bridge network, they use the unmapped port numbers. So you want to talk to the database on port 5432. You only use the mapped port number if you want to talk to a container from the host.

Change your connection string from

ConnectionStrings__DefaultConnection=User ID =postgres;Password=postgres;Server=localhost;Port=5433;Database=SampleDriverDb; Integrated Security=true;Pooling=true;

to

ConnectionStrings__DefaultConnection=User ID =postgres;Password=postgres;Server=app_db;Port=5432;Database=SampleDriverDb; Integrated Security=true;Pooling=true;

and it should work.

  • Related