How to run node js even on server restart - node.js

I built a Nodejs project and now it runs smoothly.
I use forever service for running file in background but if server get restarted
the daemon won't be started automatically and should be started manually.
I want to run the daemon even the server get rebooted

You could add the forever command in .bash_profile so that every time the server restart, your command will simply be also executed.
nano ~/.bash_profile
forever start app.js # add this command to the file, or whatever command you are using.
source ~/.bash_profile # very important, else changes will not take effect
Next time, on your server restart, your command will also run, hence creating a daemon of your node script.
Note: This is maybe not the best solution, but the one I have got.
Update
As #dlmeetei, suggested, you can also start your nodejs app like a service so that we can use the features given by a linux service.
First create a file in /etc/systemd/system, like:
touch /etc/systemd/system/[your-app-name].service
nano /etc/systemd/system/[your-app-name].service
Then, add and edit the following script according to your relevance.
[Unit]
Description=Node.js Example Server
#Requires=After=mysql.service # Requires the mysql service to run first
[Service]
ExecStart=/usr/local/bin/node /opt/nodeserver/server.js
# Required on some systems
# WorkingDirectory=/opt/nodeserver
Restart=always
# Restart service after 10 seconds if node service crashes
RestartSec=10
# Output to syslog
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=nodejs-example
#User=<alternate user>
#Group=<alternate group>
Environment=NODE_ENV=production PORT=1337
[Install]
WantedBy=multi-user.target
Enable the service, it will marks the service for starting up on boot.
systemctl enable [your-app-name].service
Manage the service
systemctl start [your-app-name].service
systemctl stop [your-app-name].service
systemctl status [your-app-name].service # ensure your app is running
systemctl restart [your-app-name].service
Reference: https://www.axllent.org/docs/view/nodejs-service-with-systemd/
Thanks #dlmeetei for sharing the link.

Related

Bash script to run automatically after server restart

I have a script, it restarts tomcat in 2 minutes,, I would like that
this script was started constantly after server restart, I will be grateful if someone shows how to do it?
#! /bin/bash
sleep 120
systemctl restart tomcat
Read archwiki about systemd/Timer or maybe original freedesktop documentation about systemd.timer.
Create a file my_super_tomcat_restarter.timer in /etc/systemd/system/:
[Unit]
Description=Superbly restart my tomcat service every 120 seconds!
[Timer]
OnBootSec=120sec
OnUnitActiveSec=120sec
[Install]
WantedBy=timers.target
Create a file my_super_tomcat_restarter.service in /etc/systemd/system/ with the content:
[Unit]
Description=Superbly restart tomcat service!
[Service]
Type=oneshot
ExecStart=/usr/bin/systemctl restart tomcat
Execute from your terminal as root:
systemctl enable my_super_tomcat_restarter.timer
The timer should fire in 120 seconds and execute my_super_tomcat_restarter.service which in turn will restart your tomcat service.
either add it in init.d or systemd based on your Linux distribution of yours. in both cases you have to be root to add your script.

How to restart a running python script if the Ubuntu 16.04 server crashes automatically?

I have a simple script
#!/usr/bin/env python
# coding: utf-8
i=0
while (True):
print(i)
i=i+1
I want this script to run in background
If the server crashes, I want it to automatically restart an pick where the program left of
How do I do that
You have tu run your script as a service:
The file must have .service extension under /lib/systemd/system/ directory.
Now Your system service has been added to your service. Let’s reload the systemctl daemon to read new file. You need to reload this deamon each time after making any changes in in .service file.
sudo systemctl daemon-reload
Now enable the service to start on system boot, also start the service using the following commands.
sudo systemctl enable dummy.service
sudo systemctl start dummy.service
I personally use supervisord to handle processes. To make your script start where it left off you need some kind of persistence, like a file or a database where you can put the last state of your script and read at the restart.

What is the best way to run a Node.js script as service in Ubuntu?

I have a Node.js script that keeps my MongoDB database and the CRM database synced in real-time.
I want to run this script as a background task on my Ubuntu server. I found this solution, but it doesn't work for me. Is there another approach to reach this?
If you just want to start your application, you could use Forever or PM2 for running and auto-restarting on crash. However, this is not a background task.
For a background task that starts on server reboot, the post you linked is the right way to go. If it didn't work, maybe this article will help you. This is from official Express site: Process managers for Express apps
Basically, you create
[Unit]
Description="My Express App"
[Service]
ExecStart=/usr/bin/node server.js
WorkingDirectory=/project/absolute/path
Restart=always
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=MyApp
Environment=NODE_ENV=production PORT=8080
[Install]
WantedBy=multi-user.target
Into a /etc/systemd/system/my-app.service file and then use systemctl to start it:
systemctl enable my-app.service
systemctl start my-app.service
Now this assumes your Linux distribution works with systemctl. If your Linux distribution works with upstart or something else, then you need to google up the instruction for that process manager.

