Is there a node forever equivalent for yarn? - node.js

Right now I'm using screen in order to run my command yarn run dev-server.
I'm looking for an equivalent to something like:
forever start app.js
Except for yarn run dev-server.
dev-server in package.json is = "dev-server": "webpack-dev-server"
As everyone knows if the program crashes in screen it doesn't automatically restart.
Side note, it's a react web framework.

On an Ubuntu server, I would recommend to use systemd for running your NodeJs application.
This article has some examples how you can write a systemd unit file. If the process dies, systemd will detect it and automatically restart it.
Untested (but to sketch the idea):
[Unit]
Description=Example server
[Service]
WorkingDirectory=/path/to/my/server
ExecStart=/usr/bin/yarn run dev-server
[Install]
WantedBy=multi-user.target
Although running it through yarn is a bit weird. In a production setup, I have not seen it. Normally, you execute the server by directly running it with node (e.g., node server.js).

You can use PM2
PM2 is a daemon process manager that will help you manage and keep your application online 24/7
And for the use with yarn
pm2 start yarn --interpreter bash --name api -- start

Related

Correct command for running node.js project with pm2 in ApplicationStart hook

I want to set up ApplicationStart hook for node.js project where pm2 is used as a process manager in aws ec2 server.
I checked some tutorials and the shell script for ApplicationStart hook contains commands for running the project by using:
node/npm
pm2
for example in this tutorial, the shell script contains:
npm start
pm2 start npm --name "covidapp" -- start
in this tutorial, the shell script contains:
pm2 start npm --name "myApp"
node app.js > app.out.log 2> app.err.log < /dev/null &
Why we are running the project two times? Why we just don't use pm2?
I've deployed several apps on EC2 using PM2 and in my experience there should be no need (or benefit) to use node app.js, npm start or similar.
As you are probably already guessing, the whole point of PM2 is to run the process(es).
My recommendation would be to create a PM2 ecosystem configuration with all needed configurations, number of processes, ENV vars etc. I personally prefer this way even when running only one single node application on the server.
https://pm2.keymetrics.io/docs/usage/application-declaration/
And start the process(es) using the configuration, eg.:
pm2 start ecosystem.config.js
I also recommend using PM2 startup generator to make sure PM2 is started on server reboot: pm2 startup
https://pm2.keymetrics.io/docs/usage/startup/
Once you have the startup script generated. Start your processes using pm2 manually or by using a configuration file (see example above). Verify with pm2 status that all processes are running as expected and execute pm2 save to "snapshot" the current state. The saved state will now automatically respawn on reboot.

PM2 to start multiple Node Applications with npm start on boot(using raspberry pi)

How can I run multiple nodejs applications using command npm start in different directories using pm2 on boot? Also how do i setup them to start again if any error occurs?
I figured out how to start npm start with pm2 using - "pm2 start npm -- start"
but I don't understand how to set up them to boot.
Based on my research "pm2 startup" gives the command to setup startup which I passed as it is in the terminal.
How do I set up the rest?
Thanks,
If you've already got the part where pm2 automatically starts when you reboot, that's good.
You then need to add each of your apps to pm2.
Go into each of your project directories and run
pm2 start your_file.js --name=my_app, where your_file.js is the file you would use to start with regular node. (ie: node server.js, or node index.js, etc.) and my_app is a friendly name that you will see with pm2 status and can use to apply future commands to.
This should start your app. If you run pm2 status it is hopefully in the "running" state.
To save it so that it automatically gets booted when you reboot or restart pm2 you need to run pm2 save whenever you change app configurations.
You can do this for as many apps as you need to start.

Amazon EC2 NodeJS server stops itself after 2 days even after using sudo nohup

