如何使用pm2传递参数到应用程序? [英] How to pass arguments to app using pm2?

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

问题描述

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

I am using pm2 to start my app but i am 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天全站免登陆