Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell 通过PM2将环境变量传递给NextJS_Shell_Npm_Next.js_Pm2 - Fatal编程技术网

Shell 通过PM2将环境变量传递给NextJS

Shell 通过PM2将环境变量传递给NextJS,shell,npm,next.js,pm2,Shell,Npm,Next.js,Pm2,我有两个package.json脚本,如下所示: "start": "next start -p $PORT", "pm2_staging": "pm2 restart ecosystem.config.js --env staging", module.exports = { apps: [ { name: 'test.co.uk', script: 'npm', args: 'start', env_staging: {

我有两个
package.json
脚本,如下所示:

"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",
module.exports = {
  apps: [
    {
      name: 'test.co.uk',
      script: 'npm',
      args: 'start',
      env_staging: {
        API: 'staging',
        NODE_ENV: 'production',
        PORT: 3001,
      },
    },
  ],
};
还有一个类似这样的
ecosystem.config.js

"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",
module.exports = {
  apps: [
    {
      name: 'test.co.uk',
      script: 'npm',
      args: 'start',
      env_staging: {
        API: 'staging',
        NODE_ENV: 'production',
        PORT: 3001,
      },
    },
  ],
};
然后,我运行以下命令:

TEST_VAR='test' npm run pm2_staging
我预计会发生以下情况:

  • PM2重启命令触发
  • econosystem.config.js
    启动
    npm start
    命令并设置一些环境变量
  • 应用程序启动,所有环境变量都可用,包括
    TEST\u VAR
    (在原始命令中设置)

实际上,生态系统中的所有环境变量都已正确设置,但应用程序中没有可用的测试变量。为什么会这样?如果我不能这样做,我该如何从CI工具设置密钥?

今晚我遇到了同样的问题。在查看了所有需要配置的地方之后。env变量需要放入
生态系统.config.js
中,如下所示。在我的例子中,我把它放在服务器的根目录下

  module.exports = {
  apps : [{
    name: 'nextjs',
    script: 'yarn',
    args:"start",
    cwd:"/var/www/myapp/",
    instances: 2,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'development'
    },
    env_production: {
      NODE_ENV: 'production',
      API_URL: 'YOUR ENV URL',
      PORT:8000
    }
  }]
};
package.json
像这样

"scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start -p 8000"
  },
...
然后做了这样的事情

#!/bin/bash
cd /var/www/myapp/
git pull && yarn install && yarn build
cd ~/
pm2 start ecosystem.config.js --env production
然后,应用程序中的
const-API\u-URL=process.env.API\u-URL
中将提供
API\u-URL
。 这些URL有帮助
另一个想法是通过以下方式将PM2的
env
参数传递给服务器

ecosystem.config.js
是:

module.exports={
应用程序:[{
名称:“我的服务-1”,
脚本:“dist/server.js”,
env_production:process.env,//将容器的所有env参数传递给节点
}],
};
@webface

示例中的环境变量在Nextjs中不可用。要使客户端和服务器都可用,变量必须以NEXT_PUBLIC(即NEXT_PUBLIC_API_版本)作为前缀

这些环境变量必须传递到构建过程中,才能在运行时可用