Recently I have setup Node, Express and Jade on a CentOS 6.5 box with no other web servers or anything. I have the site working but in order to keep it up and running I have to leave a putty window open with the server running. So far no issue but if I lose power or internet my SSH connection is lost and the site goes down. Is there a way to keep my app.js running regardless of my SSH state?
You need to daemonize your application. There are many different ways to do it.
You can use daemon module for node.js.
You can start your application inside of 'screen'.
You can start your application with nohup util:
sudo -u [appuser] nohup node [path_to_your_app] > [path_to_log_file] 2>&1 &
i know this is old; but, my CentOS will not "sudo yum install forever" - gives error: "No package forever available". so i tried
"sudo -u [appuser] nohup node [path_to_your_app] > [path_to_log_file] 2>&1 &", where;
[appuser] = admin
[path_to_your_app] = server.js
[path_to_log_file] = log.txt.
still, in 5 min the sever timed out due to "broken pipe" and web page running via node server, stopped.
Related
Start nodejs app on linux server with ssh(if i close the ssh connection,app stopped why?)
1-create nodejs app -its oke
2-run on linux server -its oke(i stop the apache server)
But if i close the ssh connection(with my windows pc),app stopped.How can i solve this problem?
The most correct thing to do is to write a service file for it so whatever init system you have (likely systemd) will keep it running and manage the start/stop/restart stuff for you.
Failing that (and I don't blame you...) you can run it within the screen utility. Launch it with screen -d -m /path/to/start/script and then you can come back later and reconnect to it with screen -r or screen -r <pid of the screen session>.
Note that launching it that way won't restart it, etc. To do that, you could do something like
#!/bin/sh
while true
do
sleep 3s
/path/to/start/script
done
And call that with the screen command.
Use the nohup command to start the application. Like:
nohup THE_COMMAND_YOU_DONT_WANT_TO_STOP_WHEN_YOU_LOGOUT &
With nodemon it might be helpful to put the command to start the server in a file called myserver.sh containing:
nodemon server.js
Make sure the file is executable:
chmod +x myserver.js
And then run
nohup myserver.sh &
I've installed ElasticSearch and Kibana edge versions on a Ubuntu Linux 14 box. So that's Kibana 4 on ElasticSearch 1.4.4.
Runs and works like a charm through: ./bin/kibana
However, as soon as I disconnect my Putty session, Kibana stops working. ElasticSearch keeps listening on port 9200, but Kibana cannot be reached at 5601 anymore.
Difference seems to be that Kibana runs in the 'foreground' - since as soon as you run it - you see log messages flying by all the time. Using -q will make it quiet indeed - but not run in the background.
So I read somewhere that running it in the background might work: ./bin/kibana &. It doesn't. Neither does CTRL-Z and then bg work.
So maybe, the reason is that I run Kibana under the logged in user and when I log out, it kills all processes of that user. So I tried sudo adduser kibanarunner and sudo -u kibanarunner ./bin/kibana but that didn't do the trick either.
I want Kibana to stay up-and-running after I stop my SSH session - how can I do this?
You can detach the process from your session.
./bin/kibana &
disown
The answer from Louis-Philippe Huberdeau wasn't working for me, so this is my solution:
sh kibana-4.0.1-linux-x64/bin/kibana >> /var/log/kibana.log(or /dev/null) &
I find running Kibana4 as a service the most convenient practice. It works (near flawlessly) even after you disconnect SSH. One can (re)start/stop it with one simple command. To run Kibana as a service, first download the kibana4 init script:
cd /etc/init.d
sudo wget https://gist.githubusercontent.com/thisismitch/8b15ac909aed214ad04a/raw/bce61d85643c2dcdfbc2728c55a41dab444dca20/kibana4
Enable the Kibana4 service and you're good to go:
sudo chmod +x /etc/init.d/kibana4
sudo update-rc.d kibana4 defaults 96 9
sudo service kibana4 start
Complete credits to this answer goes to this wonderful step-by-step ELK installation guide. You can do likewise for Elasticsearch, Logstash and Logstash-forwarder as well.
You should try using
screen -d -m ./bin/kibana
Or another useful way:
nohup ./bin/kibana > kibana.log 2>&1 &
I recommend this command (ubuntu):
nohup ./kibana/bin/kibana &
I'm new to aws and recently I have been able to install node, mongod and also, FTPed project file to the server.
For mongodb,
I'm doing mongo in a separate terminal tab and starting service in another tab. I want to know how can I keep the mongo service running.
For node app,
Right now i'm doing node app in the server. How can I keep it alive too ?
Now the problem, is I open the browser with publicip:portno but nothing happens. How can I locate app and run it in the browser.
my app structure is
/
node
mongo
server.js and app related files
Using the Linux/Unix nohup command allows you to start commands that ignore the signals associated with the controlling terminal process terminating (SIGHUP). Adding the & to the command allows that command to run in the background and sending the output to /dev/null will ensure that your disk does not fill up with unnecessary log output. Here are some commands that should work:
nohup mongod >/dev/null &
node server.js >/dev/null &
This is more of a Linux/Unix command line issue I think. You can use the node module called forever to run your Node.js process in the background easily.
npm install -g forever
forever start YourScript.js
You can place an & at the end of the mongod command to place it in the background.
Ensure that in your node app you have the command app.listen("port number");
This is the "port number" that you should be using in your browser to render the page with the elastic IP from your AWS instance. Make sure that your elastic IP is configured to accept inbound requests.
To keep the service/app running in the background you can run the screen command then launch ur app/service (e.g. mongod OR node app.js). In the same terminal that your app is running press control + a + d, you should see
(detached)
printed on your screen.
This should keep your app/service running in the background.
I found an old PC and i want to use it as a dedicated Node.js test machine.
Basically i wanna write my apps on a win machine then copy them over samba to the node folder and launch them via ssh. Later, I would add an upstart script and copy it with samba to the server so that when i reboot the app starts automatically every time.
What do I need to install in order to properly run Node.js apps on my network on a dedicated Ubuntu server? Here is the list I came up with, please correct me if I'm wrong. Is there anything else?
ssh
samba (ftp or sftp should be the way to go but as it's a closed internal network and i have to access it from various os's samba is the simplest way to share files not considering security issues..most of the time i use a simple text editor)
"basic ubuntu server" files?
"LAMP" (?)
node.js
node package manager.
how do i install the latest Node.js, npm, and the init files on Ubuntu server. I saw that there was no simple sudo apt-get install nodejs npm.
What kind of script do I need to launch my apps and where do i put them (prefer native scripts)?
EDIT
After some testing i'm at a good point now, and here is what i did:
I installed ubuntu from a minimal CD
when it comes to choose the packages i selected ONLY ssh & samba
update the system
install the dependencies that u need to run node.js
install latest node from git
setup samba in my case i created the folder /var/nodejs for the scripts
put your testApp.js in the nodejs folder
start your testApp.js from ssh. *it won't work
3-update the system
sudo apt-get update && sudo apt-get upgrade
4-dependancies
sudo apt-get install g++ curl libssl-dev apache2-utils git-core make
5-install node
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install
6-setup samba sudo nano /etc/samba/smb.conf
[nodejs]
comment = nodejs
workgroup = WG
security = USER
path = /var/nodejs
server string =Node JS
browsable = yes
read only = no
writeable = yes
create mask = 0777
7-testApp.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Node.js\n');
}).listen(80, "192.168.0.1");
console.log('Server running at http://192.168.0.1:80/');
8-Now everything should run...but:
You can run nodejs only as administrator appending "sudo" in front of the launch command
else as a normal user u don't have access to most of the ports under 1000.
A. How can i lauch my app on port 80 without using sudo?
And obviously if u launch you app with the command sudo node /var/nodejs/testApp.js
if u close the terminal the app will stop.
For that we use a init script.
After some reading i found that upstart is natively installed in ubuntu server and it's probably the best way to launch your apps.
B. I know u need to put the script into /etc/init/ with your appname and .conf extension.but how does that work?
what do i need to install to properly run node.js apps on my network on a dedicated ubuntu server?
You just need to install nodejs. nodejs can run on any port, so you don't need Apache or anything else.
how do i install the latest nodejs,npm,and the init files on ubuntu
server
Try to follow the steps outlined in this guide: http://howtonode.org/how-to-install-nodejs . Use the instructions for Ubuntu.
when i reboot the app starts automatically every time
One way to do this is to write a small script that will run on boot. The script would contain the instruction:
nodejs /path/to/app/app.js
Check out this SO answer on how to run a script on boot: https://stackoverflow.com/questions/3036/files-and-scripts-that-execute-on-boot
By your question, you sound about as lazy and impatient as I am, therefore use PPAs instead of building from the source. Just follow the node.js ubuntu directions.
In-fact I'm so lazy, I refuse to type in port numbers, hence I proxy all my node.js applications with nginx. (This is also the best way, and only way I can tell to have multiple servers "listening" on port 80). [Nginx's install guide.] Once you get nginx up, follow Chris Lea's guide.(http://wiki.nginx.org/Install) for the proxy.
BTW if you installed apache, make sure you purge it sudo apt-get purge apache*. This will most likely break your php apps, but that's why you're running node right? Just google how to run php with nignx.
Now for upstart & monit. Just follow this guide. NOTE: The guide has a typo so read the comments carefully.
As for samaba, you're on your own there.
TL;DR
Answer A: guide
Answer B: sudo cp my-node-app.conf /etc/init; sudo service my-node-app start
Edit 1
Upstart is Ubuntu's native utiltiy for starting background processes. Read all about it here.
#!upstart
description "node-app"
author "me"
env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
respawn
start on runlevel [23]
script
#set enviroment vars here
export NODE_ENV=production
#Uncommit if you need a pid file for monit
#echo $$ > /var/run/node-app.pid
exec /usr/bin/node /path/to/app.js 2>&1 >> /path/to/log/file/app.log
end script
#Logs start and stop time timestamps to the file
pre-start script
echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Starting" >> /path/to/log/file/app.log
end script
pre-stop script
#Uncomment if you need a pid file for monit
#rm /var/run/yourprogram.pid
echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Stopping" >> /path/to/log/file/app.log
end script
Now start and stop your process by using service:
sudo service node-app start
Switch start with stop or status if needed.
If you are not using monit, just remove the pid lines. I really recommend using monit because you can configure it to give you email alert if your process dies or an error occurs in the log file.
What i would do:
install ubuntu
install apache and SVN, with svn repos accessible via http://
create a svn for each project
create a svn commit hook to autodeploy scripts to a folder
/svn//hooks/post-commit
REPOS="$1"
REV="$2"
cd /var/target/path
svn cleanup /var/target/path/
svn checkout -q --force file:///svn/ /var/target/path
svn cleanup /var/target/path/
exit 0
/svn//hooks/post_commit.sh
#!/bin/bash
REPOS="$1"
REV="$2"
# Files and directories can be distinguished, as directory paths are displayed with a trailing "/" character.
LOOK=/usr/bin/svnlook
SVN=/svn/
DEV=/var/target/path/
#mkdir /var/tmp/svn
cd /var/tmp/svn
for changes in `$LOOK changed $REPOS | awk '{print $1 "=" $2;}'`;
do
len=${#changes}
idx=`expr index "$changes" =`;
directory=${changes:$idx};
action=${changes:0:$idx-1};
if [ ${changes:len-1} = '/' ]
then
case "$action" in
"A" ) \
mkdir --mode=775 -p $DEV/$directory;
chown nobody:nobody $DEV/$directory;
chmod 775 $DEV/$directory;
;;
"D" ) \
rmdir $DEV/$directory;
;;
esac
else
case "$action" in
"A"|"U"|"UU" ) \
$SVN export --force --non-interactive -r HEAD -q file://$REPOS/$directory;
BASE=`basename $directory`;
DIR=`dirname $directory`;
chown nobody:nobody $BASE;
chmod 775 $BASE;
mkdir --mode=775 -p $DEV/$DIR;
cp -f --preserve=ownership $BASE $DEV/$DIR;
unlink $BASE;
;;
"D" ) \
rm -f $DEV/$directory;
;;
esac
fi
done
echo Updated dev subdomain
exit 1
install nodejs
install nodemon with npm install -g nodemon (out of my head - please check the manual)
create an upstart file for the node js script in /etc/init
description "nodejs with nodemonn"
author "etc"
start on startup
respawn
script
cd /var/target/project/dir/
exec nodemon /var/target/project/dir/main.js
end script
now all you have to do is work on the code and commit
when you commit the code is updated and the nodejs script is restarted
have fun coding !
I don't think samba is required, unless you want to develop on the server via samba. If you want to do that just skip the svn part and install samba, but setup nodemon upstart scripts - it will save you alot of hassle os ssh-ing.
I work this way because it allows me to write and test locally and then comit code to dev/test/prod servers quick and easy.
To solve the port 80 issue, just setup a firewall rule to redirect incoming tcp/80 to tcp/8080 (for instance) and listen in your nodejs script on that port.
More information here: https://serverfault.com/questions/112795/how-can-i-run-a-server-on-linux-on-port-80-as-a-normal-user
p.s. i did not add a complete step-by-step instruction for each item because there are plenty of guides out there that would a much better job than i can
on Ubuntu: startup booting Nodejs + socket.io by ubuntu user:
more /etc/init/noded.conf
# Ubuntu upstart file at /etc/init/noded.conf
description "noded.conf"
author "Nguyen Thanh Binh"
start on runlevel [2345]
stop on runlevel [06]
respawn
script
su - ubuntu -c "NODE_ENV=test exec sudo /usr/bin/node /home/ubuntu/server.js" >> /home/ubuntu/log.log &
end script
You can use forvere module to start a nodejs application in the background.
for full info see this http://blog.nodejitsu.com/keep-a-nodejs-server-up-with-forever.
and I am just running an Ubuntu dedicated server with nodejs and it's working without a problem
I connect to my remote server via ssh. Then I start my node.js app with Forever. Everything works fine until I close my console window. How to run node.js app FOREVER on my remote server even when I close my connection via ssh? I just want to start an app and shut down my copmputer. My app should be working in the background on my remote server.
You may also want to consider using the upstart utility. It will allow you to start, stop and restart you node application like a service. Upstart can configured to automatically restart your application if it crashes.
Install upstart:
sudo apt-get install upstart
Create a simple script for your application that will look something like:
#!upstart
description "my app"
start on started mountall
stop on shutdown
# Automatically Respawn:
respawn
respawn limit 99 5
env NODE_ENV=production
exec node /somepath/myapp/app.js >> /var/log/myapp.log 2>&1
Then copy the script file (myapp.conf) to /etc/init and make sure its marked as executable. Your application can then be managed using the following commands:
sudo start myapp
sudo stop myapp
sudo restart myapp
Two answers: One for Windows, one for *nix:
On Windows, you can use the start command to start the process disconnected from your instance of cmd.exe:
start node example.js
On *nix, there are two aspects of this: Disconnecting the process from the console, and making sure it doesn't receive the HUP signal ("hang up"), which most processes (including Node) will respond to by terminating. The former is possibly optional, but the latter is necessary.
Starting disconnected from the console is easy: Usually, you just put an ampersand (&) at the end of the command line:
# Keep reading, don't just grab this and use it
node example.js &
But the above doesn't protect the process from HUP signals. The program may or may not receive HUP when you close the shell (console), depending on a shell option called huponexit. If huponexit is true, the process will receive HUP when the shell exits and will presumably terminate.
huponexit defaults to false on the various Linux variants I've used, and in fact I happily used the above for years until coderjoe and others helped me understand (in a very long comment stream under the answer that may have since been deleted) that I was relying on huponexit being false.
To avoid the possibility that huponexit might be true in your environment, explicitly use nohup. nohup runs the process immune from HUP signals. You use it like this:
nohup node example.js > /dev/null &
or
nohup node example.js > your-desired-filename-or-stream-here &
The redirection is important; if you don't do it, you'll end up with a nohup.out file containing the output from stdout and stderr. (By default, nohup redirects stderr to stdout, and if stdout is outputting to a terminal, it redirects that to nohup.out. nohup also redirects stdin if it's receiving from a terminal, so we don't have to do that. See man nohup or info coreutils 'nohup invocation' for details.)
In general for these things, you want to use a process monitor so that if the process crashes for some reason, the monitor restarts it, but the above does work for simple cases.
I would definitely recommend pm2
npm install -g pm2
To start server: pm2 start [yourServerFile.js]
To stop server: pm2 stop [yourServerFile.js]
Close client and server will run forever....will also restart if app crashes.
Ive been running a node server on Ubuntu for months with zero issues
Always, simple is the best, no need upstart, no need forever, just nohup:
nohup node file.js &
Believe me, I'm running so that for my case!
You could install forever using npm like this:
sudo npm install -g forever
Or as a service:
forever start server.js
Or stop service
forever stop server.js
To list all running processes:
forever list
node expamle.js & for example
In Linux, SSH into your remote server and run
screen
to launch into a new screen.
Finally, type ctrlad to detach the screen session without killing the process.
More info here.
I had similar issue and I think using forever will help to handle crashed and restarts
You can install forever globally:
sudo nom install -g forever
And run this command:
nohup forever server.js &
This should handle all the trouble of closing the terminal, closing ssh session, node crashes and restarts.
If you're running node.js in a production environment, you should consider using PM2, forever.js, or Nodemon.
There is no shortage of articles online comparing the different packages.
This is only a partial answer for Windows. I’ve created a single line Visual Basic Script called app.vbs that will start your node application within a hidden window:
CreateObject("Wscript.Shell").Run "node app.js", 0
To execute it automatically at startup, open the %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\ directory and add a shortcut to the app.vbs file.
More info at: https://keestalkstech.com/2016/07/start-nodejs-app-windowless-windows/
Wow, I just found a very simple solution:
First, start your process (node app)
forever dist/index.js
run: ^Z cmd + z.
Then: bg. Yeah.. bg (background).
And pum.. you are out.
Finish with exitif you are with sshor just close the terminal.
my start.sh file:
#/bin/bash
nohup forever -c php artisan your:command >>storage/logs/yourcommand.log 2>&1 &
There is one important thing only. FIRST COMMAND MUST BE "nohup", second command must be "forever" and "-c" parameter is forever's param, "2>&1 &" area is for "nohup". After running this line then you can logout from your terminal, relogin and run "forever restartall" voilaa... You can restart and you can be sure that if script halts then forever will restart it.
I <3 forever