Home > OS >  How to connect an ASP.NET backend to a postgres database inside a docker container
How to connect an ASP.NET backend to a postgres database inside a docker container

Time:01-28

I have been trying to connect my webapi built in ASP.NET Core 7.1 to a postgresql database. It is inside a docker container. However, every time I run docker-compose -f docke-compose.yml up, I get the following error:

 Unhandled exception. System.Net.Sockets.SocketException (00000001, 11): Resource temporarily unavailable

I assume this means that something has gone wrong with the database connection but I don't know how to fix it. Here is my docker-compose.yml

version: '3.8'

services:
  server:
    build: ./Test
    ports:
      - "8000:80"
    depends_on:
      - db
  
  db:
    container_name: db
    image: postgres:latest
    environment:
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=pass
      - POSTGRES_DB=data
    volumes:
      - pgdata:/var/lib/postgresql/data
    ports:
      - "1234:5432"
    networks:
      - db-network
  
networks:
  db-network:
    driver: bridge

volumes:
  pgdata:

And here is my appsettings.json from the backend

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "Data": "Host=db;Port=5432;Database=data;User ID=user;Password=pass"
  },
  "AllowedHosts": "*"
}

I have tried changing the connection strings, password and user id but I keep getting the same error.

CodePudding user response:

Either remove network from docker-compose.yml (so default is used) or add db-network to server:

services:
  server:
    build: ./Test
    ports:
      - "8000:80"
    depends_on:
      - db
    networks:
      - db-network
  • Related