如何使用 PM2 将执行参数传递给应用程序? [英] How to pass execution arguments to app using PM2?

查看:39
本文介绍了如何使用 PM2 将执行参数传递给应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 pm2 来启动我的应用程序,但我无法向它传递参数.我使用的命令是 pm2 start app.js -- dev.虽然这永远有效.

I am using pm2 to start my app but I'm not able to pass argument to it. The command I am using is pm2 start app.js -- dev. Though this works with forever.

推荐答案

您可以按照此票证中的说明进行操作:https://github.com/Unitech/pm2/issues/13

You can do as stated in this ticket: https://github.com/Unitech/pm2/issues/13

虽然如果您要传递环境,您可能需要考虑利用环境变量.有了这个,您可以创建一个变量,该变量可以被该环境中的任何进程使用 process.env.* 访问.

Though if you're passing the environment you may want to consider leveraging environment variables. With this you create a variable which can be accessed by any process in that environment with process.env.*.

所以你有一个配置文件config.json:

So you have a configuration file config.json:

{
   "dev": {
        "db": {
            "hosts":["localhost"],
            "database": "api"
        },
        "redis": {
            "hosts": ["localhost"]
        }
   },
   "staging": {
        "db": {
            "hosts":["1.1.1.1"],
            "database": "api"
        },
        "redis": {
            "hosts": ["2.2.2.2"]
        }
   },
   "production": {
        "db": {
            "hosts":["1.1.1.1", "1.1.1.2", "1.1.1.3"],
            "database": "api"
        },
        "redis": {
            "hosts": ["2.2.2.2", "2.2.2.3"]
        }
   }
}

然后你导入你的配置:

var config=require('./config.json')[process.env.NODE_ENV || 'dev'];

db.connect(config.db.hosts, config.db.database);

然后您将通过 shell 在您的环境中设置变量:

Then you'd set the variable in your environment via shell:

export NODE_ENV=staging
pm2 start app.js

环境变量将持续与您的会话一样长.因此,您必须在 ~/.bashrc 文件中为该用户设置它,以使变量保持不变.这将在每个会话中设置变量.

The environment variable will last as long as your session. So you'll have to set it in the ~/.bashrc file for that user for the variable to persist. This will set the variable every session.

PM2 有一个部署系统,允许您设置每次在您的应用程序被守护进程之前都有一个环境变量.这就是 POSIX 系统中的守护进程通常采用参数的方式,因为这些参数不会随进程丢失.鉴于您的情况,这可能无关紧要,但这是一个很好的做法.

PM2 has a deploy system which allows you to set an environment variable each time before your app is daemonized. This is how daemons in POSIX systems typically take parameters, because those parameters aren't lost with the process. Given with your circumstance it might not matter so much, but its a good practice.

此外,您应该考虑在本地停止/启动,并尽可能重新启动(如果在集群模式下)以防止在生产中停机.

Moreover you should consider stop/starting locally, and restarting(if in cluster mode) whenever possible to prevent downtime when in production.

这篇关于如何使用 PM2 将执行参数传递给应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