How to pass arguments to app using pm2?

后端 未结 10 1184
予麋鹿
予麋鹿 2020-12-07 17:29

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.

10条回答
  •  佛祖请我去吃肉
    2020-12-07 18:00

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

    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.*.

    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"]
            }
       }
    }
    

    Then you import your config:

    var config=require('./config.json')[process.env.NODE_ENV || 'dev'];
    
    db.connect(config.db.hosts, config.db.database);
    

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

    export NODE_ENV=staging
    pm2 start app.js
    

    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 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.

提交回复
热议问题