rename process using pm2 programmatic api - node.js

I have an electron app which uses pm2 to start some apps using the pm2 module.Everything is fine.However I am trying to implement the following feature:Renaming an app you have started.I know that using the cli I can do the following:
pm2 restart app --name"New name";
So I found the pm2.restart function which takes an Object and a callback as a parameter.So I tried this:
var options = {app:"Blogsport App",name:"New name"};
var callback = function(err){
if(err) {console.log('Failed')}
else {console.log('App renamed')}
};
pm2.restart(options,callback);
This will always log "App renamed".However If I do pm2 list I see that the app has not be renamed.Is there anything I can do to rename an app without deleting it and start it again with a different name?

you can try this:
pm2 restart id --name newName
Example: your id is 1 , then you can type : pm2 restart 1 --name development

you can do
pm2 delete id|name
pm2 start app.js -n newname
or
pm2 restart id|name -n newname

pm2 ls
to see your app id
then you have two options
delete and start again
pm2 delete <id>
pm2 start index.js --name newname
or just restart to keep same id
pm2 restart <id> --name newname

Related

Azure App Service (Linux), NEXT JS app , PM2 not possible to set cluster mode

I have tried to set up a cluster by PM2 on Next JS app on Azure App Service (Linux) using startup command "pm2-runtime start ecosystem.config.js" or "pm2 --no-daemon start ecosystem.config.js". Both commands fail. When I am using pm2-runtime the current working directory passed to NodeJS script becomes: "wwwroot/ecosystem.config.js/.next" as a "directory parameters" and the server fails. In second command pm2 --no-daemon I receive information Unknown or unexpected option: --no-daemon. Both commands work for "fork" mode. Is it possible to set up a cluster mode for the azure app service with nextjs app?
ecosystem.config.code
module.exports = {
apps: [
{
name: 'next',
script: './node_modules/next/dist/bin/next',
args: 'start -p ' + (process.env.PORT || 3000),
instances: 2,
exec_mode: 'cluster',
watch: false,
autorestart: true,
},
],
};*
Errors for --no-daemon
enter image description here
Error for pm2-runtime
Error: Could not find a production build in the '/home/site/wwwroot/ecosystem.config.js/.next' directory. Try building your app with 'next build' before starting the production se
rver. https://err.sh/vercel/next.js/production-start-no-build-id
0|next| at Server.readBuildId (/home/site/wwwroot/node_modules/next/next-server/server/next-server.ts:2044:15)
0|next| | at new Server (/home/site/wwwroot/node_modules/next/next-server/server/next-server.ts:199:25)
0|next| | at createServer (/home/site/wwwroot/node_modules/next/server/next.ts:41:10)
0|next| | at start (/home/site/wwwroot/node_modules/next/server/lib/start-server.ts:9:15)
0|next| | at exec (/home/site/wwwroot/node_modules/next/cli/next-start.ts:53:3)
0|next| | at /home/site/wwwroot/node_modules/next/bin/next.ts:113:19 code here
Adding command pm2 list before pm2-runtime solves the issue, I suppose that the command pm2 list initializes the pm2 and sets the proper path for pm2-runtime.

How to run apps in the background using pm2 from a nodejs script?

I am trying to create an app that allows me to create demos of my other apps and run them on subdomain. Now everything works when I run my app through node server.js command, but when I run it in the background using pm2 start server.js, The following script doesnt work. When I log into my droplet using SSH, and run pm2 status, the demo app's start script is not on the list. What should I do?
const runInitialServerConfigurationNodejs = async (subdomain, port) => {
await shellPromise(`cp /var/www/${subdomain}_app/server/.env.example /var/www/${subdomain}_app/.env`);
await shellPromise(`cd /var/www/${subdomain}_app/server && yarn`);
await shellPromise(`mv /var/www/${subdomain}_app/server/server.js /var/www/${subdomain}_app/server/${subdomain}.js`);
await shellPromise(`echo "APP_ENV=production" >> /var/www/${subdomain}_app/server/.env`);
await shellPromise(`echo "MONGODB_KEY=mongodb://localhost:27017/${subdomain}_db" >> /var/www/${subdomain}_app/server/.env`);
await shellPromise(`echo "NODE_PORT=${port}" >> /var/www/${subdomain}_app/server/.env`);
await shellPromise(`cd /var/www/${subdomain}_app/server && pm2 start ${subdomain}.js && pm2 save && pm2 set pm2:autodump true`); // doesnt work here
}
Somehow pm2 does not work for my implementation. However i managed to get it working using the forever module.

How can I check if my pm2 app NODE_ENV is getting set?

