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

时间:2019-11-08 17:13:02

标签: shell npm next.js pm2

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

"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",

还有一个ecosystem.config.js,看起来像这样:

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重新启动命令
  • ecosystem.config.js触发npm start命令并设置一些环境变量
  • 该应用程序启动,并且所有环境变量都可用,包括TEST_VAR(在原始命令中设置)

实际发生的情况是正确设置了生态系统中的所有环境变量,但应用程序中没有TEST_VAR。为什么会这样?如果无法执行此操作,如何从CI工具设置秘密密钥?

3 个答案:

答案 0 :(得分:0)

今晚我遇到了同样的问题。看完所有地方后,我发现了所需的配置。 env变量需要像下面一样进入您的def tf(corp): words_set = set() for i in corp: a=i.split(' ') for j in a: words_set.add(j) words_dict = {i:0 for i in words_set} wcount=0 matr=list() for doc in corp: for worduni in words_dict: count=0 for words in doc.split(' '): if words==worduni: count+=1 words_dict[worduni]=count/len(doc.split(' ')) print(words_dict) matr.append(words_dict.copy()) return matr 。就我而言,我将其放在服务器的根目录

ecosystem.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 将在您的应用程序中的API_URL中可用。 这些网址有助于 https://willandskill.se/en/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04/ https://pm2.keymetrics.io/docs/usage/application-declaration/

答案 1 :(得分:0)

另一个想法是通过以下方式将 PM2 的env 参数所有传递到服务器。

ecosystem.config.js 是:

module.exports = {
    apps: [{
        name: "my-service-1",
        script: "dist/server.js",
        env_production: process.env, // pass all the env params of the container to node
    }],
};

答案 2 :(得分:0)

@webface

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

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