Create a startup script for meteor in linux server

I have followed some posts and tutorials as well to create a script to start meteor project when server restart. i have followed answer mentioned in : How to run meteor on startup on Ubuntu server
Then I gave executable permission to script with "chmod +x meteor-server.sh".
I have tried to put this script in /etc/init.d and /etc/init folders but meteor project does not start at the reboot. I'm using ubuntu 16.04.
I would be grateful if you can show me the fault that i have done. Following code is my "meteor.server.sh" script file.
# meteorjs - meteorjs job file
description "MeteorJS"
author "Jc"
# When to start the service
start on runlevel [2345]
# When to stop the service
stop on runlevel [016]
# Automatically restart process if crashed
respawn
# Essentially lets upstart know the process will detach itself to the background
expect fork
# Run before process
pre-start script
cd /home/me/projects/cricket
echo ""
end script
# Start the process
exec meteor run -p 4000 --help -- production
First of all, there's already a very good tool mupx that allows you to deploy meteor projects to your own architecture, so there's really no need to do it by yourself unless you have a very good.
If you really need to deploy manually, this will take several steps. I am not going to cover all the details because you're specifically asking about the startup script and the remaining instruction should be easily accessible in the Internet.
1. Prepare your server
Install MongoDB unless you are planning to use a remote database.
Install NodeJS.
Install reverse proxy server, e.g. Nginx, or haproxy.
Install Meteor, which we will use as the build tool only.
2. Build your app
I am assuming here that you already have the source code of your app put on the server to which you're planning to deploy. Go to your project root and run the following command:
meteor build /path/to/your/build --directory
Please note that if /path/to/your/build exists it will be recursively deleted first, so be careful with that.
3. Install app dependencies
Go to /path/to/your/build/bundle/programs/server and run:
npm install
4. Prepare a run.sh script
The file can be of the following form:
export MONGO_URL="mongodb://127.0.0.1:27017/appName"
export ROOT_URL="http://myapp.example.com"
export PORT=3000
export METEOR_SETTINGS="{}"
/usr/bin/env node /path/to/your/build/bundle/main.js
I will assume you put it in /path/to/your/run.sh. A couple of notes here:
This form of MONGO_URL assumes you have MongoDB installed locally.
You will need to instruct your reverse proxy server to point your app trafic to port 3000.
METEOR_SETTINGS should be the output of JSON.stringify(settings) of whatever settings object you may have.
5. Prepare upstart script
With all the preparations we've made so far, the script can be as simple as
description "node.js server"
start on (net-device-up and local-filesystems and runlevel [2345])
stop on runlevel [016]
respawn
script
exec /path/to/your/run.sh
end script
This file should go to /etc/init/appName.conf.
Finally i got it to work. I have used following 2 scripts to run meteor on the startup.
First i put this service file(meteor.service) in /etc/systemd/system
[Unit]
Description = My Meteor Application
[Service]
ExecStart=/etc/init.d/meteor.sh
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=meteor
[Install]
WantedBy=multi-user.target
I have called a scipt using this service. I put this following script(meteor.sh) in /etc/init.d
#!/bin/sh -
description "Meteor Projects"
author "Janitha"
#start service on following run levels
start on runlevel [2345]
#stop service on following run levels
stop on runlevel [016]
#restart service if crashed
respawn
#set user/group to run as
setuid janitha
setgid janitha
chdir /home/janitha/projects/cricket_app
#export HOME (for meteor), change dir to plex requests dir, and run meteor
script
export HOME=/home/janitha
exec meteor
end script
I make both these file executable by using
chmod +x meteor.service
chmod +x meteor.sh
And i have used following two commands to enable the service
systemctl daemon-reload
systemctl enable meteor.service
I used this configurations successfully
In /etc/init.d add a file called meteor.sh
#!/bin/sh
export HOME="/home/user"
cd /home/user/meteor/sparql-fedquest
meteor --allow-superuser
You must give executions permissions to meteor.sh
sudo chmod 644 meteor.sh
Also you must create meteor.service in /etc/systemd/system
[Unit]
Description =Portal of bibliographic resources of University of Cuenca
Author = Freddy Sumba
[Service]
ExecStart=/etc/init.d/meteor.sh
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=meteor
[Install]
WantedBy=multi-user.target
Also you must give permissions to meteor.service
$ sudo chmod 644 meteor.service
Then, we need add the service to this start each time that the server reboot
$ systemctl enable meteor.service
And finally start the service
$ service meteor start

