首页 > 解决方案 > 如何在 Dockerized GraphQL + Postgres 设置中运行 Prisma 迁移?

问题描述

我不熟悉使用 Prisma 以及 Dockerizing 我的设置。我想使用 Prisma 指定我的数据模型,将 Postgres 作为我的数据库,并在 GraphQL API(我当前的 API 使用apollo-server-express)中使用它,该 API 还处理身份验证和角色等。

我现在拥有的是一个简单docker-compose.ymlDockerfileGraphQL API:

码头工人-compose.yml

services:
  api:
    build: ./api
    env_file:
      - .env
    volumes:
      - ./api:/usr/src/app
    ports:
      - ${API_PORT}:${API_PORT}
    command: npm start

Dockerfile

# Latest LTS version
FROM node:14

# Set default values for environment variables
ENV API_PORT=3001

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Bind port
EXPOSE ${API_PORT}

# Start server
CMD ["npm", "start"]

我将如何在此设置中使用 Prisma 和 Postgres,迁移以某种容器化方式发生,而不是我在 CLI 中手动执行 Prisma 命令?

感谢指出我的误解、提示或反馈!谢谢

标签: postgresqldockerdocker-composedockerfileprisma

解决方案


对我自己的问题的迟到回答:就像@Athir 建议的那样,我现在将两个进程分开并创建了两个 docker-compose.yml 文件:一个名为docker-compose.migrate.yml负责运行迁移的文件,另一个名docker-compose.yml为主应用程序。

我的docker-compose.migrate.yml

version: '3'
services:
  prisma-migrate:
    container_name: prisma-migrate
    build: ./api/prisma
    env_file:
      - .env
    environment:
      DB_HOST: <secret>
    depends_on:
      - db

  db:
    image: postgres:13
    container_name: db
    restart: always
    env_file:
      - .env
    environment:
      DB_PORT: 5432
    ports:
      - ${DB_PORT}:5432
    volumes:
      - ${POSTGRES_VOLUME_DIR}:/var/lib/postgresql/data

使用以下 Prisma Dockerfile:

FROM node:14

RUN echo $DATABASE_URL

WORKDIR /app

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

RUN chmod +x ./prisma/wait-for-postgres.sh

RUN npm install
RUN npx prisma generate

RUN apt update
RUN apt --assume-yes install postgresql-client

# Git will replace the LF line-endings with CRLF, causing issues while executing the wait-for-postgres shell script
# Install dos2unix and replace CRLF (\r\n) newlines with LF (\n)
RUN apt --assume-yes install dos2unix
RUN dos2unix ./prisma/wait-for-postgres.sh

CMD sh ./prisma/wait-for-postgres.sh ${DB_HOST} ${POSTGRES_USER} npx prisma migrate deploy && npx prisma db seed --preview-feature

wait-for-postgres.sh

#!/bin/sh
# wait-for-postgres.sh

set -e
  
host="$1"
user="$2"
shift
shift
cmd="$@"
  
until PGPASSWORD=$POSTGRES_PASSWORD psql -h "$host" -U "$user" -c '\q'; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 1
done
  
>&2 echo "Postgres is up - executing command"

exec $cmd

推荐阅读