centos7離線安裝Nginx、nginx反向代理、nginx負載均衡
下載所需rmp包(包中有所有rpm)
安裝 gcc PCRE pcre-devel zlib OpenSSL
直接下載.tar.gz安裝包,地址:https://nginx.org/en/download.html(文件在包中)
cd /usr/local/
mkdir rpm
cd rpm
把rpm文件上傳
rpm -Uvh ./*.rpm --nodeps --force
cd /usr/local/
mkdir nginx
cd nginx
把nginx安裝包上傳
tar -zxvf nginx-1.15.4.tar.gz
cd nginx-1.15.4
./configure 效果如下圖:
編譯安裝
make
make install
查找安裝路徑:
whereis nginx
開放端口
添加
firewall-cmd --permanent --zone=public --add-port=80/tcp
(--permanent永久生效,沒有此參數重啟后失效)
重新載入
firewall-cmd --reload
查詢端口是否開放
firewall-cmd --query-port=80/tcp
啟動、停止nginx
cd /usr/local/nginx/sbin/
./nginx 啟動nginx
./nginx -s stop 此方式相當於先查出nginx進程id再使用kill命令強制殺掉進程
./nginx -s quit 此方式停止步驟是待nginx進程處理任務完畢進行停止
./nginx -s reload 重啟nginx(重新加載配置文件)
開機自啟動
即在rc.local增加啟動代碼就可以了。
vi /etc/rc.local
增加一行 /usr/local/nginx/sbin/nginx
設置執行權限:
chmod 755 rc.local
訪問端口如下成功:
Nginx反向代理(一台nginx 192.168.50.80,一台tomcat192.168.50.102:8080)
下載啟動tomcat 必須要有jdk環境
cd /usr/local
mkdir tomcat
上傳tomcat包 apache-tomcat-8.5.34.tar.gz
tar -zxvf apache-tomcat-8.5.34.tar.gz
cd /usr/local/tomcat/apache-tomcat-8.5.34/bin
./startup.sh
開放8080端口
添加
firewall-cmd --permanent --zone=public --add-port=8080/tcp
重新載入
firewall-cmd --reload
查詢端口是否開放
firewall-cmd --query-port=8080/tcp
關閉tomcat:
cd /usr/local/tomcat/apache-tomcat-8.5.34/bin
./shutdown.sh
切換到nginx服務器
cd /usr/local/nginx/conf
vi nginx.conf
在location/{}中加入tomcat服務器ip及端口
proxy_pass http://192.168.0.115:8080; Tomcat地址配置(被代理的地址)
./nginx -s reload 重啟nginx
現在訪問nginx會出現tomcat的頁面
Nginx負載均衡(一台nginx 192.168.50.120 兩台tomcat 192.168.50.102:8080 192.168.50.103:8080)
切換到nginx服務器
cd /usr/local/nginx/conf
vi nginx.conf
修改配置文件
添加:
upstream backend{
#ip_hash;
server 192.168.50.102:8080;
server 192.168.50.103:8080;
}
在location/{}中添加:
proxy_pass http://backend;
./nginx -s reload 重啟nginx
切換到tomcat,為演示方便查看,修改tomcat index
cd /usr/local/tomcat/apache-tomcat-8.5.34/webapps/ROOT
vi index.jsp
${pageContext.servletContext.serverInfo}-192.168.50.102 加上本機ip方便查看
另一台tomcat也是如下操作
訪問nginx會出現如下效果:
此時nginx負載均衡完成
附:
Nginx負載均衡其他幾種配置方法:
配置1:
此配置將請求轉發到兩個WEB服務器,根據客戶端IP分配目標主機,同時按權重分配流量,(weight 默認為1.weight越大,負載的權重就越大)
upstream backend {
ip_hash;
server 192.168.50.102:8080 weight=5;
server 192.168.50.103:8080 weight=3;
}
配置2:
默認負載平衡配置,nginx應用HTTP負載平衡來分發請求。
upstream backend {
server 192.168.50.102:8080;
server 192.168.50.103:8080;
}
配置3:
最小連接負載平衡配置,nginx將盡量不使用繁忙的服務器,而是將新請求分發給不太忙的服務器。
upstream backend {
least_conn;
server 192.168.50.102:8080;
server 192.168.50.103:8080;
}
配置4:
會話持久性配置,使用ip-hash,客戶端的IP地址用作散列密鑰,
以確定應為客戶端請求選擇服務器組中的哪個服務器。
此方法確保來自同一客戶端的請求將始終定向到同一服務器,除非此服務器不可用。
upstream backend {
ip_hash;
server 192.168.50.102:8080;
server 192.168.50.103:8080;
}
配置5:
加權負載平衡配置,通過使用服務器權重進一步影響nginx負載平衡算法。
未配置權重的服務器,意味着所有指定的服務器被視為對特定負載平衡方法同等資格。
如:
upstream backend {
ip_hash;
server 192.168.14.132:8080 weight=3;
server 192.168.14.133:80 weight=2;
server 192.168.14.134:80;
server 192.168.14.135:80;
}