Search code examples
node.jsdockernestjsprisma

Prisma getting Can't reach database server at `localhost`:`3306` error on Dockerized nestjs


When i dockerized Nestjs with MySql and phpMyadmin i getting this error on console:

Error: Can't reach database server at `localhost`:`3306`
at r /usr/src/app/node_modules/.pnpm/@[email protected][email protected]/node_modules/@prisma/client/runtime/library.js:108:2574)

migrating and seeding database is fine but this this code doesn't work:

async signUp(@Body() dto: AuthDto):Promise<any> {
  return await this.prisma.user.findUnique(
      {
        where: {
          mobileNumber: dto.mobileNumber
        }
      }
  );
}

migrating and seeding:

➜  my_app git:(master) ✗ npx prisma db push --force-reset && npx prisma db seed

Datasource "db": MySQL database "my_app" at "localhost:3306"

The MySQL database "my_app" at "localhost:3306" was successfully reset.

npm notice
Environment variables loaded from .env
Running seed command `ts-node prisma/seed.ts` ...

🌱  The seed command has been executed.

docker-compose.yaml

networks:
  host:
    name: my_app
    external: true
  lan_access:
    driver: bridge
    
services:
  my_app:
    build:
      context: .
      dockerfile: src/Dockerfile
      target: development
    command: npm run start:dev my_app
    env_file:
      - src/.env

    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    networks:
      - default
    ports:
      - '80:3000'

  database:
    image: mysql:latest
    restart: always
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_DATABASE: 'my_db'
      MYSQL_PASSWORD: 'root'
      MYSQL_ROOT_PASSWORD: 'root'
    ports:
      - '3306:3306'
    expose:
      - '3306'
    volumes:
      - my-db:/var/lib/mysql

  phpmyadmin:
    image: phpmyadmin:latest
    restart: always
    ports:
      - 8080:80
    environment:
      - PMA_ARBITRARY=1
volumes:
  my-db:

Dockerfile:

# Development stage
FROM node:alpine As development

WORKDIR /usr/src/app

COPY package*.json ./
COPY prisma ../../prisma/

RUN npm install -g pnpm
RUN pnpm install --save

COPY . .

RUN npm run build

# Production stage
FROM node:alpine as production

ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

WORKDIR /usr/src/app

COPY package*.json ./
COPY prisma ../../prisma/

RUN npm install -g pnpm
RUN pnpm install --only=production

COPY . .

COPY --from=development /usr/src/app/dist ./dist
COPY --chown=node:node --from=builder /usr/src/app/prisma /prisma


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

Solution

  • As you're running the server inside a docker-compose project, you should use the database service's name as the host to make use of docker compose's internal DNS resolution. Using the host database in your server's env should fix the error