Utilizing Prisma, Docker, and NextJS: The mystery of "npx prisma db push" within docker-compose

I am looking to containerize my application (Prisma 4.9.1, NextJS 12, PostgreSQL) using Docker. The goal is to make it easy for users to clone the repository, type docker-compose up, and have everything running smoothly.

The issue I am facing is determining where to place the command npx prisma db push. I have tried various locations without success. Any suggestions or ideas?

My Dockerfile:

FROM node:18 AS dependencies

WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn

FROM node:18 AS build

WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

RUN npx prisma generate
RUN yarn build:in:docker

FROM node:18 AS deploy

WORKDIR /app

ENV NODE_ENV production

COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/prisma ./prisma

EXPOSE 3000

ENV PORT 3000

CMD ["node", "server.js"]

My docker-compose.yml file:

version: '3.9'
services:
  postgres:
    image: postgres:latest
    container_name: postgres
    hostname: myhost
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
      POSTGRES_DB: splitmate
    volumes:
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped
  splitmate-app:
    image: splitmate
    build:
      context: .
      dockerfile: Dockerfile
      target: deploy
    volumes:
      - postgres-data:/app/postgres-data
    environment:
      DATABASE_URL: postgresql://root:password@myhost:5432/splitmate?schema=public&connect_timeout=60
    ports:
      - 3000:3000
volumes:
  postgres-data:

The container builds successfully and starts. However, when the code attempts to access the database, I encounter the following error:

features-splitmate-app-1  | Invalid `prisma.account.findUnique()` invocation:
features-splitmate-app-1  | 
features-splitmate-app-1  | 
features-splitmate-app-1  | The table `public.Account` does not exist in the current database. {
features-splitmate-app-1  |   message: '\n' +
features-splitmate-app-1  |     'Invalid `prisma.account.findUnique()` invocation:\n' +
features-splitmate-app-1  |     '\n' +
features-splitmate-app-1  |     '\n' +
features-splitmate-app-1  |     'The table `public.Account` does not exist in the current database.',
features-splitmate-app-1  |   stack: 'Error: \n' +
features-splitmate-app-1  |     'Invalid `prisma.account.findUnique()` invocation:\n' +
features-splitmate-app-1  |     '\n' +
features-splitmate-app-1  |     '\n' +
features-splitmate-app-1  |     'The table `public.Account` does not exist in the current database.\n' +
features-splitmate-app-1  |     '    at RequestHandler.handleRequestError (/app/node_modules/@prisma/client/runtime/index.js:31941:13)\n' +
features-splitmate-app-1  |     '    at RequestHandler.handleAndLogRequestError (/app/node_modules/@prisma/client/runtime/index.js:31913:12)\n' +
features-splitmate-app-1  |     '    at RequestHandler.request (/app/node_modules/@prisma/client/runtime/index.js:31908:12)\n' +
features-splitmate-app-1  |     '    at async PrismaClient._request (/app/node_modules/@prisma/client/runtime/index.js:32994:16)\n' +
features-splitmate-app-1  |     '    at async getUserByAccount (/app/node_modules/@next-auth/prisma-adapter/dist/index.js:11:29)',
features-splitmate-app-1  |   name: 'Error'
features-splitmate-app-1  | }

Answer №1

I successfully resolved the issue

Updated Dockerfile:

FROM node:18 AS dependencies

WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn

FROM node:18 AS build

WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .

RUN npx prisma generate
RUN yarn build:in:docker
COPY migrate-and-start.sh .
RUN chmod +x migrate-and-start.sh

FROM node:18 AS deploy

WORKDIR /app

ENV NODE_ENV production

COPY --from=build /app/public ./public
COPY --from=build /app/package.json ./package.json
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/prisma ./prisma
COPY --from=build /app/migrate-and-start.sh .

EXPOSE 3000

ENV PORT 3000

CMD ["./migrate-and-start.sh"]

migrate-and-start.sh

#!/bin/bash

npx prisma generate
npx prisma db push
node server.js

Adjusted docker-compose.yml

version: '3.9'
services:
  postgres:
    image: postgres:latest
    container_name: postgres
    hostname: myhost
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
      POSTGRES_DB: splitmate
    volumes:
      - postgres-data:/var/lib/postgresql/data
    restart: unless-stopped
  splitmate-app:
    image: splitmate
    build:
      context: .
      dockerfile: Dockerfile
      target: deploy
    volumes:
      - postgres-data:/app/postgres-data
    environment:
      DATABASE_URL: postgresql://root:password@myhost:5432/splitmate?schema=public&connect_timeout=60
    ports:
      - 3000:3000
volumes:
  postgres-data:

Answer №2

After some searching, I came across a solution that closely resembles this approach:

Docker Configuration

FROM node:18-alpine

# Set working directory
WORKDIR /app

# Copy project files
COPY . .

# Update npm to latest version
RUN npm install -g npm@latest

# Install project dependencies
RUN npm install

# Expose port 3000
EXPOSE 3000

# Start the application
CMD source migrate-and-start.sh

migrate-and-start.sh

#!/bin/sh
npm run build
npx prisma generate
npx prisma migrate dev --name init
npm run start

This setup specifically addresses issues where Prisma fails to locate a ready PostgreSQL database.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent Next.js 13 from caching Firebase response or query result

