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

使用PM2管理SvelteKit时.env文件注入失败的求助

问题:PM2无法通过ecosystem.config.cjs注入.env文件

尝试用PM2管理SvelteKit构建产物时,遇到无法通过ecosystem.config.cjs注入.env文件的问题,相关配置如下:

.env.production文件

PORT=3000

两个配置文件仅env: { }部分不同:

可正常运行的配置(应用能使用指定端口)

module.exports = {
    apps: [
        {
            name: 'my_app',
            script: './build/index.js',
            watch: false,
            ignore_watch: ['database'],
            autorestart: true,
            // 直接传入PORT时可正常生效
            env: {
                PORT: 3000
            }
        }
    ]
};

无法运行的配置(注入的PORT变量被忽略)

module.exports = {
    apps: [
        {
            name: 'my_app',
            script: './build/index.js',
            watch: false,
            ignore_watch: ['database'],
            autorestart: true,
            // 尝试注入.env文件时被忽略
            env: {
                ENV_PATH: "./.env.production",
            }
        }
    ]
};

解决方法

PM2不支持通过env字段中的ENV_PATH加载.env文件,正确做法是使用env_file字段指定.env文件路径:

修改后的ecosystem.config.cjs

module.exports = {
    apps: [
        {
            name: 'my_app',
            script: './build/index.js',
            watch: false,
            ignore_watch: ['database'],
            autorestart: true,
            // 使用env_file指定要加载的.env文件路径
            env_file: "./.env.production"
        }
    ]
};

额外说明

  1. 路径校验:确保.env.production文件的路径正确,路径是相对于PM2启动时的工作目录
  2. 多环境配置:如果需要区分开发/生产等不同环境,可结合env_<环境名>和env_file_<环境名>字段:
module.exports = {
    apps: [
        {
            name: 'my_app',
            script: './build/index.js',
            watch: false,
            ignore_watch: ['database'],
            autorestart: true,
            // 开发环境配置
            env_development: {
                NODE_ENV: "development"
            },
            env_file_development: "./.env.development",
            // 生产环境配置
            env_production: {
                NODE_ENV: "production"
            },
            env_file_production: "./.env.production"
        }
    ]
};

启动时指定环境:

pm2 start ecosystem.config.cjs --env production
  1. 变量优先级:如果env字段和env_file中的变量重复,env字段的变量会覆盖.env文件中的对应值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:36:31