Oliver Escoto
Oliver Escoto

Reputation: 11

Can't reach database server at `database`:`5432` running on docker container

I'm working on a NextJS application with Prisma and a postgres DB connected through docker. This setup was working before and suddenly i get an error.

I was trying to seed my database using prisma and I get this error:

 94 try {
  → 95   const update1 = await prisma.user.update(
  Can't reach database server at `localhost`:`5432`
  
  Please make sure your database server is running at `localhost`:`5432`.

I have a docker container running on port 5555:5432

any access of Prisma to the database gives the same error, same with migrations: Error: P1001: Can't reach database server at localhost:5432

connection string:

DATABASE_URL="postgresql://postgres:postgres@localhost:5432/mid-jobs-db?schema=public"

docker-compose.yml

version: "3.8"
services:
  postgres:
    image: postgres:13
    restart: always
    container_name: mid-jobs-db
    ports:
      - "5555:5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    volumes:
      - my-db:/var/lib/postgresql/data
volumes:
  my-db:

docker ps Docker PS screenshot

I have a Docker Desktop and I can see the container running

my node version is: v16.13.0

I tried restarting the docker container, deleting it and running it again with docker compose up. I tried using this different connection URLS, also tried adding ?connect_timeout=300 to it. I tried changing the port in the docker container to:

    ports:
      - "5432:5432"

but then I get a different error

Database `mid-jobs-db` does not exist on the database server at `localhost:5432`

I didn't change anything on the docker container or the connection string and it was working fine a week ago. (Might have restarted my Mac anytime from that day).

Upvotes: 0

Views: 1746

Answers (1)

BertC
BertC

Reputation: 2656

Your docker compose implies that the file only has the Postgres database. That database is accessible in 2 different ways:

  1. On the Host on port 5555
  2. From another container which is setup in the same (!!) docker-compose file through "postgresql://postgres:postgres@localhost:5432"

If you want to access the database from something outside this host, then you need to access the host (via domainname?) on port 5555.

If you want to access the database from another container, which is not set up in the same docker-compose file, then you need to do the following:

  • Create an external network and give this postgres container an IP in that network
  • Give your application (which wants to connect to this postgres) also an IP in that same network
  • Access the postgres database via IP address

Upvotes: 0

Related Questions