I have my app running on http://talkwithstranger.com/ and I have deployed it on AWS EC2. I use this command
sudo nohup node index.js &
To continue running my Node JS server even if I close my terminal and exit my SSH.
However, after 2 days everytime I wake up and I find out that the node server itself stops automatically. I checked the running processes by using
ps -ef
and my node script is not there.
Google Chrome say site DNS not found, because NodeJS Express is not running of course to serve my html file, but why it stops itself?
What is causing this unexpected shutdown of my server after every 2 days? I have to manually run nohup again to run it again.
Does nohup has a time to expire or something ?
You should run node.js using a service / process manager. You can use something basic such as forever or supervisord but I would actually advise you to take a look at PM2.
It can do a lot of things - one of them being that it manages your process, makes sure it keeps running, restarts it when it fails, manages the logs, etc. You can also have it autostart when you restart the server.
It becomes really powerful in combination with https://pm2.io, because this enables you to monitor your server's metrics such as CPU and memory remotely and see whether exceptions happened, and much more (such as even remotely updating the software by pulling from git). However, they no longer offer a free plan unfortunately - their plans now start at $79/month, which is a pity. But don't worry, the PM2 application itself is still free and open source, only the monitoring costs money.
Basic usage of PM2:
npm install -g pm2
...to install PM2.
pm2 start my_script.js
Starts a script and lets it run in background.
pm2 status
Shows the status of any running scripts.
pm2 restart all
Restarts all running scripts.
pm2 kill
Stops all scripts and completely shuts down the PM2 daemon.
pm2 monit
Monitors CPU/RAM usage and shows it.
pm2 logs
Shows the last 20 output and error log lines and starts streaming live logs to the console. The logs are stored in the folder ~/.pm2/logs.
Using PM2, your script will not stop - at most, it will restart. And if it does you will be able to more easily understand why because you can easily access logs and watch what happenes with memory usage, etc.
Extra tips:
To avoid filling up the harddisk with logfiles, I recommend installing the module pm2-logrotate:
pm2 install pm2-logrotate
To automatically launch PM2 with the same script on startup when the server starts, you can first save the current configuration:
pm2 save
...and then use the following command to install a startup script - follow the instructions displayed, which will be different based on the exact OS you are using:
pm2 startup
To use PM2 in a more advanced way with multiple processes, custom environment variables, etc., take a look at ecosystem files.
You can try forever.Install using the following command.
npm install -g forever
Then just start forever:
forever start index.js
Another better option for production use is pm2.You can install pm2 with below command
npm install -g pm2
# or
yarn global add pm2
start server
pm2 start index.js
The best thing is you can achieve load balancing with pm2(utilize all available CPU)
pm2 start index.js -i max
For more info, you can visit pm2 documentation page.

Autostart Node.js app (Ghost Blog) on server restart

After my preparation and installation of Ghost, I'm stuck with setting my DO Ubuntu to auto-start itself on server restart. I was suggested to use forever, and I do use it, however as far as I can understand from the concept of it; forever is just to keep the process running once it's started, and it vanishes (needs to be manually started) on each restart.
I'm looking for a solid solution that will keep multiple nodejs apps alive, even when the server is restarted or completely crashed.
For howtoinstallghost.com, allghostthemes.com, ghostforbeginners.com we use pm2 to keep Ghost running. We have a write up on how to setup pm2 here:
http://www.allaboutghost.com/keep-ghost-running-with-pm2/
DigitalOcean's one-click Ghost app use an Upstart script to have Ghost start on boot. It looks like:
description "Ghost: Just a blogging platform"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]
# If the process quits unexpectedly trigger a respawn
respawn
setuid ghost
setgid ghost
env NODE_ENV=production
chdir /var/www/ghost
exec /usr/local/bin/npm start --production
pre-stop exec /usr/local/bin/npm stop --production
and it is installed to /etc/init/ghost.conf This has the added benefit of allowing you manage it like any other service on your server with commands like sudo service ghost restart
You want to set it up as an init.d script so that you can start it or stop it as a service (and set it up to autostart using chkconfig).
Details are here: https://help.ubuntu.com/community/UbuntuBootupHowto
Note that's in addition to using things like Forever and Monit to restart on service crash and so on.

