實踐NGINX的反向代理與負載均衡
阿新 • • 發佈:2018-05-17
nginx源碼安裝實踐NGINX的反向代理與負載均衡
安裝nginx過程
[root@lb01 opt]# yum install pcre-devel openssl-devel -y [root@lb01 opt]# wget -q http://nginx.org/download/nginx-1.10.2.tar.gz [root@lb01 opt]# useradd nginx -s /sbin/nologin -M [root@lb01 opt]# tar xf nginx-1.10.2.tar.gz -C /usr/src/ [root@lb01 opt]# cd /usr/src/nginx-1.10.2/ [root@lb01 nginx-1.10.2]# ./configure --prefix=/usr/local/nginx-1.10.2 --user=nginx --group=nginx --with-http_stub_status_module --with-http_ssl_module [root@lb01 nginx-1.10.2]#make;make install [root@lb01 nginx-1.10.2]# cd /usr/local/ [root@lb01 local]# ln -s /usr/local/nginx-1.10.2/ /usr/local/nginx [root@lb01 local]# echo ‘export PATH=/usr/local/nginx/sbin:$PATH‘>>/etc/profile [root@lb01 local]# source /etc/profile [root@lb01 local]# nginx [root@lb01 local]# lsof -i:80
配置nginx負載服務器文件
[root@lb01 conf]# egrep -v "#|^$" nginx.conf.default > nginx.conf [root@lb01 conf]# vim nginx.conf worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream server_pools { --在http區塊裏upstream模塊,將web節點的IP或著域名放置池中 server 10.0.0.11:80 weight=1 max_fails=3 fail_timeout=10; --weight 權重 server 10.0.0.14:8081 weight=1 max_fails=3 fail_timeout=10; --max_fails失敗的嘗試次數 server 10.0.0.14:8082 weight=1 max_fails=3 fail_timeout=10; --fail_timeout 失敗後的再次嘗試時間 } server { listen 80; server_name bbs.etiantian.org; location / { proxy_pass http://server_pools; --proxy模塊調用upstream模塊池裏面的web節點, proxy_set_header Host $host; --該參數在訪問後端服務器的時候 會帶上hosts信息。定義虛擬主機的信息標簽 proxy_set_header X-Forwarded-For $remote_addr; --代理的時候在會顯示真實客戶客戶端IP地址 } } 配置完成了檢測語法重啟服務 [root@lb01 conf]# nginx -t nginx: the configuration file /usr/local/nginx-1.10.2/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx-1.10.2/conf/nginx.conf test is successful [root@lb01 conf]# nginx -s stop [root@lb01 conf]# nginx
查看web服務器的首頁文件(下面3臺web服務器是之前實驗做好了的)
查看nginx服務器上的首頁文件 [root@nginx ~]# cat /usr/local/nginx/html/www.anuo1.com/index.html anuo nginx web --111111 查看tomcat多實例服務器的首頁文件 [root@tomcat ~]# cat /usr/local/tomcat1/webapps/ROOT/index.jsp anuo tomcat web111111 [root@tomcat ~]# cat /usr/local/tomcat2/webapps/ROOT/index.jsp anuo tomcat web2
測試訪問
[root@lb01 ~]# ifconfig eth0 --查看確認負載均衡服務器的IP
eth0 Link encap:Ethernet HWaddr 00:0C:29:9F:CF:C6
inet addr:10.0.0.13 Bcast:10.0.0.255 Mask:255.255.255.0
……
進行測試:
[root@lb01 conf]# elinks -dump 10.0.0.13 --elinke -dump 命令是直接將URL的內容輸出至標準輸出
anuo tomcat web111111
[root@lb01 conf]# elinks -dump 10.0.0.13
anuo tomcat web2
[root@lb01 conf]# elinks -dump 10.0.0.13
anuo nginx web --111111
nginx還有一些參數說明
ip_hash 參數
可以解決動態網頁的session共享問題,但有時會導致請求負載均衡分配不均
least_conn 參數
會根據後端節點的連接數來決定分配情況,哪個機器連接數少就分發。 就是看誰閑發送給誰
fair 參數
根據後端服務器的響應時間來分配請求,響應時間短的優先分配。
調度算法
定義輪詢調度算法 rr 默認調度算法 平均分配
定義權重調度算法 wrr
定義靜態調度算法 ip-hash
定義最小的連接數-least_conn
實踐NGINX的反向代理與負載均衡