You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit Docker容器中/undefined/get-paginated错误排查与解决

Docker运行SvelteKit应用出现/undefined/get-paginated 404错误的原因及解决方法

在Docker容器中运行SvelteKit应用时,出现如下404错误:

SvelteKitError: Not found: /undefined/get-paginated
at resolve2 (file:///app/build/server/index.js:3850:18)
at resolve (file:///app/build/server/index.js:3682:34)
at Object.handle (file:///app/build/server/chunks/hooks.server-JRK4nkXw.js:31:26)
at respond (file:///app/build/server/index.js:3680:43)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
status: 404,
text: 'Not Found'
}

本地构建运行正常,但Docker环境下PUBLIC_BACKEND_SERVER_URL环境变量未正确加载,导致请求路径拼接为/undefined/get-paginated。

错误原因

核心问题是SvelteKit环境变量的编译时机与Docker构建流程不匹配:

  • $env/static/public类型的环境变量是在构建阶段被硬编码到代码中的,而非运行时动态读取。
  • 当前Docker流程在builder阶段执行npm run build时,未传入PUBLIC_BACKEND_SERVER_URL,导致构建后的代码中该变量值为undefined。
  • 后续docker run时传入的环境变量无法覆盖已编译到代码中的值。

另外,svelte.config.js中adapter-node的envPrefix设为空字符串,这会影响运行时公共环境变量的识别,但并非本次问题的直接原因——因为你使用的是编译时注入的$env/static/public。

解决方法

方案一:构建时注入环境变量(适合固定后端地址场景)

修改Docker构建命令,在构建阶段传入环境变量:

docker build --build-arg PUBLIC_BACKEND_SERVER_URL=http://localhost:4000 -t my-frontend .

同时更新Dockerfile,在builder阶段接收并设置该环境变量:

FROM node AS builder
WORKDIR /app
COPY package*.json .
RUN npm ci
COPY . .
# 接收构建参数并设置为环境变量
ARG PUBLIC_BACKEND_SERVER_URL
ENV PUBLIC_BACKEND_SERVER_URL=$PUBLIC_BACKEND_SERVER_URL
RUN npm run build
RUN npm prune --production

FROM node
WORKDIR /app
COPY --from=builder /app/build build/
COPY --from=builder /app/node_modules node_modules/
COPY package.json .
EXPOSE 3000
ENV NODE_ENV=production
CMD ["node", "build"]

方案二:改用运行时动态环境变量(适合需动态修改后端地址场景)

如果需要在docker run时灵活指定后端地址,需切换为运行时注入的环境变量:

  1. 修改代码中的导入语句:
// 替换原有的静态导入
import { PUBLIC_BACKEND_SERVER_URL } from "$env/dynamic/public";
  1. 更新svelte.config.js中的adapter-node配置,确保SvelteKit能识别运行时的公共环境变量:
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: vitePreprocess(),
  kit: {
    adapter: adapter({ 
      out: 'build', 
      precompress: false, 
      envPrefix: 'PUBLIC_', // 设置为公共环境变量前缀
      polyfill: true 
    })
  }
};

export default config;
  1. 保持原docker run命令不变,运行时传入的PUBLIC_BACKEND_SERVER_URL会被正确加载。

内容的提问来源于stack exchange,提问作者kawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:32:16