How does one start a node.js server as a daemon process?

In Python Twisted, you have the twistd command that helps you with a number of things related to running your application (daemonize it for example).
How do you daemonize a node.js server so that it can run even after the current session is closed?
Forever is answer to your question.
Install
$ curl https://npmjs.org/install.sh | sh
$ npm install forever
# Or to install as a terminal command everywhere:
$ npm install -g forever
Usage
Using Forever from the command line
$ forever start server.js
Using an instance of Forever from Node.js
var forever = require('forever');
var child = new forever.Forever('your-filename.js', {
max: 3,
silent: true,
args: []
});
child.on('exit', this.callback);
child.start();
If you need your process to daemonize itself, not relaying on forever - you can use the daemonize module.
$ npm install daemonize2
Then just write your server file as in example:
var daemon = require("daemonize2").setup({
main: "app.js",
name: "sampleapp",
pidfile: "sampleapp.pid"
});
switch (process.argv[2]) {
case "start":
daemon.start();
break;
case "stop":
daemon.stop();
break;
default:
console.log("Usage: [start|stop]");
}
Mind you, that's rather a low level approach.
To start a systemd service manager daemon, write a service file. For example, create a file /etc/systemd/system/myservice.service.
[Unit]
Description=myservice-description
After=network.target
[Service]
ExecStart=/opt/myservice-location/src/node/server.js --args=here
Restart=always
User=me
Group=group
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/opt/myservice-location
[Install]
WantedBy=multi-user.target
Be sure to shebang your server.js (or the whatever the main file is that you execute). Or else consider adding the node executable that you want to use by providing the full, absolute path in the ExecStart= attribute of the service file.
#!/usr/bin/env node
// here is the content of the file "server.js"
...
Remember to update the service manager daemon after every change to the myservice.service file.
$ systemctl daemon-reload
Then start the service running and enable the service to start at boot.
$ systemctl start myservice
$ systemctl enable myservice
UPDATE: i updated to include the latest from pm2:
for many use cases, using a systemd service is the simplest and most appropriate way to manage a node process. for those that are running numerous node processes or independently-running node microservices in a single environment, pm2 is a more full featured tool.
https://github.com/unitech/pm2
http://pm2.io
it has a really useful monitoring feature -> pretty 'gui' for command line monitoring of multiple processes with pm2 monit or process list with pm2 list
organized Log management -> pm2 logs
other stuff:
Behavior configuration
Source map support
PaaS Compatible
Watch & Reload
Module System
Max memory reload
Cluster Mode
Hot reload
Development workflow
Startup Scripts
Auto completion
Deployment workflow
Keymetrics monitoring
API
The simplest approach would just to send the command to the background.
$ node server.js &
Then you can kill the process at a later time. I usually do the following:
$ killall node
Note: I'm running OS X.
You can try:
$ nohup node server.js &
It work for me on Mac and Linux.
The output will be in the ./nohup.out file
But I still recommend you use pm2 or forever, because they are easily used for restarting, stopping and logging.
There are more advanced general-purpose runners, such as monit and runit.
For the background on the normal way to daemonise on a POSIX system you can search for the C method.
I have not seen enough methods in the node.js API to allow it to be done the C way by hand. However, when using child_process, you can have node.js do it for you:
http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options
I consider this a potential waste of time because there's a good chance your system provides the same.
For example:
http://libslack.org/daemon/manpages/daemon.1.html
If you want something portable (cross platform) the other posts offer solutions that might suffice.
2022 - PM2
There is a better and one of the most popular solutions for that and it's called pm2 (npm package link).
To run one or multiple Node.js servers you need to install it: npm install pm2 -g
To run: pm2 start app.js
To stop: pm2 stop nameOfAppFromList
You can also list your running apps pm2 list
To check logs of a specific one, run pm2 logs nameOfAppFromList

Resources