如何在 Dockerized GraphQL + Postgres 设置中运行 Prisma 迁移?

2023-12-31

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

我现在拥有的是一个简单的docker-compose.yml and a Dockerfile我的 GraphQL API 的:

docker-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 命令?

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


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

My 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

EDIT: 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

编辑:示例.env file:

# ---- DB ----
DB_HOST=localhost
DB_PORT=5432
DB_SCHEMA=example

POSTGRES_DB=example
POSTGRES_USER=example
POSTGRES_VOLUME_DIR=/path/where/you/want/to/store
POSTGRES_PASSWORD=example

DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${DB_HOST}:${DB_PORT}/${POSTGRES_DB}?schema=${DB_SCHEMA}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Dockerized GraphQL + Postgres 设置中运行 Prisma 迁移? 的相关文章

随机推荐