我正在使用 NestJS 服务器实现一个应用程序,使用 PostgreSQL 数据库和 Prisma 服务来处理数据。 在 Dockerfile 中启动服务时尝试运行 Prisma 迁移时遇到问题。这是我的 docker-compose.yml 文件:
version: '3.8'
services:
# POSTGRES
postgres:
container_name: postgres
image: postgres:13.5
restart: always
ports:
- 5432:5432
env_file:
- ./backend/.env
volumes:
- postgres:/var/lib/postgresql/data
networks:
- transcendance
# BACKEND
backend:
build:
context: ./backend
dockerfile: Dockerfile
args:
- BUILDKIT_INLINE_CACHE=1
container_name: backend
restart: always
env_file:
- ./backend/.env
ports:
- 3001:3001
- 5555:5555 # Expose a port for Prisma Studio
depends_on:
- postgres
networks:
- transcendance
volumes:
- ./backend:/app
networks:
transcendance:
volumes:
postgres:
我正在使用此 Dockerfile 构建并运行我的后端容器:
FROM node:lts
WORKDIR /app
COPY package*.json ./
COPY prisma ./prisma/
COPY entrypoint.sh /app/entrypoint.sh
COPY . .
RUN npm i -g @nestjs/cli
RUN npm install
RUN chmod +x /app/entrypoint.sh
EXPOSE 3001 3002 5555
ENTRYPOINT [ "/app/entrypoint.sh" ]
CMD [ "npm", "run", "start:dev" ]
我已按如下方式设置此entrypoint.sh 文件以进行此迁移
#!/bin/sh
# Apply Prisma migrations and start the application
npx prisma migrate deploy
npx prisma generate
# Run database migrations
npx prisma migrate dev --name init
# Run the main container command
exec "$@"
我的所有容器都已创建良好,但只有我的数据库正在运行,其他容器处于 CREATED 状态。如果我删除脚本及其执行,运行
docker compose up --build
,然后直接从后端容器进行迁移,一切都会正常运行。
对此有什么帮助吗?谢谢!
在您的 Compose 文件中,您有一个
volumes:
块,它会使用主机中的内容覆盖图像的代码。删除这个。
services:
backend:
volumes: # <-- delete
- ./backend:/app # <-- delete
当此块存在时,容器中的
/app
目录就是主机系统中的 ./backend
目录。 /app
下的图像中的任何内容都被隐藏,并被安装的内容替换。
更具体地说,当你的 Dockerfile 说
RUN chmod +x /app/entrypoint.sh
绑定挂载隐藏了权限更改。如果该文件在主机系统上不可执行,那么当容器运行时它也将不可执行,并且将其作为容器的入口点运行时会出现错误。
这样的安装也会隐藏图像的
node_modules
目录。如果您的主机系统与容器环境不完全兼容(相同的操作系统和 C 库库),那么这可能会导致启动问题。有一个常见的解决方法是利用 Docker 功能将 node_modules
树存储在匿名卷中,但这意味着容器环境将忽略 package.json
文件中的更改,并且您可以获得不同的库树,具体取决于何时你首先运行了容器。