【NodeJs】Linux安裝NodeJs並配合Nginx實現反向代理
Linux安裝NodeJs並配合Nginx實現反向代理
NodeJs
是什麼
Node.js是一個Javascript執行環境(runtime)。實際上它是對Google V8引擎進行了封裝。V8引 擎執行Javascript的速度非常快,效能非常好。
Node.js對一些特殊用例進行了優化,提供了替代的API,使得V8在非瀏覽器環境下執行得更好。
本地安裝(OS X)
版本選擇
- V4.4.4,長期支援版本,成熟可靠
- V6.2.0 穩定版本,最新特性
這裡我還是傾向於使用最新的版本~
下載安裝包
https://nodejs.org/dist/v6.2.0/node-v6.2.0.pkg
雙擊安裝安裝包
下一步下一步,就安裝完成了。
簡單執行
node -v
v6.2.0
本地執行(OS X)
建立demo檔案
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
}) ;
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
寫入到檔案example.js
執行檔案
node example.js
這時命令列輸出Server running at http://127.0.0.1:3000/
同時在瀏覽器輸入http://127.0.0.1:3000/
,頁面輸出Hello World
關閉終端,頁面不再可用。
Express框架
我們這裡採用Express框架進行網站專案demo的搭建。
npm install express
node_modules
建立demo.js檔案
var express = require('express');
app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8081)
在同級資料夾建立public
資料夾,裡面放入靜態檔案1.jpg
在瀏覽器輸入http://127.0.0.1:8081/1.jpg
檢視Response Headers,X-Powered-By:Express
伺服器安裝(CentOS 7)
安裝node
curl --silent --location https://rpm.nodesource.com/setup | bash -
yum -y install nodejs
yum install npm
關於Node的版本
我上一步通過node安裝的版本號是v0.10.42
,一開始以為錯了,經過查資料發現,目前node共維護了4個版本
- v0.10.42 (LTS)
- v0.12.10 (LTS)
- 4.4.5 LTS
- 6.2
呵呵噠,真亂。
編寫demo例項
這部分的流程跟上面的一致。
安裝forever 並執行
npm install forever -g
forever start app.js
配置Nginx
cd /usr/local/nginx/conf/vhost/
vi demonode.coderfix.cn.conf
server {
listen 80;
server_name demonode.coderfix.cn;
location / {
proxy_pass http://127.0.0.1:8899;
}
}
Nginx解析域名,轉發給本地的nodejs的8899埠~
配置域名解析並訪問
http://demonode.coderfix.cn/
這樣就完成了nodejs和nginx的部署。
可能出現的問題
Nodejs服務多開導致報錯
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:884:11)
at Server._listen2 (net.js:1022:14)
at listen (net.js:1044:10)
at Server.listen (net.js:1110:5)
at Object.<anonymous> (folderName/app.js:33:24)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
關掉之前啟動的程序,再開就好了。
ps aux | grep node
kill -9 ****