怎么用Forever和nginx部署Node站點

線程持久運行

一般來說,我們在window cmd上通過node index.JS啟動一個服務(wù)器,只要不關(guān)閉,就可以一直訪問和調(diào)用接口。但是在linux上往往如果長時間不操作或者你要執(zhí)行其他操作時候,你的node服務(wù)就會斷開,用戶也不能訪問你的網(wǎng)站了。怎么辦?我們可以安裝forever模塊來解決。

npm?install?forever?-g?//?全局安裝forever模塊

由原先的啟動方式node index.js 改為 forever start index.js即可,下面列出幾個常見命令

forever?list?//?列出當前所有運行的服務(wù) forever?start?-w?index.js?//?文件改動自動重啟 forever?stopall?//?停止所有服務(wù) forever?stop?app.js?//停止其中一個node?app? forever?stop?[id]?//?forever?list?找到對應(yīng)的id,然后

當然還有許多命令,可以查閱相關(guān)模塊。一般來說最簡單的使用方式就是:

forever?start?index.js

這樣即使我們切換到其他linux路徑時或者退出時,node服務(wù)還是存在的,即別人還是可以訪問你的網(wǎng)站啦。

配置nginx

nginx是一個由俄羅斯人開發(fā)的反向代理服務(wù)器,如今已經(jīng)被全世界許多公司所使用。關(guān)于nginx的介紹以及安裝可以自己查閱資料或者到菜鳥教程快速學習一下。這里我的linux已經(jīng)安裝好了nginx了.

下面我要使用nginx來代理剛剛forever start index.js啟動的http://localhost:8089了,即通過我的域名來訪問http://localhost:8089 這個網(wǎng)站了. 查看nginx配置文件路徑

find?/?-name?nginx.conf

怎么用Forever和nginx部署Node站點

切換到里面進入修改里面配置

?server?{ ??listen????80;?#?監(jiān)聽端口?直接配置80即可 ??server_name?hellocode.xyz;?#?輸入域名會跳轉(zhuǎn)到?http://localhost:8089 ??include?/etc/nginx/default.d/*.conf; ??location?/?{ ???proxy_pass?http://118.89.33.75:8089;?#?你的node網(wǎng)站應(yīng)用 ??} ??error_page?404?/404.html; ????location?=?/40x.html?{ ??} ??error_page?500?502?503?504?/50x.html; ????location?=?/50x.html?{ ??} }

退出檢查配置是否正確

nginx?-t

怎么用Forever和nginx部署Node站點

重新加載nginx

nginx?-s?reload

打開瀏覽器 輸入網(wǎng)址即可以訪問網(wǎng)站啦 !

在訪問過程之中可能會遇到跨域問題,那么就需要node端設(shè)置支持跨域,以express框架來說,index.js中自定義一個中間件

var?allowcors?=?function(req,?res,?next)?{ ?res.header('access-control-allow-origin',?req.headers.origin); ?res.header('access-control-allow-methods',?'get,put,post,delete,options'); ?res.header('access-control-allow-headers',?'content-type'); ?res.header('access-control-allow-credentials','true'); ?next(); }; app.use(allowcors);//使用跨域中間件

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊12 分享