如何在Docker Compose中集成Prisma迁移实现一键启动全栈应用
Solution: Automate Prisma Migrations on Docker Compose Startup
Here's how to configure your setup to run Prisma migrations automatically when starting your stack with docker compose up -d:
Step 1: Create a Backend Startup Script
Add a start.sh file to your backend/ directory to handle migration execution and app startup:
#!/bin/sh # Wait for PostgreSQL to accept connections until npx prisma db ping; do echo "Waiting for database to be ready..." sleep 2 done # Run Prisma migration npx prisma migrate dev --name init --skip-seed # Start the backend application node index.js
Step 2: Update Backend Dockerfile
Modify your backend.dockerfile to include the startup script and set it as the default command:
FROM node:20 WORKDIR /app COPY package*.json ./ RUN npm install COPY prisma ./prisma RUN npx prisma generate COPY . . # Make startup script executable RUN chmod +x start.sh EXPOSE 4000 # Use the startup script to run migrations then start the app CMD ["./start.sh"]
Step 3: Configure Database Health Check in Compose
Update your compose.yaml to ensure the backend waits for PostgreSQL to be fully ready before starting:
version: "3.9" services: frontend: container_name: frontend image: frontend build: context: ./frontend dockerfile: frontend.dockerfile ports: - "3000:3000" environment: - NEXT_PUBLIC_API_URL=http://localhost:4000 restart: always depends_on: - backend backend: container_name: backend image: backend build: context: ./backend dockerfile: backend.dockerfile ports: - "4000:4000" environment: - DATABASE_URL=postgresql://postgres:postgres@db:5432/postgres?schema=public depends_on: db: condition: service_healthy # Wait for DB to be fully operational db: container_name: db image: postgres:13 restart: always environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U postgres -d postgres"] interval: 5s timeout: 5s retries: 5 volumes: pgdata: {}
Important Notes
- Migration Command:
prisma migrate devis intended for development environments (creates migrations and applies them). For production, replace it withprisma migrate deploywhich runs existing migrations without creating new ones. - Double Safeguard: The health check ensures PostgreSQL is accepting connections, while the
prisma db pingloop adds an extra layer of protection against connection delays. - One-Command Startup: Running
docker compose up -dwill now automatically:- Start and initialize PostgreSQL
- Wait for PostgreSQL to be ready
- Run Prisma migrations
- Start the backend and frontend services
内容的提问来源于stack exchange,提问作者Abeer
相关产品推荐
相关产品推荐

