Sugeng rawuh

PM2 for Node.js developers - settings in my application

Installing pm2

Firstly, pm2 should be installed globally to run several applications.

npm install pm2 -g

pm2 uses a configuration file to maintain the application.it can be either JSON or js or YAML file.

Here, we are going to use process.json file which will have the configuration for our application.

Application Setup

Create a simple node.js application with a file called app.js

npm init --yes

add the following code in app.js.

const express = require('express');

const app = express();

app.get('/',(req,res) => {

    res.send("PM2 is working, Send me Home");
    
})

const PORT = process.env.PORT;
app.listen(PORT,() => {
    console.log(`server is running on port ${PORT}`);
})

After that, create a file called process.json. it contains the apps array which contains the application configuration details.

{
    "apps": [{
        "name" : "nodepm2",
        "script" : "./app.js",
        "env" : {
            "PORT" : 4005
        },
        "env_production" : {
            "PORT" : 4000
        }
    }]
}

Firstly, name is the name of the process that pm2 running. pm2 will run the file mentioned in the script. Here, it will run like

pm2 start app.js

env contains the environment variable for the application. we can specify different env variables such as development, production or staging.

Here, we mentioned the environment variables for production and default(development).

Running pm2

Therefore, To run the application using pm2, we can start the application using the configuration of pm2.

pm2 start process.json
Share:

0 comments:

Post a Comment

Tonton video



Yuk, SUBSCRIBE

omfiki.blogspot.com