個人博客:http://zhangsunyucong.top
前言
這篇文章適合熟悉nodejs的同學觀看。主要是關於如何使用nginx做反向代理和負載均衡nodejs的多個實例的配置流程,nodejs實例可以是分佈在同一臺主機上或者不同的主機上的多個實例。
主要內容有
- 在同一主機創建nodejs多個實例
- 詳細講解ngnix.conf文件的每項配置的作用
在同一主機創建nodejs多個實例
我的nodejs環境:
- window 7 64位
- nodejs v8.1.3
- webstorm 2017版
根目錄/server.js文件
'use strict';
var express = require('express');
var timeout = require('connect-timeout');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
// 設置模板引擎,路徑在根目錄+public中
app.set('views', path.join(__dirname, 'public'));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(express.static(path.join(__dirname, 'public')));
// 設置默認超時時間
app.use(timeout('15s'));
//請求體
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//cookie
app.use(cookieParser());
//註冊HTTP消息頭部信息
app.use(
function(req, res, next) {
res.set(
{
'Content-Type': 'text/html',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Rememberme': true,
'Access-Control-Allow-HttpOnly': false,
'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Credentials': true, //false,
'Access-Control-Max-Age': '86400', // 24 hours
'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
}
);
//decodeURI(req.url)
console.log('%s %s', req.method, req.url);
next();
}
);
//首頁
app.get('/', function(req, res) {
res.render('index1', { currentTime: new Date() });
});
app.use(function(req, res, next) {
// 如果任何一個路由都沒有返回響應,則拋出一個 404 異常給後續的異常處理器
if (!res.headersSent) {
var err = new Error('Not Found');
err.status = 404;
next(err);
}
});
// 錯誤處理
app.use(function(err, req, res, next) {
if (req.timedout && req.headers.upgrade === 'websocket') {
// 忽略 websocket 的超時
return;
}
var statusCode = err.status || 500;
if (statusCode === 500) {
console.error(err.stack || err);
}
if (req.timedout) {
console.error('請求超時: url=%s, timeout=%d, 請確認方法執行耗時很長,或沒有正確的 response 回調。', req.originalUrl, err.timeout);
}
res.status(statusCode);
// 默認不輸出異常詳情
var error = {};
if (app.get('env') === 'development') {
// 如果是開發環境,則將異常堆棧輸出到頁面,方便開發調試
error = err;
}
res.render('error', {
message: err.message,
error: error
});
});
function catchGlobalError(err) {
// 註冊全局未捕獲異常處理器
process.on('uncaughtException', function(err) {
console.error('Caught exception:', err.stack);
});
process.on('unhandledRejection', function(reason, p) {
console.error('Unhandled Rejection at: Promise ', p, ' reason: ', reason.stack);
});
}
//創建兩個服務器實體
var server = require('http').createServer(app);
var server1 = require('http').createServer(app);
//服務器監聽端口
var PORT = parseInt(process.env.PORT || 3000);
var PORT1 = PORT + 1;
server.listen(PORT, function (err) {
console.log('Node app is running on port:', PORT);
catchGlobalError(err);
});
server1.listen(PORT1, function (err) {
console.log('Node app is running on port:', PORT1);
catchGlobalError(err);
});
根目錄/views/error.ejs
<!DOCTYPE HTML>
<html>
<head>
<title>Error</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1><%= message %></h1>
<h2><%= error.status %></h2>
<pre><%= error.stack %></pre>
</body>
</html>
根目錄/views/index.ejs
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>nodejs 和 nginx</title>
<link rel="stylesheet" href="./stylesheets/style.css">
</head>
<body>
<p><h3>Hello world</h3></p>
</body>
</html>
ngnix配置文件
nginx.config
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
upstream nodeproxy {
server 192.168.10.137:3000 weight=10;
server 127.0.0.1:3001 weight=12;
}
server {
listen 8089;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
proxy_pass http://nodeproxy; #與upstream的名稱一致
proxy_redirect default;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
nginx常用命令 ###
在nginx的安裝根目錄下,打開命令行工具,運行。
啓動nginx:start nginx
重新加載配置:nginx -s reload
重新打開日誌:nginx -s reopen
關閉nginx:
快速停止:nginx -s stop
有序關閉:nginx -s quit
如果遇到啓動不了nginx,可能是監聽的端口被佔用。
使用命令:netstat -aon | findstr :80
查詢一下
用瀏覽器訪問localhost:8089,我的測試的結果是:
“D:\WebStorm 2017.2.1\bin\runnerw.exe” D:\nodejs\node.exe D:\collect\leancloud\jiangebuluo\NodeTestDemo\myServer.js
Node app is running on port: 3000
Node app is running on port: 3001
服務器監聽的IP: 192.168.10.137
服務器監聽的IP: 192.168.10.137
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 127.0.0.1
服務器監聽的IP: 192.168.10.137
服務器監聽的IP: 192.168.10.137
最後
另外貼出一個ubuntu的詳細配置講解。來自獵手家園的博客
#定義Nginx運行的用戶和用戶組
user www www;
#nginx進程數,建議設置爲等於CPU總核心數。
worker_processes 8;
#全局錯誤日誌定義類型,[ debug | info | notice | warn | error | crit ]
error_log /usr/local/nginx/logs/error.log info;
#進程pid文件
pid /usr/local/nginx/logs/nginx.pid;
#指定進程可以打開的最大描述符:數目
#工作模式與連接數上限
#這個指令是指當一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(ulimit -n)與nginx進程數相除,但是nginx分配請求並不是那麼均勻,所以最好與ulimit -n 的值保持一致。
#現在在linux 2.6內核下開啓文件打開數爲65535,worker_rlimit_nofile就相應應該填寫65535。
#這是因爲nginx調度時分配請求到進程並不是那麼的均衡,所以假如填寫10240,總併發量達到3-4萬時就有進程可能超過10240了,這時會返回502錯誤。
worker_rlimit_nofile 65535;
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型
#是Linux 2.6以上版本內核中的高性能網絡I/O模型,linux建議epoll,如果跑在FreeBSD上面,就用kqueue模型。
#補充說明:
#與apache相類,nginx針對不同的操作系統,有不同的事件模型
#A)標準事件模型
#Select、poll屬於標準事件模型,如果當前系統不存在更有效的方法,nginx會選擇select或poll
#B)高效事件模型
#Kqueue:使用於FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用雙處理器的MacOS X系統使用kqueue可能會造成內核崩潰。
#Epoll:使用於Linux內核2.6版本及以後的系統。
#/dev/poll:使用於Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。
#Eventport:使用於Solaris 10。 爲了防止出現內核崩潰的問題, 有必要安裝安全補丁。
use epoll;
#單個進程最大連接數(最大連接數=連接數*進程數)
#根據硬件調整,和前面工作進程配合起來用,儘量大,但是別把cpu跑到100%就行。每個進程允許的最多連接數,理論上每臺nginx服務器的最大連接數爲。
worker_connections 65535;
#keepalive超時時間。
keepalive_timeout 60;
#客戶端請求頭部的緩衝區大小。這個可以根據你的系統分頁大小來設置,一般一個請求頭的大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這裏設置爲分頁大小。
#分頁大小可以用命令getconf PAGESIZE 取得。
#[root@web001 ~]# getconf PAGESIZE
#4096
#但也有client_header_buffer_size超過4k的情況,但是client_header_buffer_size該值必須設置爲“系統分頁大小”的整倍數。
client_header_buffer_size 4k;
#這個將爲打開文件指定緩存,默認是沒有啓用的,max指定緩存數量,建議和打開文件數一致,inactive是指經過多長時間文件沒被請求後刪除緩存。
open_file_cache max=65535 inactive=60s;
#這個是指多長時間檢查一次緩存的有效信息。
#語法:open_file_cache_valid time 默認值:open_file_cache_valid 60 使用字段:http, server, location 這個指令指定了何時需要檢查open_file_cache中緩存項目的有效信息.
open_file_cache_valid 80s;
#open_file_cache指令中的inactive參數時間內文件的最少使用次數,如果超過這個數字,文件描述符一直是在緩存中打開的,如上例,如果有一個文件在inactive時間內一次沒被使用,它將被移除。
#語法:open_file_cache_min_uses number 默認值:open_file_cache_min_uses 1 使用字段:http, server, location 這個指令指定了在open_file_cache指令無效的參數中一定的時間範圍內可以使用的最小文件數,如果使用更大的值,文件描述符在cache中總是打開狀態.
open_file_cache_min_uses 1;
#語法:open_file_cache_errors on | off 默認值:open_file_cache_errors off 使用字段:http, server, location 這個指令指定是否在搜索一個文件是記錄cache錯誤.
open_file_cache_errors on;
}
#設定http服務器,利用它的反向代理功能提供負載均衡支持
http
{
#文件擴展名與文件類型映射表
include mime.types;
#默認文件類型
default_type application/octet-stream;
#默認編碼
#charset utf-8;
#服務器名字的hash表大小
#保存服務器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。參數hash bucket size總是等於hash表的大小,並且是一路處理器緩存大小的倍數。在減少了在內存中的存取次數後,使在處理器中加速查找hash表鍵值成爲可能。如果hash bucket size等於一路處理器緩存的大小,那麼在查找鍵的時候,最壞的情況下在內存中查找的次數爲2。第一次是確定存儲單元的地址,第二次是在存儲單元中查找鍵 值。因此,如果Nginx給出需要增大hash max size 或 hash bucket size的提示,那麼首要的是增大前一個參數的大小.
server_names_hash_bucket_size 128;
#客戶端請求頭部的緩衝區大小。這個可以根據你的系統分頁大小來設置,一般一個請求的頭部大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這裏設置爲分頁大小。分頁大小可以用命令getconf PAGESIZE取得。
client_header_buffer_size 32k;
#客戶請求頭緩衝大小。nginx默認會用client_header_buffer_size這個buffer來讀取header值,如果header過大,它會使用large_client_header_buffers來讀取。
large_client_header_buffers 4 64k;
#設定通過nginx上傳文件的大小
client_max_body_size 8m;
#開啓高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
#sendfile指令指定 nginx 是否調用sendfile 函數(zero copy 方式)來輸出文件,對於普通應用,必須設爲on。如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡IO處理速度,降低系統uptime。
sendfile on;
#開啓目錄列表訪問,合適下載服務器,默認關閉。
autoindex on;
#此選項允許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用
tcp_nopush on;
tcp_nodelay on;
#長連接超時時間,單位是秒
keepalive_timeout 120;
#FastCGI相關參數是爲了改善網站的性能:減少資源佔用,提高訪問速度。下面參數看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
#gzip模塊設置
gzip on; #開啓gzip壓縮輸出
gzip_min_length 1k; #最小壓縮文件大小
gzip_buffers 4 16k; #壓縮緩衝區
gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
gzip_comp_level 2; #壓縮等級
gzip_types text/plain application/x-javascript text/css application/xml; #壓縮類型,默認就已經包含textml,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
gzip_vary on;
#開啓限制IP連接數的時候需要使用
#limit_zone crawler $binary_remote_addr 10m;
#負載均衡配置
upstream piao.jd.com {
#upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的機率越大。
server 127.0.0.1:3000 weight=3;
server 127.0.0.1:3001 weight=2;
#nginx的upstream目前支持4種方式的分配
#1、輪詢(默認)
#每個請求按時間順序逐一分配到不同的後端服務器,如果後端服務器down掉,能自動剔除。
#2、weight
#指定輪詢機率,weight和訪問比率成正比,用於後端服務器性能不均的情況。
#例如:
#upstream bakend {
# server 192.168.0.14 weight=10;
# server 192.168.0.15 weight=10;
#}
#2、ip_hash
#每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端服務器,可以解決session的問題。
#例如:
#upstream bakend {
# ip_hash;
# server 192.168.0.14:88;
# server 192.168.0.15:80;
#}
#3、fair(第三方)
#按後端服務器的響應時間來分配請求,響應時間短的優先分配。
#upstream backend {
# server server1;
# server server2;
# fair;
#}
#4、url_hash(第三方)
#按訪問url的hash結果來分配請求,使每個url定向到同一個後端服務器,後端服務器爲緩存時比較有效。
#例:在upstream中加入hash語句,server語句中不能寫入weight等其他的參數,hash_method是使用的hash算法
#upstream backend {
# server squid1:3128;
# server squid2:3128;
# hash $request_uri;
# hash_method crc32;
#}
#tips:
#upstream bakend{#定義負載均衡設備的Ip及設備狀態}{
# ip_hash;
# server 127.0.0.1:9090 down;
# server 127.0.0.1:8080 weight=2;
# server 127.0.0.1:6060;
# server 127.0.0.1:7070 backup;
#}
#在需要使用負載均衡的server中增加 proxy_pass http://bakend/;
#每個設備的狀態設置爲:
#1.down表示單前的server暫時不參與負載
#2.weight爲weight越大,負載的權重就越大。
#3.max_fails:允許請求失敗的次數默認爲1.當超過最大次數時,返回proxy_next_upstream模塊定義的錯誤
#4.fail_timeout:max_fails次失敗後,暫停的時間。
#5.backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這臺機器壓力會最輕。
#nginx支持同時設置多組的負載均衡,用來給不用的server來使用。
#client_body_in_file_only設置爲On 可以講client post過來的數據記錄到文件中用來做debug
#client_body_temp_path設置記錄文件的目錄 可以設置最多3層目錄
#location對URL進行匹配.可以進行重定向或者進行新的代理 負載均衡
}
#虛擬主機的配置
server
{
#監聽端口
listen 80;
#域名可以有多個,用空格隔開
server_name www.jd.com jd.com;
index index.html index.htm index.php;
root /data/www/jd;
#對******進行負載均衡
location ~ .*.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#圖片緩存時間設置
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 10d;
}
#JS和CSS緩存時間設置
location ~ .*.(js|css)?$
{
expires 1h;
}
#日誌格式設定
#$remote_addr與$http_x_forwarded_for用以記錄客戶端的ip地址;
#$remote_user:用來記錄客戶端用戶名稱;
#$time_local: 用來記錄訪問時間與時區;
#$request: 用來記錄請求的url與http協議;
#$status: 用來記錄請求狀態;成功是200,
#$body_bytes_sent :記錄發送給客戶端文件主體內容大小;
#$http_referer:用來記錄從那個頁面鏈接訪問過來的;
#$http_user_agent:記錄客戶瀏覽器的相關信息;
#通常web服務器放在反向代理的後面,這樣就不能獲取到客戶的IP地址了,通過$remote_add拿到的IP地址是反向代理服務器的iP地址。反向代理服務器在轉發請求的http頭信息中,可以增加x_forwarded_for信息,用以記錄原有客戶端的IP地址和原來客戶端的請求的服務器地址。
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
#定義本虛擬主機的訪問日誌
access_log /usr/local/nginx/logs/host.access.log main;
access_log /usr/local/nginx/logs/host.access.404.log log404;
#對 "/" 啓用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#後端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可選。
proxy_set_header Host $host;
#允許客戶端請求的最大單文件字節數
client_max_body_size 10m;
#緩衝區代理緩衝用戶端請求的最大字節數,
#如果把它設置爲比較大的數值,例如256k,那麼,無論使用firefox還是IE瀏覽器,來提交任意小於256k的圖片,都很正常。如果註釋該指令,使用默認的client_body_buffer_size設置,也就是操作系統頁面大小的兩倍,8k或者16k,問題就出現了。
#無論使用firefox4.0還是IE8.0,提交一個比較大,200k左右的圖片,都返回500 Internal Server Error錯誤
client_body_buffer_size 128k;
#表示使nginx阻止HTTP應答代碼爲400或者更高的應答。
proxy_intercept_errors on;
#後端服務器連接的超時時間_發起握手等候響應超時時間
#nginx跟後端服務器連接超時時間(代理連接超時)
proxy_connect_timeout 90;
#後端服務器數據回傳時間(代理髮送超時)
#後端服務器數據回傳時間_就是在規定時間之內後端服務器必須傳完所有的數據
proxy_send_timeout 90;
#連接成功後,後端服務器響應時間(代理接收超時)
#連接成功後_等候後端服務器響應時間_其實已經進入後端的排隊之中等候處理(也可以說是後端服務器處理請求的時間)
proxy_read_timeout 90;
#設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
#設置從被代理服務器讀取的第一部分應答的緩衝區大小,通常情況下這部分應答中包含一個小的應答頭,默認情況下這個值的大小爲指令proxy_buffers中指定的一個緩衝區的大小,不過可以將其設置爲更小
proxy_buffer_size 4k;
#proxy_buffers緩衝區,網頁平均在32k以下的設置
#設置用於讀取應答(來自被代理服務器)的緩衝區數目和大小,默認情況也爲分頁大小,根據操作系統的不同可能是4k或者8k
proxy_buffers 4 32k;
#高負荷下緩衝大小(proxy_buffers*2)
proxy_busy_buffers_size 64k;
#設置在寫入proxy_temp_path時數據的大小,預防一個工作進程在傳遞文件時阻塞太長
#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
proxy_temp_file_write_size 64k;
}
#設定查看Nginx狀態的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file confpasswd;
#htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
}
#本地動靜分離反向代理配置
#所有jsp的頁面均交由tomcat或resin處理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有靜態文件由nginx直接讀取不經過tomcat或resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|
pdf|xls|mp3|wma)$
{
expires 15d;
}
location ~ .*.(js|css)?$
{
expires 1h;
}
}
}