rwadurian/backend/services/admin-service/Dockerfile

92 lines
2.7 KiB
Docker

# =============================================================================
# Admin Service Dockerfile
# =============================================================================
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package*.json ./
COPY tsconfig*.json ./
COPY nest-cli.json ./
# Copy Prisma schema
COPY prisma ./prisma/
# Install dependencies
RUN npm ci
# Generate Prisma client (dummy DATABASE_URL for build time only)
RUN DATABASE_URL="postgresql://user:pass@localhost:5432/db" npx prisma generate
# Copy source code
COPY src ./src
# Build TypeScript
RUN npm run build
# Verify build output exists
RUN ls -la dist/ && test -f dist/main.js
# Production stage - use Debian slim for OpenSSL compatibility
FROM node:20-slim
# Create non-root user with home directory (npm cache needs it)
RUN groupadd -g 1001 nodejs && \
useradd -u 1001 -g nodejs -m nestjs
# Install OpenSSL and curl for health checks
RUN apt-get update && apt-get install -y --no-install-recommends \
openssl \
curl \
&& rm -rf /var/lib/apt/lists/*
# Create app directory and uploads directory with correct ownership
RUN mkdir -p /app /app/uploads && chown -R nestjs:nodejs /app
WORKDIR /app
# Switch to non-root user before installing dependencies
USER nestjs
# Install production dependencies only
COPY --chown=nestjs:nodejs package*.json ./
RUN npm ci --only=production
# Copy Prisma schema and generate client (dummy DATABASE_URL for build time only)
COPY --chown=nestjs:nodejs prisma ./prisma/
RUN DATABASE_URL="postgresql://user:pass@localhost:5432/db" npx prisma generate
# Copy built files
COPY --chown=nestjs:nodejs --from=builder /app/dist ./dist
# Create uploads directory with correct ownership (before volume mount)
# This ensures the directory exists and has correct ownership
# Note: When a named volume is mounted, if it's empty, Docker will copy the container's directory content to it
USER root
RUN mkdir -p /app/uploads && chown -R nestjs:nodejs /app/uploads
USER nestjs
# Create startup script that runs migrations before starting the app
RUN printf '%s\n' \
'#!/bin/sh' \
'set -e' \
'echo "Running database migrations..."' \
'npx prisma migrate deploy || npx prisma db push --accept-data-loss' \
'echo "Starting application..."' \
'exec node dist/main.js' \
> /app/start.sh && chmod +x /app/start.sh
ENV NODE_ENV=production
# Expose port
EXPOSE 3010
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s --retries=3 \
CMD curl -f http://localhost:3010/api/v1/health || exit 1
# Start service with migration
CMD ["/app/start.sh"]