So I just deployed a site with node and pm2 for the first time and I'm going back and doing some optimization and reading best practices, etc.
I read that you can get a lot of benefit by setting NODE_ENV=production.
I found this in the pm2 docs:
[process.json]
"env_production" : {
"NODE_ENV": "production"
}
...
$ pm2 start process.json --env production
So, I did it but I have no idea if it is working. While trying to figure out how to check it I learned to try:
$ node
> process.env.NODE_ENV
> undefined
So, that's not a good sign.. but, with my limited understanding of how the low level stuff works, I can guess that maybe pm2 launches each app as a separate node process? So maybe I'm not in the right process when I try to check it.
Also, I don't know if I have to make a new ~/.pm2/dump.pm2 file because maybe whenever that is maybe overriding the options I set? (because I used pm2 startup).
How do I check if my pm2 app's NODE_ENV is set?
To answer the actual question in the title:
Within your script, for me my Express app's app.js file, you can use process.env.NODE_ENV to get the current value of NODE_ENV and log that out if you want.
An even better way is to use PM2's Process Metrics module, aka pmx.
yarn add pmx
or
npm install pmx --save
then
const Probe = require('pmx').probe()
Probe.metric({
name : 'NODE_ENV',
value : function() {
return process.env.NODE_ENV
}
})
Now it will show up in calls to pm2 monit (bottom left).
To change your environment:
It is necessary that you kill and restart the process to change your environment.
$ pm2 kill && pm2 start pm2.json --env production
The following isn't good enough:
pm2 restart pm2.json --env production
You can also check your NODE_ENV via running pm2 show <yourServerName>. This will output info about your running server including node env.
In addition, you can check your environment variables via running pm2 env 0. This will show all the environment variables for the running node process.
Start it with npm by adding this to your package.json:
"scripts": {
"myScript": "NODE_ENV=production pm2 start server.js"
}
Then
npm start myScript
You can do it directly too, but this is easy to manage, automate wth crontab and is in your source control...
Your process.json file is incomplete. Try using something like this:
[process.json]
{
"name" : "MyApp",
"script" : "myapp.js",
"env_production" : {
"NODE_ENV": "production"
}
}
Then add logging into your code, preferably somwhere on startup:
console.log("NODE_ENV : ", process.env.NODE_ENV);
Now start the application:
pm2 start process.json --env production
Lastly watch app logs:
pm2 logs MyApp
This should do it.
May be at the start of your server script you can print the value of the environment variable and then check the PM2 logs. Use the following code to print your environment variable value:
console.log('process.env.NODE_ENV:', process.env.NODE_ENV);
And then use the following code to see the PM2 logs
pm2 logs app_name
Here app_name is your process name as indicated by the entry in the process.json file.
You can set Environment variable for pm2 specifically.
go to /etc/systemd/system/ location.
you can see a file named pm2-username.service
file. (eg: pm2-root.service ) you can directly add an Enviorment variable for pm2.
for me, it was LD_LIBRARY_PATH . so I added the line as below after the PATH variable.
Environment=PATH=/usr/local/lib......
Environment=LD_LIBRARY_PATH=/opt/oracle/instantclient_21_1
after that, you can restart or start the node application with update-env flag,
pm2 start yourapp --update-env
try pm2 env <app_name/id> also you can find NODE_ENV in pm2 show <app_name/id>
In your terminal just type:
echo NODE_ENV
it will print current selected environment variable

Switch from fork to cluster mode in pm2

I have a pm2 managed app that runs in fork mode. How can I switch it to cluster mode?
You can take a look at this document.
Stop and delete your current app run on the pm2.
pm2 stop ${your app name}
pm2 delete ${your app name}
And rerun your app with arguments -i max:
pm2 start path/to/main.js -i max --name="${your app name}"
// Should use pm2 not pm
Or create a json config file and run your app with it
// processes.json
{
"your-app-name" : [{
"script" : "path/to/main.js",
"instances" : "max",
"exec_mode" : "cluster"
}]
}
pm2 start processes.json
Switch app to Cluster Mode
$ pm2 reload all # Reload all apps in cluster mode
$ pm2 gracefulReload all # Graceful reload all apps in cluster mode

How to start node.js app with pm2 in cluster mode?

We are trying to start our app with pm2 0.12.8 on ubuntu 14.04 with octa core proccessor. The read me on the git hub has a very straight forward command for running node app in cluster mode.
# Cluster mode
$ pm2 start app.js -i 0 **# Will start maximum processes with LB depending on available CPUs**
$ pm2 start app.js -i max **# Same as above, but deprecated yet.**
But the above command are not working for us. When we try to run these commands only one instance is listed by pm2.
Why?
Any suggestion
Thanks
have you tried starting a fixed number of processes? i.e.
pm2 start app.js -i 2 //should start two instances.
what does "pm2 monit" show you?
also try
pm2 stop all
pm2 delete all
and then
pm2 start app.js -i 0
if you stop a process in pm2 it still reserves one cpu for it even if its not running. you should allways use pm2 delete
Since you are looking to use a process file to manage your pm2, the process file should look similar to this:
// ecosystem.js
{
"apps" : [{
"name" : "API",
"script" : "server.js",// name of the startup file
"instances" : 4, // number of workers you want to run
"exec_mode" : "cluster", // to turn on cluster mode; defaults to 'fork' mode
"env": {
"PORT" : "9090" // the port on which the app should listen
}
// for more options refer : http://pm2.keymetrics.io/docs/usage/application-declaration/#process-file
}]
}
Run this app using the following command to start and stop respectively:
$ pm2 start ecosystem.js
$ pm2 stop ecosystem.js
For fresh process
pm2 start app.js --name "my-node-app" -i 2 // to create 2 process
To make existing running process. You have to stop and delete the current running process, if it was fork mode. Then only it can create cluster mode.
pm2 stop my-node-app
pm2 delete my-node-app
pm2 start app.js --name "my-node-app" -i 2 // to create 2 process
I think you might ever start this project with normal mode (fork_mode), so you should delete all process list before change to cluster mode, since pm2 will memorise ur start options
pm2 delete all
pm2 start app.js -i [NUMBER_OF_INSTANCE|max]
You can get the best information here : pm2 cluster mode
To enable the cluster mode, just pass the -i option:
pm2 start app.js -i max
max means that PM2 will auto detect the number of available CPUs and run as many processes as possible
Or via a js/yaml/json file:
module.exports = {
apps : [{
script : "api.js",
instances : "max",
exec_mode : "cluster"
}]
}
NOTE: you need to set the exec_mode to cluster so PM2 know you want to load balance between each instances, by default it will not
Then to start the Process File:
pm2 start processes.json
The -i or instances option can be:
0/max to spread the app across all CPUs
-1 to spread the app across all CPUs - 1
number to spread the app across number CPUs.

Resources