0

I have my NestJS application that use PrismaORM for connection to PostgreSQL. But building of docker file crashes after executing npx prisma migrate dev --name init with error Can't reach database server at postgres:5432

My docker-compose.yml

version: "3.8"
services:
    api:
        build:
            dockerfile: Dockerfile
            context: .
        depends_on: 
            - postgres
        env_file:
            - ./.env
        ports:
            - "8080:5000"

    postgres:
        image: postgres:10.4
        ports:
            - "5432:5432"
        environment: 
            POSTGRES_USER: user
            POSTGRES_PASSWORD: password 
            POSTGRES_DB: db
        volumes:
            - ./postgres-data:/var/lib/postgresql/data
        env_file:
            - ./.env

**My Dockerfile **

FROM node:16

WORKDIR /qmessanger/src/server

COPY package*.json ./

COPY prisma ./prisma/

COPY .env ./

COPY . .

RUN npm install


RUN npm run build
RUN npx prisma generate
RUN npx prisma migrate dev --name init

EXPOSE 8080

CMD [ "node", "dist/main" ]

My .env config

DATABASE_URL="postgresql://user:password@postgres:5432/db"
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_USER=user
POSTGRES_PASSWORD=password
POSTGRES_DB=db

My prisma config

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
QueezZ
  • 1
  • 1

1 Answers1

0

The issue is that you're trying to run the migration before the postgres service is running. You would need to run the migration as part of your startup command or entrypoint.

Here is an example of a similar problem in Django and they used an entrypoint script to run the migration: How do you perform Django database migrations when using Docker-Compose?

TJ H.
  • 244
  • 1
  • 4
  • OP can also try https://github.com/vishnubob/wait-for-it to ensure PG is available before trying out the migration. – Harshit Pant Nov 07 '22 at 10:06