Home > front end >  Error: P1001: Can't reach database server at `localhost`:`5200`
Error: P1001: Can't reach database server at `localhost`:`5200`

Time:02-24

Technologies I use:

  • nestjs -> for backend
  • prisma -> for orm
  • postgresql -> database

I'm trying to run these technologies using Docker but I'm running into the following issue:

prisma schema loaded from prisma/schema.prism
Datasource "db": PostgreSQL database "nestjs", schema "public" at "localhost:5200"
Error: P1001: Can't reach database server at `localhost`:`5200`
Please make sure your database server is running at `localhost`:`5200`

docker-compose.dev.yml

version: '3.7'
services:
  db:
    image: postgres:12.9
    ports:
      - 5200:5432
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: 123
      POSTGRES_DB: nestjs
    volumes:
      - database-data:/var/lib/postgresql/data
    networks:
      - sai
    restart: always

  test:
    container_name: test
    image: test
    build:
      context: .
      target: development
      dockerfile: Dockerfile
    command: npm run start:prod
    ports:
      - 3000:3000
      - 9229:9229
    networks:
      - sai
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    links:
      - db
    depends_on:
      - db
    restart: always

networks:
  sai:
    driver: bridge

volumes:
  database-data:

Nestjs does not see my locahost database on port 5200.

Dockerfile file:

FROM node:latest as development
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=development
COPY . .
RUN npm run build


FROM node:latest as production
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install --only=production
COPY . .
COPY --from=development /usr/src/app/prisma ./prisma
COPY --from=development /usr/src/app/dist ./dist
EXPOSE 3000
CMD npm run start:prod

The npm run start:prod command also corresponds to the following in the package.json file:

...
  "generate:prisma": "npx prisma migrate dev --name init",
  "start:prod": "npm run generate:prisma && npm run dist/main",
...

CodePudding user response:

Instead of using localhost:5200 as the address of the database, you need to use db:5432.

Localhost and the mapped port are used when connecting from the host machine. You're connecting from another container on the bridge network and there you need to use the service name and the port the container is listening on.

  • Related