nginx原始碼編譯及負載均衡
Nginx是一款輕量級的Web 伺服器/反向代理伺服器及電子郵件(IMAP/POP3)代理伺服器,並在一個BSD-like 協議下發行。其特點是佔有記憶體少,併發能力強,事實上nginx的併發能力確實在同類型的網頁伺服器中表現較好,中國大陸使用nginx網站使用者有:百度、京東、新浪、網易、騰訊、淘寶等
#########################nginx原始碼編譯#######################
所需安裝包:nginx-1.14.0.tar.gz
tar zxf nginx-1.14.0.tar.gz
ls ##檢視是否解壓
cd nginx-1.14.0/src/core/
ls
vim nginx.h ## 刪除掉14行最後的NGINX_VERSION ,這樣可以不對外顯示你的版本號
cd nginx-1.14.0/auto/cc/
ls
vim gcc ##將172行 CFLAGS="$CFLAGS -g"註釋掉
原始碼編譯及安裝
cd nginx-1.14.0
./configure --help ###檢視編譯時的幫助命令
yum install gcc -y ###解決編譯過程中需要安裝的軟體
yum install -y pcre-devel
yum install -y openssl-devel
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --with-threads --with-file-aio
make
make install
cd /usr/local/nginx
ls
du -sh ##檢視剛裝檔案的大小
cd sbin/
pwd
ln -s /usr/local/nginx/sbin/nginx /sbin/ ##做軟連線
nginx -t ###檢測語法
nginx ##開啟nginx
nginx -s stop ###關閉nginx
cd /usr/local/nginx/html/ ###nginx的預設釋出目錄
測試:(測試時要開啟nginx)
在網站訪問 www.westos.org www.westos.org/test.html
cd /usr/local/nginx/html/ ###nginx的預設釋出目錄
vim test.html
########################nginx實現負載均衡######################
cd /usr/local/nginx/conf/
lscpu ##可以檢視主機的cpu數
vim /etc/security/limits.conf
寫入:
nginx - nofile 65536
ngnix -s reload ###重新載入
nginx -t ##檢查語法
nginx -s stop ##關閉nginx
useradd -M -d /usr/local/nginx/ nginx ###建立一個nginx使用者
id nginx ###檢視使用者nginx
vim nginx.conf ##編輯nginx主配置檔案(在此之前添加了一顆cpu,總共兩個)
nginx -s reload
測試輪詢:for i in {1..10};do curl www.westos.org;done
加上權重後的效果:for i in {1..10};do curl www.westos.org;done
新增ip_hash後的效果((同一個ip訪問後端伺服器不變):for i in {1..10};do curl www.westos.org;done
###################在nginx中靜態新增模組stick#######################
Sticky是nginx的一個模組,它是基於cookie的一種nginx的負載均衡解決方案,通過分發和識別cookie,來使同一個客戶端的請求落在同一臺伺服器上,預設標識名為route(新增sticky演算法後,在用瀏覽器訪問時,其通常會快取資訊,結果不會輪詢它是針對瀏覽器的,更換瀏覽器後它會改變)
1.客戶端首次發起訪問請求,nginx接收後,發現請求頭沒有cookie,則以輪詢方式將請求分發給後端伺服器。
2.後端伺服器處理完請求,將響應資料返回給nginx。
3.此時nginx生成帶route的cookie,返回給客戶端。route的值與後端伺服器對應,可能是明文,也可能是md5、sha1等Hash值
4.客戶端接收請求,並儲存帶route的cookie。
5.當客戶端下一次傳送請求時,會帶上route,nginx根據接收到的cookie中的route值,轉發給對應的後端伺服器。
1.關閉之前的nginx
nginx -s stop
2.解壓tar zxf nginx-1.10.1.tar.gz (nginx穩定版)
解壓tar zxf nginx-sticky-module-ng.tar.gz(nginx sticky模組)
3.編譯安裝(因為之前安裝的版本不支援sticky演算法,所以要重新原始碼安裝一個nginx版本,為了避免覆蓋之前的nginx)
cd nginx-1.10.1
./configure --prefix=/opt/nginx --with-http_ssl_module --with-http_stub_status_module --with-threads --with-file-aio
--add-module=/root/nginx-sticky-module-ng ##必須改變安裝路徑,不然會覆蓋之前的nginx,而且之前選擇
##的引數這次也必須選擇(這叫靜態新增模組)
make && make install
4.編輯配置檔案加上sticky演算法(在這兒為了方便把之前的複製過來)
cd /opt/nginx/conf/
cp /usr/local/nginx/conf/nginx.conf .
vim nginx.conf
5.在瀏覽器中測試
/opt/nginx/sbin/nginx -t ##新的nginx命令的絕對路徑
/opt/nginx/sbin/nginx ##開啟nginx
在瀏覽器中:www.westos.org 然後按F12
可見瀏覽器中將後端伺服器中的資訊快取,以便下次使用。