Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: shut down web container gracefully (#2635)

Max Deichmann5c57b2b8e112
diff --git a/.dockerignore b/.dockerignore
index e7c96af0df..1de652634f 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -3,6 +3,6 @@ Dockerfile
node_modules
npm-debug.log
README.md
-.next
+**/.next
.git
**/node_modules
\ No newline at end of file
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d2991b63cd..a904e28d51 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -480,6 +480,9 @@ importers:
posthog-node:
specifier: ^3.6.3
version: 3.6.3
+ prexit:
+ specifier: ^2.2.0
+ version: 2.2.0
prisma:
specifier: ^5.13.0
version: 5.13.0
@@ -16750,6 +16753,10 @@ packages:
resolution: {integrity: sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==}
dev: false
+ resolution: {integrity: sha512-MrkWg5/0XFTM0txQtPFZlhk3qhMtyd+bP1vXJKQqOOYcdQ8/Wl5+G0Utxv69TLfH0PMm/ushn0YTYQ2SH2WzJg==}
+ dev: false
+
resolution: {integrity: sha512-abo2EBIjqJALfjm8p+uOsQk38DlU3rlLJA9/cOvcLLt8A9bjMkRwlqaZDAD/iXVZcXJRJPgJ98fEviTa+w8oTQ==}
engines: {node: '>=14'}
diff --git a/web/Dockerfile b/web/Dockerfile
index c414c76e4f..0cf9b7505d 100644
--- a/web/Dockerfile
+++ b/web/Dockerfile
@@ -11,7 +11,6 @@ ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
RUN corepack prepare [email protected] --activate
-
FROM --platform=${TARGETPLATFORM:-linux/amd64} base AS pruner
WORKDIR /app
@@ -19,7 +18,6 @@ WORKDIR /app
COPY . .
RUN turbo prune --scope=web --docker
-
FROM --platform=${TARGETPLATFORM:-linux/amd64} base AS builder
WORKDIR /app
@@ -32,6 +30,7 @@ COPY --from=pruner /app/out/json/ .
RUN pnpm install --frozen-lockfile
ENV DOCKER_BUILD 1
+ENV NEXT_MANUAL_SIG_HANDLE true
# pass public variables in build step
ARG NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
@@ -53,14 +52,13 @@ RUN rm -f ./web/src/middleware.ts
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
ENV NEXT_TELEMETRY_DISABLED 1
+ENV NEXT_MANUAL_SIG_HANDLE true
RUN turbo run build --filter=web
# Production image, copy all the files and run next
FROM --platform=${TARGETPLATFORM:-linux/amd64} base AS runner
-RUN apk add --no-cache dumb-init
-
WORKDIR /app
ENV NODE_ENV production
@@ -68,13 +66,16 @@ ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1
# Needed to re-enable validation of environment variables during runtime
ENV DOCKER_BUILD 0
+# Set NEXT_MANUAL_SIG_HANDLE for runtime
+ENV NEXT_MANUAL_SIG_HANDLE true
+
+RUN apk add --no-cache dumb-init
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
RUN npm install -g --no-package-lock --no-save prisma
-
COPY --from=builder --chown=nextjs:nodejs /app/web/next.config.mjs .
COPY --from=builder --chown=nextjs:nodejs /app/web/package.json .
@@ -95,5 +96,8 @@ USER nextjs
# Default port to 3000
ENV PORT 3000
-# CMD ["node", "server.js"]
-CMD ["dumb-init", "--", "./web/entrypoint.sh"]
+
+ENTRYPOINT ["dumb-init", "--", "./web/entrypoint.sh"]
+
+# startup command
+CMD ["node", "./web/server.js"]
diff --git a/web/entrypoint.sh b/web/entrypoint.sh
index 999fb084b4..621dd2a324 100644
--- a/web/entrypoint.sh
+++ b/web/entrypoint.sh
@@ -35,5 +35,5 @@ if [ $status -ne 0 ]; then
exit $status
fi
-# Start server
-node web/server.js
+# Run the command passed to the docker image on start
+exec "$@"
\ No newline at end of file
diff --git a/web/package.json b/web/package.json
index 5f995d9a1e..505c26aab4 100644
--- a/web/package.json
+++ b/web/package.json
@@ -13,7 +13,7 @@
"lint:fix": "dotenv -e ../.env -- next lint --fix",
"prettier": "prettier --write ./src *.{ts,js}",
"clean": "rm -rf node_modules",
- "start": "dotenv -e ../.env -- next start",
+ "start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",
"test": "dotenv -e ../.env -- jest --runInBand",
"test:watch": "dotenv -e ../.env -- jest --watch --runInBand",
"test:e2e": "dotenv -e ../.env -- playwright test",
@@ -99,6 +99,7 @@
"next-themes": "^0.3.0",
"posthog-js": "^1.122.0",
"posthog-node": "^3.6.3",
+ "prexit": "^2.2.0",
"prisma": "^5.13.0",
"react": "18.2.0",
"react-day-picker": "^8.10.1",
diff --git a/web/src/instrumentation.ts b/web/src/instrumentation.ts
index 4bd68736f9..9d0b69e8b6 100644
--- a/web/src/instrumentation.ts
+++ b/web/src/instrumentation.ts
@@ -1,8 +1,17 @@
// See: https://vercel.com/docs/observability/otel-overview
+import { shutdown } from "@/src/utils/shutdown";
+import prexit from "prexit";
+
export async function register() {
if (process.env.NEXT_RUNTIME === "nodejs") {
await import("./sentry.server.config");
+ if (process.env.NEXT_MANUAL_SIG_HANDLE) {
+ prexit(async (signal) => {
+ console.log("Signal: ", signal);
+ return await shutdown(signal);
+ });
+ }
}
if (process.env.NEXT_RUNTIME === "edge") {
diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsx
index 201486d2f5..2508d06252 100644
--- a/web/src/pages/_app.tsx
+++ b/web/src/pages/_app.tsx
@@ -18,6 +18,7 @@ import { useRouter } from "next/router";
import posthog from "posthog-js";
import { PostHogProvider } from "posthog-js/react";
import { CrispWidget, chatSetUser } from "@/src/features/support-chat";
+import prexit from "prexit";
// Custom polyfills not yet available in `next-core`:
// https://github.com/vercel/next.js/issues/58242
@@ -31,6 +32,7 @@ import "react18-json-view/src/style.css";
import { DetailPageListsProvider } from "@/src/features/navigate-detail-pages/context";
import { env } from "@/src/env.mjs";
import { ThemeProvider } from "@/src/features/theming/ThemeProvider";
+import { setSigtermReceived, shutdown } from "@/src/utils/shutdown";
const setProjectInPosthog = () => {
// project
@@ -163,3 +165,10 @@ function UserTracking() {
}, [session]);
return null;
}
+
+if (process.env.NEXT_MANUAL_SIG_HANDLE) {
+ prexit(async (signal) => {
+ console.log("Signal: ", signal);
+ return await shutdown(signal);
+ });
+}
diff --git a/web/src/pages/api/public/health.ts b/web/src/pages/api/public/health.ts
index 433a5c8b04..3a8bf838a1 100644
--- a/web/src/pages/api/public/health.ts
+++ b/web/src/pages/api/public/health.ts
@@ -1,6 +1,7 @@
import { VERSION } from "@/src/constants";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { telemetry } from "@/src/features/telemetry";
+import { isSigtermReceived } from "@/src/utils/shutdown";
import { prisma } from "@langfuse/shared/src/db";
import { type NextApiRequest, type NextApiResponse } from "next";
@@ -14,6 +15,15 @@ export default async function handler(
const failIfNoRecentEvents = req.query.failIfNoRecentEvents === "true";
try {
+ if (isSigtermReceived()) {
+ console.log(
+ "Health check failed: SIGTERM / SIGINT received, shutting down",
+ );
+ return res.status(500).json({
+ status: "SIGTERM / SIGINT received, shutting down",
+ version: VERSION.replace("v", ""),
+ });
+ }
await prisma.$queryRaw`SELECT 1;`;
if (failIfNoRecentEvents) {
diff --git a/web/src/utils/shutdown.ts b/web/src/utils/shutdown.ts
new file mode 100644
index 0000000000..308799eb32
--- /dev/null
+++ b/web/src/utils/shutdown.ts
@@ -0,0 +1,34 @@
+// https://github.com/vercel/next.js/issues/51404
+// There is no official best way to gracefully shutdown a Next.js app in Docker.
+// This here is a workaround to handle SIGTERM and SIGINT signals.
+// NEVER call process.exit() in this process. Kubernetes should kill the container: https://kostasbariotis.com/why-you-should-not-use-process-exit/
+// We wait for 20 seconds to allow the app to finish processing requests. There is no native way to do this in Next.js.
+
+declare global {
+ // eslint-disable-next-line no-var
+ var sigtermReceived: boolean | undefined;
+}
+
+globalThis.sigtermReceived = globalThis.sigtermReceived ?? false;
+
+export const setSigtermReceived = () => {
+ console.log("Set sigterm received to true");
+ globalThis.sigtermReceived = true;
+};
+
+export const isSigtermReceived = () =>
+ Boolean(process.env.NEXT_MANUAL_SIG_HANDLE) && globalThis.sigtermReceived;
+
+export const shutdown = async (signal: PrexitSignal) => {
+ if (signal === "SIGTERM" || signal === "SIGINT") {
+ console.log("SIGTERM / SIGINT received. Shutting down in 20 seconds.");
+ setSigtermReceived();
+
+ return await new Promise<void>((resolve) => {
+ setTimeout(() => {
+ console.log("Shutdown complete");
+ resolve();
+ }, 20000);
+ });
+ }
+};