I've created an API route located at: app/api/notes/route.js import db from "@/utils/firebaseDB" import { collection, getDocs } from "firebase/firestore"; export const GET = async (request) => { let posts = [] try { ...

Is a loading screen necessary when setting up the Stripe API for the checkout session?

While working on my web app and implementing the Stripe API for creating a checkout session, I encountered an issue where there is a white screen displayed awkwardly when navigating to the Stripe page for payments. The technology stack I am using is NextJ ...

Having Trouble with CORS when Sending a POST Request to Next.js 13.4.4 API Endpoint

I am currently using Next.js version 13.4.4 and have set up an endpoint at http://localhost:5000/logout. Within my src/app/logout/route.tsx file, the following code is present: import { NextRequest, NextResponse } from "next/server"; export asyn ...

Is it possible to modify the default case sensitivity of Next.js routes to make them case insensitive?

Currently, I am utilizing the app router. The URL that is currently in use is http://localhost:3000/SomeClientURL However, the client has requested that if a user enters http://localhost:3000/someclienturl, it should function in the same manner. I attemp ...

Using RSelenium and Docker containers to extract data (leveraging makeFirefoxProfile and mime types)

My task involves downloading over 50 datasets weekly from a dynamic website, and I am seeking to automate this process using R. Each dataset corresponds to a different school, with each school having its own unique link. Interestingly, the code structure f ...

Issue with state update in Markdown Editor using React and Next.js

"use client"; import { useState, useLayoutEffect } from "react"; import { useParams } from "next/navigation"; import React from "react"; import dynamic from "next/dynamic"; const SimpleMDE = dynamic(() =&g ...

Is it possible to customize the naming of the many-to-many tables in Next.js with Prisma?

Prisma automatically generates names for many-to-many tables, such as "_TableaToTableb" combining the names of Table A and Table B. The default id field names inside these tables are "A" and "B". I have two questions: Can I manually name the relation ta ...

Parsing XLSX files using next.js on an API route from an incoming request

Looking for ways to reduce my NextJS bundle size, I decided to move my XLSX parsing to an API route. Utilizing the npm xlsx (sheetjs) package, I extract JSON from a selected XLSX file. In the frontend, this is how I handle it: let res; let formData = new ...

Error in Typescript: An element is implicitly assigned the 'any' type because a string expression is being used to index a different type

Hello everyone, I'm fairly new to TypeScript and I've been struggling to troubleshoot an error in my code. Can someone please assist me with solving this TypeScript error? I keep getting the error message: "Element implicitly has an 'any&a ...

Troubleshooting NextJS useEffect with localStorage

I am attempting to retrieve a string from local storage, perform a check against it, and redirect the page based on the value stored in local storage. However, I am facing an issue where the page is briefly visible before redirecting to the original page. ...

Operating multiple containers with kubernetes for job processing

Currently, I am facing a challenge with processing multiple files in s3 using k8s. To address this, I have set up a job on k8s that consists of around 500 containers, each with different environments. However, the job is running very slowly and has failed ...

Is there a way to toggle the visibility of all React components while a loading screen is being displayed?

Whenever the page is changed in my case, a loading screen will appear. For instance: http://localhost:3000/ ----> http://localhost:3000/fr A loading screen will be displayed during the page transition. I am looking to hide other components. How ...

A guide to organizing page components across multiple `/pages` directories in a Next.js application

As I delve into my first project using Next.js, I find that my pages directory has expanded significantly. Now, I am keen on organizing my pages by grouping them into modules, resulting in a structure like 'src/modules/*/pages/*'. In my quest fo ...

The flow of execution context does not transition smoothly from getStaticPaths to getStaticProps as expected

Struggling to access data from a dynamic route in pages/science-and-engineering/[field].js. Using getStaticPath with getStaticProps but facing an issue where getStaticProps isn't being executed and the component isn't rendering. Only getStaticPat ...

Invalid default value for Drizzle timestamp at current date and time

As a newcomer to the Drizzle ORM, I am experimenting with creating a simple schema that includes a 'created_at' column with a default value set to the date when the account was created. Here is the schema: export const users = mysqlTable('us ...

Prisma unexpectedly updates the main SQL Server database instead of the specified database in the connection string

I have recently transitioned from using SQLite to SQL Server in the t3 stack with Prisma. Despite having my models defined and setting up the database connection string, I am encountering an issue when trying to run migrations. Upon running the commands: ...

Struggling to successfully upload a file to the Strapi upload API from a Next.js API route

Currently, I have implemented react dropzone on a specific page for the purpose of sending a file to an API route called /api/upload. Afterward, the file is supposed to be uploaded to a Strapi upload API using the following code: import formidable from &ap ...

Leveraging NextJS and React's Context API by incorporating a layout component wrapper

My current setup is as follows: I have a layout component where I include a navigation component and children. I enclose them within my Provider like this AppLayout.js <Layout> <Navigation/> <main> {children} </main> < ...

Struggling with importing aliases in TypeScript for shadcn-ui library

I am facing a challenge with resolving TypeScript path aliases in my project. I have set up the tsconfig.json file to include path aliases using the "baseUrl" and "paths" configurations, but alias imports are not functioning as intended. My goal is to imp ...

Ways to abbreviate a URL using Next JS

While working on my Next.js application, I encountered an issue with passing an object between pages. To achieve this, I compressed my array of objects into JSON using JSON.stringify(result) on the index page and then parsed it on the second page using JSO ...