1. 程式人生 > >第二十二課預習任務

第二十二課預習任務

12.17 Nginx負載均衡 12.18 ssl原理 12.19 生成ssl金鑰對 12.20 Nginx配置ssl 12.21 php-fpm的pool 12.22 php-fpm慢執行日誌 12.23 open_basedir 12.24 php-fpm程序管理

1.Nginx負載均衡

1.1 什麼是Nginx負載均衡

網站的訪問量越來越大,伺服器的服務模式也得進行相應的升級,比如分離出資料庫伺服器、分離出圖片作為單獨服務,這些是簡單的資料的負載均衡,將壓力分散到不同的機器上。有時候來自web前端的壓力,也能讓人十分頭痛。怎樣將同一個域名的訪問分散到兩臺或更多的機器上呢?這其實就是另一種負載均衡了,nginx自身就可以做到,只需要做個簡單的配置就行。

  nginx不單可以作為強大的web伺服器,也可以作為一個反向代理伺服器,而且nginx還可以按照排程規則實現動態、靜態頁面的分離,可以按照輪詢、ip雜湊、URL雜湊、權重等多種方式對後端伺服器做負載均衡,同時還支援後端伺服器的健康檢查。

Nginx負載均衡一些基礎知識:

1.2 nginx的upstream支援的4種方式

nginx 的 upstream目前支援 4 種方式的分配 

1)、輪詢(預設) 

  每個請求按時間順序逐一分配到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。 

2)、weight 

  指定輪詢機率,weight和訪問比率成正比,用於後端伺服器效能不均的情況。 

2)、ip_hash 

  每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端伺服器,可以解決session的問題。  

3)、fair(第三方) 

  按後端伺服器的響應時間來分配請求,響應時間短的優先分配。  

4)、url_hash(第三方)

1.3 配置檔案

//新建一個load.conf,寫入以下這段配置檔案
[[email protected] ~]# vim  /usr/local/nginx/conf/vhost/load.conf
upstream  qq               
{
    ip_hash;
    server   61.135.157.156:80;
    server   125.39.240.113:80;
}
 
