diff --git a/Dockerfile b/Dockerfile index 8331a65..0831ab5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ # Use Node.js 18 LTS FROM node:20-alpine -# Install MongoDB CLI tools and curl for import operations and health checks -RUN apk add --no-cache mongodb-tools curl +# Install MongoDB CLI tools, curl, and jq for import operations and health checks +RUN apk add --no-cache mongodb-tools curl jq # Set working directory WORKDIR /app @@ -27,7 +27,7 @@ EXPOSE 3000 # Health check HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:3000/api/health || exit 1 + CMD curl -f http://localhost:3000/api/health | jq -e '.status == "healthy"' || exit 1 # Start the application CMD ["npm", "start"] diff --git a/src/app/api/health/route.ts b/src/app/api/health/route.ts new file mode 100644 index 0000000..4506706 --- /dev/null +++ b/src/app/api/health/route.ts @@ -0,0 +1,48 @@ +import { NextResponse } from 'next/server'; +import { MongoClient } from 'mongodb'; + +export async function GET() { + const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost/beanstalk'; + const healthStatus: { + status: 'healthy' | 'degraded'; + timestamp: string; + services: { + app: string; + mongodb: string; + }; + mongodb_error?: string; + mongodb_databases?: Array<{name: string; sizeOnDisk: number}>; + } = { + status: 'healthy', + timestamp: new Date().toISOString(), + services: { + app: 'healthy', + mongodb: 'unknown' + } + }; + + try { + // Test MongoDB connection + const client = new MongoClient(mongoUri); + await client.connect(); + await client.db().admin().ping(); + + // List databases for diagnostics + const dbList = await client.db().admin().listDatabases(); + healthStatus.mongodb_databases = dbList.databases.map((db: any) => ({ + name: db.name, + sizeOnDisk: db.sizeOnDisk + })); + + await client.close(); + + healthStatus.services.mongodb = 'healthy'; + } catch (error) { + healthStatus.status = 'degraded'; + healthStatus.services.mongodb = 'unhealthy'; + healthStatus.mongodb_error = error instanceof Error ? error.message : 'Unknown error'; + } + + const statusCode = healthStatus.status === 'healthy' ? 200 : 503; + return NextResponse.json(healthStatus, { status: statusCode }); +}