1. 程式人生 > >在Ubuntu下安裝nodejs4.x,並實現開機自動啟動forever程序守護nodejs應用後臺執行

在Ubuntu下安裝nodejs4.x,並實現開機自動啟動forever程序守護nodejs應用後臺執行

一、在Ubuntu下安裝nodejs4.x

官方文件的方法最簡單,不會出錯

Node.js v4.x:

    NOTE: If you are using Ubuntu Precise or Debian Wheezy, you might want to read about running Node.js >= 4.x on older distros.

# Using Ubuntu
<strong>curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -
sudo apt-get install -y nodejs</strong>

# Using Debian, as root
curl -sL https://deb.nodesource.com/setup_4.x | bash -
apt-get install -y nodejs

使用nodejs -v檢視是否安裝成功

來源官方文件

http://nodejs.cn/download/package-manager/#debian-and-ubuntu-based-linux-distributions

https://github.com/nodesource/distributions

二,開機自動啟動forever程序守護nodejs應用後臺執行

https://github.com/foreverjs/forever

超簡單的forever,用到的主要命令

forever start app.js

檢視所有正在執行的node程序

forever list


先寫一個指令碼檔案,檔名是<filename>,檔案裡面要寫全路徑哦~

#!/bin/sh

forever start <the path is "/home....">/app.js
先看看指令碼寫對了沒有
./<filename>

把這個指令碼檔案複製到 /etc/init.d目錄下去

sudo cp -i <filename> ./etc/init.d
設定指令碼檔案的許可權
sudo chmod +x /etc/init.d/test
將指令碼放到啟動指令碼中去
cd /etc/init.d
sudo update-rc.d <filename> defaults <number>
<number>是這個指令碼的啟動的順序號,去這個etc資料夾下面的這幾個資料夾中看看,選個合適的數字


輸出參考如下 http://rongjih.blog.163.com/blog/static/33574461201111504843245/

不想啟動這個指令碼啦?
解除安裝啟動指令碼的方法:
cd /etc/init.d
sudo update-rc.d -f <filename> remove
命令輸出的資訊和上圖有點像,不貼了

三、關於forever的一些注意事項

開機自動啟動的forever啟動的node程序用forever list命令並不能查到,想要查應該用linux系統的命令

ps -ax

然後會看到所有的程序,由於開機啟動的原因,forever monitor的程序和node的程序比較靠前

如果此時修改node app的程式碼,會node的程序依舊完美執行。

想要讓改動生效的話,請檢視node的app.js程序的pid

sudo kill <pid>
然後forever 會自動重啟node程序,完美~
用list命令可以發現有新的node程序,pid是新的