server
{
    listen  80;
    server_name  www.qq.com;
 
    location / {
        proxy_pass        http://qq;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    }
}

1.4 測試負載均衡

//沒有配置前出現的是預設頁面
[[email protected] ~]#curl -x127.0.0.1:80 www.qq.com
This is the default directory.

//如果配置了負載均衡就會出現原始碼
[[email protected] ~]# curl -x127.0.0.1:80 www.qq.com
<div class="txtArea">
		<h3><a href="http://new.qq.com/omn/20180920/20180920A1ZV4G.html" target="_blank">א԰ɼۈºǿˆɱɫ8ǿ Ԑλ´³ɫ¾?/a></h3>
	</div>
	<ul>
														  <li>
    <a href="http://new.qq.com/omn/20180921/20180921A0J6D8.html" target="_blank">¼ªЩɽ±¦°ְ׍»Ȼȥˀ£¬Ū½?軀a>
  </li>

												  <li>
    <a href="http://new.qq.com/omn/20180921/20180921A0KUHD.html" target="_blank">¸ࠌ?Ȗ·¸³˿ͺϷ¨ȨӦ ˭4Ϊ̻ćñµ¥£¿</a>
  </li>
......................................................
	var _mtac = {};
	(function() {
	    var mta = document.createElement("script");
	    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.2";
	    mta.setAttribute("name", "MTAH5");
	    mta.setAttribute("sid", "500460529");
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(mta, s);
	})();
	</script>
</body>
</html><!--[if !IE]>|xGv00|f6adb1516cb9c807847e8347fd4c6dde<![endif]-->

2.ssl原理

2.1 什麼是ssl

SSL:Secure Sockets Layer,即安全套接層,及其繼任者傳輸層安全是為網路通訊提供安全及資料完整性的一種安全協議。例如:我們輸入網址時,例如我們訪問百度時,訪問的網址是www.baidu.com,但是你可以試一下,你在網址欄上輸入後回車跳轉,會加上HTTPS,這就是加上了HTTPS協議,加密傳輸,安全性更高。

2.2 SSL處理過程

1.瀏覽器傳送地址到伺服器。

2.伺服器傳送數字證書以及伺服器的公鑰給瀏覽器。

3.瀏覽器用預製的CA列表驗證證書,如果有問題,立即提示風險。

4.如果正確,瀏覽器產生隨機對稱金鑰,並且用伺服器的公鑰加密。

5.伺服器用自己的私鑰進行解密,並且得到對稱金鑰。

6.伺服器給瀏覽器傳送它想要的內容,通訊通道建立並安全。

3.生成ssl金鑰對

3.1 生成型別為rsa格式的私鑰

//密碼設定為123456
[[email protected] conf]# openssl genrsa -des3 -out tmp.key 2048
Generating RSA private key, 2048 bit long modulus
..............+++
............................................+++
e is 65537 (0x10001)
Enter pass phrase for tmp.key:
Verifying - Enter pass phrase for tmp.key:

3.2 轉換key,取消密碼

//轉換key,取消密碼
[[email protected] conf]# openssl rsa -in tmp.key -out knightlai.key
Enter pass phrase for tmp.key:
writing RSA key
刪除金鑰檔案
[[email protected] conf]# rm -f tmp.key

3.3 生成證書請求檔案

//生成請求檔案目的是為了讓請求檔案和私鑰一起去生成一個公鑰。
[[email protected] conf]# openssl req -new -key knightlai.key -out knightlai.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:11
State or Province Name (full name) []:knightlai
Locality Name (eg, city) [Default City]:jiangxiang^H^H^H^[[D^[[D
Organization Name (eg, company) [Default Company Ltd]:px
Organizational Unit Name (eg, section) []:px
Common Name (eg, your name or your server's hostname) []:px
Email Address []:[email protected]^H^H

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:123456
An optional company name []:px


//建立公鑰
[[email protected] conf]# openssl x509 -req -days 365 -in knightlai.csr -signkey knightlai.key -out knightlai.crt
Signature ok
subject=/C=11/ST=knightlai/L=jiangxiang\x08\x08\x08\x1B[D\x1B[D/O=px/OU=px/CN=px/[email protected]\x08\x08
Getting Private key
//crt是公鑰,key是私鑰
[[email protected] conf]# ll
-rw-r--r-- 1 root root 1289 Sep 12 01:16 knightlai.crt
-rw-r--r-- 1 root root 1106 Sep 12 01:14 knightlai.csr
-rw-r--r-- 1 root root 1679 Sep 12 01:10 knightlai.key

4.Nginx配置ssl

4.1 建立配置檔案

[[email protected] conf]# vim ssl.conf
server
{
    listen 443;
    server_name aming.com;
    index index.html index.php;
    root /data/wwwroot/yolks.com;
    ssl on; #開啟ssl即支援https
    ssl_certificate yolkslinux.crt; #指定公鑰
    ssl_certificate_key yolkslinux.key; #指定私鑰
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #協議
}

4.2 重新編譯nginx

[[email protected] vhost]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] unknown directive "ssl" in /usr/local/nginx/conf/vhost/ssl.conf:7
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

//增加ssl_module模組重新編譯
[[email protected] nginx]# cd /usr/local/src/nginx-1.8.0
[[email protected] nginx-1.8.0]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module
checking for OS
 + Linux 3.10.0-862.el7.x86_64 x86_64
checking for C compiler ... found
 + using GNU C compiler
 + gcc version: 4.8.5 20150623 (Red Hat 4.8.5-28) (GCC) 
checking for gcc -pipe switch ... found
checking for gcc builtin atomic operations ... found
checking for C99 variadic macros ... found
checking for gcc variadic macros ... found
checking for unistd.h ... found
checking for inttypes.h ... found
checking for limits.h ... found
[[email protected] nginx-1.8.0]# make &&make install
make -f objs/Makefile
make[1]: Entering directory `/usr/local/src/nginx-1.8.0'
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
	-o objs/src/core/nginx.o \
	src/core/nginx.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
	-o objs/src/core/ngx_log.o \
	src/core/ngx_log.c
cc -c -pipe  -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g  -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \
	-o objs/src/core/ngx_palloc.o \
	src/core/ngx_palloc.c
.......................................

4.3 重啟nginx

[[email protected] nginx-1.8.0]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[[email protected] nginx-1.8.0]# /usr/local/nginx/sbin/nginx -s reload

[[email protected] nginx-1.8.0]# /etc/init.d/nginx restart
Restarting nginx (via systemctl):                          [  OK  ]
//檢視443埠啟動了
[[email protected] nginx-1.8.0]# netstat -lnp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      53910/nginx: master 
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      810/sshd            
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      898/master          
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      53910/nginx: master

4.4 測試ssl證書

//測試提示因為是我們自已建立的ssl證書,提示不安全的因素
[[email protected] nginx-1.8.0]# curl https://test.com
curl: (60) Peer's certificate issuer has been marked as not trusted by the user.
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
 of Certificate Authority (CA) public keys (CA certs). If the default
 bundle file isn't adequate, you can specify an alternate file
 using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
 the bundle, the certificate verification probably failed due to a
 problem with the certificate (it might be expired, or the name might
 not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
 the -k (or --insecure) option.

5.php-fpm的pool

5.1 nginx中可以開多個虛擬機器,他們都需要php提供服務,所以為了保證每個不同虛擬機器的效能,可以開啟多個php-fpm的pool服務。每個pool服務一個站點。

5.2 配置檔案

//加入include = etc/php-fpm.d/*.conf
[[email protected] nginx-1.8.0]# vim  /usr/local/php-fpm/etc/php-fpm.conf
[global]
pid = /usr/local/php-fpm/var/run/php-fpm.pid
error_log = /usr/local/php-fpm/var/log/php-fpm.log
include = etc/php-fpm.d/*.conf

[[email protected] nginx-1.8.0]# mkdir /usr/local/php-fpm/etc/php-fpm.d/

5.3 新建 pool

//新建一個www的pool
[[email protected] php-fpm.d]# vim www.conf
[www]
listen = /tmp/www.sock
listen.mode=666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024
//新建一個test的pool
[[email protected] php-fpm.d]# vim test.conf
[test]
listen = /tmp/test.sock
listen.mode=666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024

5.4 測試php-fpm的pool

//重啟一下php-fpm
[[email protected] php-fpm.d]# service php-fpm stop
Gracefully shutting down php-fpm . done
[[email protected] php-fpm.d]# service php-fpm start
Starting php-fpm  done
//檢視程序兩個pool都有了 test和www
[[email protected] php-fpm.d]# ps aux |grep php-fpm
root      53973  0.1  0.4 123740  4940 ?        Ss   01:58   0:00 php-fpm: master process (/usr/local/php-fpm/etc/php-fpm.conf)
php-fpm   53974  0.0  0.4 123680  4712 ?        S    01:58   0:00 php-fpm: pool test
..............................................
php-fpm   53993  0.0  0.4 123680  4720 ?        S    01:58   0:00 php-fpm: pool test
php-fpm   53994  0.0  0.4 123680  4716 ?        S    01:58   0:00 php-fpm: pool www
................................................................................
php-fpm   54013  0.0  0.4 123680  4724 ?        S    01:58   0:00 php-fpm: pool www

6.php-fpm慢執行日誌

6.1php-fpm有一個非常有用的功能,就是慢執行日誌。可以非常有效的用來診斷系統的問題在哪裡。尤其是當系統訪問速度慢時。

6.2 配置檔案

[[email protected] php-fpm.d]# vim www.conf
request_slowlog_timeout = 1 //執行超過一秒的語句記錄下來,生產環境中,這裡一般寫2秒鐘 
slowlog = /usr/local/php-fpm/var/log/www-slow.log //日誌存放目錄


[[email protected] php-fpm.d]# vim /usr/local/nginx/conf/vhost/test.com.conf 

6.3 新建php檔案測試慢執行

[[email protected] php-fpm.d]# vim /data/wwwroot/test.com/test.php
 <?php echo "test slow log";
 sleep(2);
 echo "done";
 ?>

6.4 測試慢執行配置是否成功

[[email protected] etc]# curl -x127.0.0.1:80 test.com/test.php
 test slow logdone
//我們這裡監聽的是1秒,實際上我們寫的程式是2秒,所以會產生慢日誌
[[email protected] etc]# curl -x127.0.0.1:80 test.com/test.php
 test slow logdone[[email protected] etc]# cat /usr/local/php-fpm/var/log/www-slow.log

[12-Sep-2018 02:38:12]  [pool www] pid 54137
script_filename = /data/wwwroot/test.com/test.php
[0x00007f0441ee91e8] sleep() /data/wwwroot/test.com/test.php:2

7.open_basedir

7.1 配置檔案

[[email protected] php-fpm.d]# vim test.conf
//加入這一行
php_admin_value[open_basedir]=/data/nginx/test.com:/tmp/

//重啟服務
[[email protected] php-fpm.d]# service php-fpm restart
Gracefully shutting down php-fpm . done
Starting php-fpm  done

7.2 配置錯誤日誌

[[email protected] php-fpm.d]# vi /usr/local/php-fpm/etc/php.ini 
 
error_log=/usr/local/php-fpm/var/log/php_errors.log
error_reporting=E_ALL
display_errors = Off
log_errors = On

//建立錯誤日誌目錄
[[email protected] php-fpm.d]# touch /usr/local/php-fpm/var/log/php_errors.log
[[email protected] php-fpm.d]# chmod 777 /usr/local/php-fpm/var/log/php_errors.log

8.php-fpm程序管理

[[email protected] etc]# cat www.conf 
[www]
listen = /tmp/www.sock
listen.mode=666
user = php-fpm
group = php-fpm
pm = dynamic //動態的
;pm = static
pm.max_children = 50 //最大子程序50個
pm.start_servers = 20 // 啟動的時候20個
pm.min_spare_servers = 5 //空閒時,最少有5個
pm.max_spare_servers = 35 //空閒時,最大有35個
pm.max_requests = 500 // 一個程序最多的請求數
rlimit_files = 1024
request_slowlog_timeout = 1  
slowlog = /usr/local/php-fpm/var/log/www-slow.log  
php_admin_value[open_basedir]=/data/wwwroot/test.com:/tmp/