How do I get my Golang web server to run in the background?

I have recently completed the Wiki web development tutorial (http://golang.org/doc/articles/wiki/). I had tons of fun and I would like to experiment more with the net/http package.
However, I noticed that when I run the wiki from a console, the wiki takes over the console. If I close the console terminal or stop the process with CTRL+Z then the server stops.
How can I get the server to run in the background? I think the term for that is running in a daemon.
I'm running this on Ubuntu 12.04. Thanks for any help.
Simple / Usable things first
If you want a start script without much effort (i.e. dealing with the process, just having it managed by the system), you could create a systemd service. See Greg's answer for a detailled description on how to do that.
Afterwards you can start the service with
systemctl start myserver
Previously I would have recommended trying xinetd or something similar for finer granuarlity regarding resource and permission management but systemd already covers that.
Using the shell
You could start your process like this:
nohup ./myexecutable &
The & tells the shell to start the command in the background, keeping it in the job list.
On some shells, the job is killed if the parent shell exits using the HANGUP signal.
To prevent this, you can launch your command using the nohup command, which discards the HANGUP signal.
However, this does not work, if the called process reconnects the HANGUP signal.
To be really sure, you need to remove the process from the shell's joblist.
For two well known shells this can be achieved as follows:
bash:
./myexecutable &
disown <pid>
zsh:
./myexecutable &!
Killing your background job
Normally, the shell prints the PID of the process, which then can be killed using the kill command, to stop the server. If your shell does not print the PID, you can get it using
echo $!
directly after execution. This prints the PID of the forked process.
You could use Supervisord to manage your process.
Ubuntu? Use upstart.
Create a file in /etc/init for your job, named your-service-name.conf
start on net-device-up
exec /path/to/file --option
You can use start your-service-name, as well as: stop, restart, status
This will configure your service using systemd, not a comprehensive tutorial but rather a quick jump-start of how this can be set up.
Content of your app.service file
[Unit]
Description=deploy-webhook service
After=network.target
[Service]
ExecStart=/usr/bin/go webhook.go
WorkingDirectory=/etc/deploy-webhook
User=app-svc
Group=app-svc
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=deploy-webhook-service
PrivateTmp=true
Environment=APP_PARAM_1=ParamA
Environment=APP_PARAM_2=ParamB
[Install]
WantedBy=multi-user.target
Starting the Service
sudo systemctl start deploy-webhook.service
Service Status
sudo systemctl status deploy-webhook.service
Logs
journalctl -u deploy-webhook -e
After you press ctrl+z (putting the current task to sleep) you can run the command bg in the terminal (stands for background) to let the latest task continue running in the background.
When you need to, run fg to get back to the task.
To get the same result, you can add to your command & at the end to start it in the background.
To add to Greg's answer:
To run the Go App as a service you need to create a new service unit file.
However, the App needs to know where Go is installed. The easiest way to lookup that location is by running this command:
which go
which gives you an output like this:
/usr/local/go/bin/go
With this piece of information, you can create the systemd service file. Create a file named providus-app.service in the /etc/systemd/system/ using the command below:
sudo touch /etc/systemd/system/providus-app.service
Next open the newly created file:
sudo nano /etc/systemd/system/providus-app.service
Paste the following configuration into your service file:
[Unit]
Description=Providus App Service
After=network.target
[Service]
Type=forking
User=deploy
Group=deploy
ExecStart=/usr/local/go/bin/go run main.go
WorkingDirectory=/home/deploy/providus-app
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=providus-app-service
PrivateTmp=true
[Install]
WantedBy=multi-user.target
When you are finished, save and close the file.
Next, reload the systemd daemon so that it knows about our service file:
sudo systemctl daemon-reload
Start the Providus App service by typing:
sudo systemctl restart providus-app
Double-check that it started without errors by typing:
sudo systemctl status providus-app
And then enable the Providus App service file so that Providus App automatically starts at boot, that is, it can start on its own whenever the server restarts:
sudo systemctl enable providus-app
This creates a multi-user.target symlink in /etc/systemd/system/multi-user.target.wants/providus-app.service for the /etc/systemd/system/providus-app.service file that you created.
To check logs:
sudo journalctl -u providus-app

Resources