Run nextjs application in the background - node.js

I have an application built with nextJs and this application should work on a local server (Windows).
my customer told me that he needed this application to work in the background after searching I found that I needed to use a package called pm2 and when I used it gives me an error and I found that I needed to make some configurations for it and I can't found any helping resources, please help 💔

I found that to run nextJs application in the background you will need a custom configuration
you need to download the pm2 globally in your system
create a file with the name ecosystem.config.js in the root folder next to the package.json file
you need to put your config data in this file which would be something like this
module.exports = {
apps: [
{
name: "inventory_test",
script: "node_modules/next/dist/bin/next",
args: "start -p 3333", //running on port 3000
watch: false,
},
],
};
you should set the name as the name you want to see when you check
the list of pm2
the problem will be solved when you set the script as I did in the code above to be more precise the default run of pm2 is to go to the node js folder in the system and try to make start for the application using npm directly but this is the problem we need to make it use the node runner from the nextjs itself or something like this so we change the script as above
after that, we set the arguments that we should run after the npm and in my example is the arg start and choose the port for our application too
and now we make our config
NOTES
you should make build before you start the application
to run the project you will open the folder of the project in the terminal || cmd || cmder and run the command pm2 start ecosystem.config.js

Related

PM2 run nodejs sveltekit app with options

I have an app that i bult with npm run build, with sveltekit, everything works fine, but i have to specify the ORIGIN like it says here https://github.com/sveltejs/kit/tree/master/packages/adapter-node, to make it run otherwise i run in to this problem "Cross-site POST form submissions are forbidden".
I run it like this and it works fine ORIGIN=http://myorigin node out/index.js.
Now i need to register it to PM2 but i find nothing to run it with the origin parameter.
I have also tried to set the ORIGIN keu in the .env file, and installing dotenv, but i still need to run this command: node -r dotenv/config build, with options, and i cant make it start from PM2.
Is there a way to do this?
Thanks
i found this and it worked https://pm2.keymetrics.io/docs/usage/application-declaration/
module.exports = {
apps : [{
name : "app",
script : "ORIGIN=http://myorigin node out/index.js"
}]
}

How to run nuxt.js in real service?

I used vue-cli in
vue init nuxt/express myProject
and,
npm run dev
developed.
but,
npm run build
after, was created dist file.
How i can run in real service in pm2?
(I will use ubuntu in AWS EC.)
you just need to start your app like that:
pm2 start npm --name "your-project-name" -- start
Check the status:
pm2 status
and after you can restart / stop:
pm2 restart your-project-name
pm2 stop your-project-name
Prerequisites
node.js installed on web server
nginx installed and configured on web server
pm2 installed and configured on web server
Then
Add to your universal Nuxt app for serving it though PM2 is a file called ecosystem.config.js. Create a new file with that name in your root project directory and add the following content:
module.exports = {
apps: [
{
name: 'project-name',
exec_mode: 'cluster',
instances: 'max', // Or a number of instances
script: './node_modules/nuxt/bin/nuxt.js',
args: 'start'
}
]
}
Connect to your linux server via FTP (FileZilla or etc..)
Send the blue files I marked to the server.
(you don't need to upload node_modues, .nuxt, dist, .git, .idea, etc... folders)
Connect server via ssh console, (windows : putty)
and go to projects folder that you uploaded files.
cd /
cd var/www/project-name
Install node_modules folder by;
npm install
Execute nuxt build and create .nuxt folder by;
npm run build
Finally, ready to start starts pm2 server by;
pm2 start

Running Meteor Build under Node with settings argument

Typically when developing I would use meteor run --settings settings.json. This works fine and can view the settings in the browser with Meteor.settings on the console.
I am now build for production, using meteor build, I've looked at the documentation and there is nowhere to add settings during the build process.
So the build runs and I have my .tar.gz file, it's loaded to production and then I untar/compress the folder and run the start script.
It enters the program with npm start and the package.json section looks like this (ignore the stop script);
{
"name": "myapp",
"scripts": {
"start": "node main.js --settings settings.json",
"stop": "killall node"
}
}
When I look at my app it is not collecting these settings. It is as if when bundled it doesn't expect the arguements. I also tried using forever beforehand, but I had no joy with this either.
Any help would appreciated, start to wish I never bothered with Meteor :)
You can refer to Meteor Guide > Production > Deployment and Monitoring > Environment variables and Settings
Settings. These are in a JSON object set via either the --settings Meteor command-line flag or stringified into the METEOR_SETTINGS environment variable.
As for setting environment variables, if you use a 3rd party host, you may have a GUI or CLI to define them.
Otherwise, you should have plenty resources including on SO:
Node.js: Setting Environment Variables
How can I set an environmental variable in node.js?
https://themeteorchef.com/snippets/making-use-of-settings-json/
In short, it should look like:
METEOR_SETTINGS='{"key":"value"}' node main.js
You can also try the bash cat command to extract the content of a file: $(cat settings.json)

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

Issue with running node app using forever

So I have a node.js app in which I am using node-config-manager, to manage the various environments (development, staging, production).
I am trying to use forever to run this process in the background, however when I run forever start /path/to/main.js, it is telling me
Error: No file for this config - app.
The error is saying it's coming from line 9. When it first tries to add a configuration file, app.json.
1. import configManager from 'node-config-manager';
2. const options = {
3. configDir: './config',
4. env: 'develop',
5. camelCase: true
6. };
7. console.log(process.env.NODE_ENV);
8. configManager.init(options);
9. configManager.addConfig('app');
10. configManager.addConfig('logger');
11. configManager.addConfig('db');
export default configManager;
Inside my config folder I have three other folders, 'develop', 'staging', and 'production'.
Inside all of these folders I have three files, app.json, db.json, & logger.json.
So I am not sure what is causing the problem here. The config 'develop' does in fact exist, but there seems to be something wrong.
This app runs fine when I start it with nodemon, it's just forever thats causing problems.
Am I missing something with my understanding of how node-config-manager works? I thought all i had to do was change my NODE_ENV variable to the name of the folder inside my config directory and i'd be all set.
Thanks in advance for all the help.
the ./ directive for the config file looks at the relative path from the current working directory. forever is probably not being run from the working directory of the project, so it can't find the file.
if you project lives in /path/to then you need to provide that as the --workdingDir parameter to forever.
forever start /path/to/main.js --workingDir=/path/to/
that should take care of it

Resources