目录
一.Nginx 反向代理功能
1.正向代理是客户端指定让代理去访问哪个服务。翻墙服务是用户自己花钱买到,所以正向代理代表的是客户端的利益, 反向代理是代理将客户端的请求分发给某个服务器。Nginx服务器是服务端搭建的,代表的是服务端的利益。
2.反向代理:reverse proxy,指的是代理外网用户的请求到内部的指定的服务器,并将数据返回给用户的 一种方式,这是用的比较多的一种方式。 nginx 本身不具备的请求通过某种预 定义的协议转发至其它服务器处理,不同的协议就是Nginx服务器与其他服务器进行通信的一种规范,主要在不同的场景使用以下模块实现不同的功能: ngx_http_proxy_module: #将客户端的请求以http协议转发至指定服务器进行处理 ngx_http_upstream_module #用于定义为proxy_pass,fastcgi_pass,uwsgi_pass #等指令引用的后端服务器分组 ngx_stream_proxy_module: #将客户端的请求以tcp协议转发至指定服务器处理 ngx_http_fastcgi_module: #将客户端对php的请求以fastcgi协议转发至指定服务器助理 ngx_http_uwsgi_module: #将客户端对Python的请求以uwsgi协议转发至指定服务器处理
3.逻辑调用关系:
同构代理:用户不需要其他程序的参与,直接通过http协议或者tcp协议访问后端服务器 。
异构代理:用户访问的资源时需要经过处理后才能返回的,比如php,python,等等,这种访问资源需 要经过处理才能被访问
#需要三台主机:
#172.25.254.100 Nginx 代理服务器
#172.25.254.10 后端node1web,Apache部署
#172.25.254.20 后端node2web,Apache部署
--------------------node1web:172.25.254.10--------------------------
yum install httpd -y
systemctl enable --now httpd
echo node1web - 172.25.254.10 > /var/www/html/index.html
dnf install php -y
systemctl restart httpd
vim /var/www/html/index.php
<?php
phpinfo();
?>
-----------------node2web:172.25.254.20---------------------------
[root@node2 ~]# yum install httpd -y
[root@node2 ~]# systemctl enable --now httpd
[root@node2 ~]# mkdir -p /var/www/html/static/
[root@node2 ~]# echo node2web static - 172.25.254.20 > /var/www/html/static/index.html
[root@node2 ~]# vim /etc/httpd/conf/httpd.conf
....
#listen 12.34.56.78:80
listen 8080
....
[root@node2 ~]# systemctl restart httpd
测试:在nginx端curl一下。
[root@nginx ~]# curl 172.25.254.20:8080/static/
node2web static - 172.25.254.20
[root@nginx ~]# curl 172.25.254.10
node1web - 172.25.254.10
----------------------nginx:172.25.254.100-----------------------
#nginx
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaozhuhzhu.conf
server {
listen 80;
server_name www.timinglee.org;
location / {
proxy_pass http://172.25.254.10:80; #proxy_pass只能写一个。反向代理单台 web服务器
}
location /static {
proxy_pass http://172.25.254.20:8080; #指定 location 实现反向代理
}
}
----------------------动静分离----------------------
[root@Nginx ~]# vim /usr/local/nginx/conf.d/xiaozhuhzhu.conf
server {
listen 80;
server_name www.timinglee.org;
location ~ \.php$ {
proxy_pass http://172.25.254.10:80; #动态
}
location /static {
proxy_pass http://172.25.254.20:8080; #静态 #指定 location 实现反向代理
}
}
nginx -s reload
测试:浏览器访问www.timinglee.org/index.php
1.缓存功能
缓存功能默认关闭状态,需要先动配置才能启用.
proxy_cache zone_name | off; 默认off #指明调用的缓存,或关闭缓存机制;Context:http, server, location #zone_name 表示缓存的名称.需要由proxy_cache_path事先定义.
proxy_cache_key string; #缓存中用于“键”的内容,默认值:proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid [code ...] time; #定义对特定响应码的响应内容的缓存时长,定义在http{...}中示例: proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m.
#node2web访问并验证缓存文件
ab -n1000 -c100 http://www.timinglee.org/static/index.html
-----------------------------------------------------------------------------
[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf
....
#gzip on;
proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g; #配置在nginx.conf http配置段
....
[root@nginx conf.d]# vim /usr/local/nginx/conf.d/xiaozhuzhu.conf
server {
listen 80;
server_name www.timinglee.org;
location ~ \.php$ {
proxy_pass http://172.25.254.10:80;
}
location /static {
proxy_pass http://172.25.254.20:8080;
proxy_cache proxycache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 301 10m;
proxy_cache_valid any 1m; #必须指定哪些响应码的缓存
}
}
测试:
#/data/nginx/proxycache/ 目录会自动生成
[root@nginx conf.d]# ll /usr/local/nginx/proxy_cache/ -d
drwx------ 2 nginx root 6 Aug 19 00:08 /usr/local/nginx/proxy_cache/
[root@nginx conf.d]# tree /usr/local/nginx/proxy_cache/
/usr/local/nginx/proxy_cache/
0 directories, 0 files
#访问并验证缓存文件
[root@node2 ~]# ab -n1000 -c100 http://www.timinglee.org/static/index.html
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking www.timinglee.org (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: nginx/1.26.1
Server Hostname: www.timinglee.org
Server Port: 80
Document Path: /static/index.html
Document Length: 32 bytes
Concurrency Level: 100
Time taken for tests: 0.262 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 283000 bytes
HTML transferred: 32000 bytes
Requests per second: 3815.91 [#/sec] (mean)
Time per request: 26.206 [ms] (mean)
Time per request: 0.262 [ms] (mean, across all concurrent requests)
Transfer rate: 1054.59 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 10 2.3 10 20
Processing: 6 14 4.5 14 28
Waiting: 4 11 3.9 11 23
Total: 13 24 4.4 24 36
Percentage of the requests served within a certain time (ms)
50% 24
66% 25
75% 26
80% 27
90% 30
95% 33
98% 35
99% 35
100% 36 (longest request)
[root@nginx conf.d]# tree /usr/local/nginx/proxy_cache/
/usr/local/nginx/proxy_cache/
└── e
└── 50
└── 99
└── 319432ef3663735a9d3cb4e0c1d9950e
3 directories, 1 file
2.http 反向代理负载均衡
在上一个节中Nginx可以将客户端的请求转发至单台后端服务器但是无法转发至特定的一组的服务器,而 且不能对后端服务器提供相应的服务器状态监测,Nginx 可以基于ngx_http_upstream_module模块提 供服务器分组转发、权重分配、状态监测、调度算法等高级功能。
#后端多台 web服务器
172.25.254.100 #Nginx 代理服务器
172.25.254.10 #后端web node1,Apache部署
172.25.254.20 #后端web node2,Apache部署
#部署后端 Apache服务器,前面已完成基础配置。
----------------172.25.254.10 #后端web node1,Apache部署------------------
[root@node1 ~]# vim /etc/hosts
....
172.25.254.100 www.timinglee.org
[root@node1 ~]# mkdir -p /var/www/html/static
[root@node1 ~]# echo static - 172.25.254.10 > /var/www/html/static/index.html
----------------172.25.254.20 #后端web node2,Apache部署------------------
[root@node1 ~]# vim /etc/hosts
....
172.25.254.100 www.timinglee.org
--------------------------172.25.254.100=nginx部署-------------------------
#配置 nginx 反向代理
##注意: 本节实验过程中先关闭缓存
[root@nginx conf.d]# vim /usr/local/nginx/conf.d/xiaozhuzhu.conf
upstream webcluster {
#ip_hash; #算法需要一个一个打开,测试多curl即可
#hash $request_uri consistent; # node1建了一个文件curl的时候加上/static/可以得到文件写的内容,不加就是node2的内容。
#hash $cookie_lee; #测试:curl -b "lee=1" www.timinglee.org;里面lee可以=1;2;3;4....
server 172.25.254.10:80 weight=1 fail_timeout=15s max_fails=3; #在里面加入down关闭。
server 172.25.254.20:8080 weight=1 fail_timeout=15s max_fails=3;
server 172.25.254.100:80 backup; #测试算法时候需要注释掉
}
server {
listen 80;
server_name www.timinglee.org;
location / {
proxy_pass http://webcluster;
}
}
[root@nginx conf.d]# nginx -s reload
测试:curl www.timinglee.org #默认轮询
二.实现 Nginx 四层负载均衡
Nginx在1.9.0版本开始支持tcp模式的负载均衡,在1.9.13版本开始支持udp协议的负载,udp主要用于 DNS的域名解析,其配置方式和指令和http 代理类似,其基于ngx_stream_proxy_module模块实现tcp 负载,另外基于模块ngx_stream_upstream_module实现后端服务器分组转发、权重分配、状态监测、 调度算法等高级功能。 如果编译安装,需要指定 --with-stream 选项才能支持ngx_stream_proxy_module模块。
----------------172.25.254.10 #后端web node1,Apache部署------------------
[root@node1 ~]# dnf install bind -y
[root@node1 ~]# vim /etc/named.conf
....
// listen-on port 53 { 127.0.0.1; };
// listen-on-v6 port 53 { ::1; };
...
// allow-query { localhost; };
....
dnssec-validation no;
...
[root@node1 ~]# vim /etc/named.rfc1912.zones
....
zone "timinglee.org" IN {
type master;
file "timinglee.org.zone";
allow-update { none; };
};
....
[root@node1 ~]# cd /var/named/
[root@node1 named]# cp named.localhost timinglee.org.zone -p
[root@node1 named]# vim timinglee.org.zone
$TTL 1D
@ IN SOA ns.timinglee.org. roor.timinglee.org. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
NS ns.timinglee.org.
ns A 172.25.254.10
www A 172.25.254.10
[root@node1 named]# systemctl restart named
[root@node1 named]# dig www.timinglee.org @172.25.254.10
; <<>> DiG 9.16.23-RH <<>> www.timinglee.org @172.25.254.10
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9148
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 759e814dddf96a240100000066c22e333577155e2e826b88 (good)
;; QUESTION SECTION:
;www.timinglee.org. IN A
;; ANSWER SECTION:
www.timinglee.org. 86400 IN A 172.25.254.10
;; Query time: 1 msec
;; SERVER: 172.25.254.10#53(172.25.254.10)
;; WHEN: Mon Aug 19 01:24:03 CST 2024
;; MSG SIZE rcvd: 90
[root@node1 named]# scp -p /etc/named.{conf,rfc1912.zones} root@172.25.254.20:/etc/
The authenticity of host '172.25.254.20 (172.25.254.20)' can't be established.
ED25519 key fingerprint is SHA256:oBPEX0nYpWQYjJ8OGpbvh+YBXeynOKk0hh0gq7trBAA.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.25.254.20' (ED25519) to the list of known hosts.
root@172.25.254.20's password:
named.conf 100% 1727 1.3MB/s 00:00
named.rfc1912.zones 100% 1126 773.9KB/s 00:00
[root@node1 named]# scp -p /var/named/timinglee.org.zone root@172.25.254.20:/var/named/timinglee.org.zone
root@172.25.254.20's password:
timinglee.org.zone 100% 205 293.2KB/s 00:00
#下载mariadb
[root@node1 named]# dnf install mariadb-server -y
[root@node1 named]# vim /etc/my.cnf.d/mariadb-server.cnf
....
[mysqld]
server-id=10
[root@node1 named]# systemctl start mariadb
[root@node1 named]# mysql
MariaDB [(none)]> CREATE USER lee@'%' identified by 'lee';
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> GRANT ALL ON *.* to lee@'%';
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> quit
Bye
----------------172.25.254.20 #后端web node2,Apache部署------------------
[root@node2 ~]# dnf install bind -y
[root@node2 ~]# ll /etc/named.conf
-rw-r----- 1 root named 1727 Aug 19 01:18 /etc/named.conf
[root@node2 ~]# ll /etc/named.rfc1912.zones
-rw-r----- 1 root named 1126 Aug 19 01:19 /etc/named.rfc1912.zones
[root@node2 ~]# vim /var/named/timinglee.org.zone
$TTL 1D
@ IN SOA ns.timinglee.org. roor.timinglee.org. (
0 ; serial
1D ; refresh
1H ; retry
1W ; expire
3H ) ; minimum
NS ns.timinglee.org.
ns A 172.25.254.20
www A 172.25.254.20
[root@node2 ~]# systemctl restart named
[root@node2 ~]# dig www.timinglee.org @172.25.254.20
; <<>> DiG 9.16.23-RH <<>> www.timinglee.org @172.25.254.20
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 23248
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 777707da505dc8e70100000066c22f36c8fbd3ba8eb575b9 (good)
;; QUESTION SECTION:
;www.timinglee.org. IN A
;; Query time: 0 msec
;; SERVER: 172.25.254.20#53(172.25.254.20)
;; WHEN: Mon Aug 19 01:28:22 CST 2024
;; MSG SIZE rcvd: 74
[root@node2 ~]# cd /var/named/
[root@node2 named]# chgrp named timinglee.org.zone
[root@node2 named]# systemctl restart named
[root@node2 named]# dig www.timinglee.org @172.25.254.20
; <<>> DiG 9.16.23-RH <<>> www.timinglee.org @172.25.254.20
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 54931
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 9639f0ef8cf919680100000066c22f591044e7e21725497c (good)
;; QUESTION SECTION:
;www.timinglee.org. IN A
;; ANSWER SECTION:
www.timinglee.org. 86400 IN A 172.25.254.20
;; Query time: 0 msec
;; SERVER: 172.25.254.20#53(172.25.254.20)
;; WHEN: Mon Aug 19 01:28:57 CST 2024
;; MSG SIZE rcvd: 90
#下载mariadb
[root@node2 named]# dnf install mariadb-server -y
[root@node2 named]# vim /etc/my.cnf.d/mariadb-server.cnf
....
[mysqld]
server-id=20
....
[root@node2 named]# systemctl start mariadb
[root@node2 named]# mysql
MariaDB [(none)]> CREATE USER lee@'%' identified by 'lee';
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> GRANT ALL ON *.* to lee@'%';
Query OK, 0 rows affected (0.001 sec)
MariaDB [(none)]> quit
Bye
[root@node2 named]# netstat -antlupe | grep 3306
tcp6 0 0 :::3306 :::* LISTEN 27 37998 2778/mariadbd
--------------------------172.25.254.100=nginx部署-------------------------
#udp 负载均衡 DNS
[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf
...
events {
worker_connections 1024;
}
include "/usr/local/nginx/tcpconf.d/*.conf";
....
[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# mkdir -p /usr/local/nginx/tcpconf.d/
[root@nginx conf.d]# mv xiaozhuzhu.conf /usr/local/nginx/tcpconf.d/
[root@nginx conf.d]# cd /usr/local/nginx/tcpconf.d/
[root@nginx tcpconf.d]# ls
[root@nginx tcpconf.d]# vim /usr/local/nginx/tcpconf.d/xiaozhuzhu.conf
stream {
upstream dns {
server 172.25.254.10:53 weight=1 fail_timeout=15s max_fails=3;
server 172.25.254.20:53 weight=1 fail_timeout=15s max_fails=3;
}
server {
listen 53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
}
[root@nginx tcpconf.d]# nginx -s reload
测试:
[root@nginx tcpconf.d]# dig www.timinglee.org @172.25.254.100
; <<>> DiG 9.16.23-RH <<>> www.timinglee.org @172.25.254.100
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 39748
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: a173604345bcaec00100000066c23297ebfde8bae3db2cdd (good)
;; QUESTION SECTION:
;www.timinglee.org. IN A
;; ANSWER SECTION:
www.timinglee.org. 86400 IN A 172.25.254.10
;; Query time: 0 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Mon Aug 19 01:42:47 CST 2024
;; MSG SIZE rcvd: 90
[root@nginx tcpconf.d]# dig www.timinglee.org @172.25.254.100
; <<>> DiG 9.16.23-RH <<>> www.timinglee.org @172.25.254.100
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 7149
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
;; WARNING: recursion requested but not available
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
; COOKIE: 8980c11b0de9e9880100000066c2329af7b0b1ffff4fe6f5 (good)
;; QUESTION SECTION:
;www.timinglee.org. IN A
;; ANSWER SECTION:
www.timinglee.org. 86400 IN A 172.25.254.20
;; Query time: 15 msec
;; SERVER: 172.25.254.100#53(172.25.254.100)
;; WHEN: Mon Aug 19 01:42:50 CST 2024
;; MSG SIZE rcvd: 90
#负载均衡MySQL
[root@nginx tcpconf.d]# vim /usr/local/nginx/tcpconf.d/xiaozhuzhu.conf
stream {
upstream dns {
server 172.25.254.10:53 weight=1 fail_timeout=15s max_fails=3;
server 172.25.254.20:53 weight=1 fail_timeout=15s max_fails=3;
}
upstream mysql {
server 172.25.254.10:3306 weight=1 fail_timeout=15s max_fails=3;
server 172.25.254.20:3306 weight=1 fail_timeout=15s max_fails=3;
}
server {
listen 3306;
proxy_timeout 60s;
proxy_pass mysql;
}
server {
listen 53 udp reuseport;
proxy_timeout 20s;
proxy_pass dns;
}
}
[root@nginx tcpconf.d]# nginx -s reload
[root@nginx tcpconf.d]# netstat -antlupe | grep 3306
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 0 39891 979/nginx: master p
[root@nginx tcpconf.d]# dnf install mariadb -y
测试:
[root@nginx tcpconf.d]# mysql -ulee -plee -h172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
| 10 |
+-------------+
[root@nginx tcpconf.d]# mysql -ulee -plee -h172.25.254.100 -e "select @@server_id"
+-------------+
| @@server_id |
+-------------+
| 20 |
+-------------+
三.实现 FastCGI
CGI的由来: 最早的Web服务器只能简单地响应浏览器发来的HTTP请求,并将存储在服务器上的HTML文件返回给浏 览器,也就是静态html文件,但是后期随着网站功能增多网站开发也越来越复杂,以至于出现动态技 术,比如像php(1995年)、java(1995)、python(1991)语言开发的网站,但是nginx/apache服务器并不 能直接运行 php、java这样的文件,apache实现的方式是打补丁,nginx通过与第三方基于协议实现,即通过某种特定协议将客户端请求转发给第三方服务处理,第三方服务器会新建新的进程处理用户的请求,处理完成后返回数据给Nginx并回收进程,最后nginx在返回给客户端,那这个约定就是通用网 关接口(common gateway interface,简称CGI),CGI(协议) 是web服务器和外部应用程序之间的接口 标准,是cgi程序和web服务器之间传递信息的标准化接口。
1.为什么会有FastCGI?
CGI协议虽然解决了语言解析器和 Web Server 之间通讯的问题,但是它的效率很低,因为 Web Server 每收到一个请求都会创建一个CGI进程,PHP解析器都会解析php.ini文件,初始化环境,请求结束的时候 再关闭进程,对于每一个创建的CGI进程都会执行这些操作,所以效率很低,而FastCGI是用来提高CGI性 能的,FastCGI每次处理完请求之后不会关闭掉进程,而是保留这个进程,使这个进程可以处理多个请 求。这样的话每个请求都不用再重新创建一个进程了,大大提升了处理效率。
2.什么是PHP-FPM?
PHP-FPM(FastCGI Process Manager: FastCGI进程管理器)是一个实现了Fastcgi的程序,并且提供进程管理的功能。 进程包括master进程和worker进程。master进程只有一个,负责监听端口,接受来自web server 的请求 worker进程一般会有多个,每个进程中会嵌入一个PHP解析器,进行PHP代码的处理。
3.FastCGI配置指令
Nginx基于模块ngx_http_fastcgi_module实现通过fastcgi协议将指定的客户端请求转发至php-fpm处 理,其配置指令如下:
fastcgi_pass address:port; \#转发请求到后端服务器,address为后端的fastcgi server的地址,可用位置:location, if in
location
fastcgi_index name;
#fastcgi默认的主页资源,示例:fastcgi_index index.php; fastcgi_param parameter value [if_not_empty];
#设置传递给FastCGI服务器的参数值,可以是文本,变量或组合,可用于将Nginx的内置变量赋值给自定义 key
fastcgi_param REMOTE_ADDR $remote_addr; #客户端源IP
fastcgi_param REMOTE_PORT $remote_port; #客户端源端口
fastcgi_param SERVER_ADDR $server_addr; #请求的服务器IP地址
fastcgi_param SERVER_PORT $server_port; #请求的服务器端口
fastcgi_param SERVER_NAME $server_name; #请求的server name
Nginx默认配置示例:
location ~ \.php$ {
root /scripts;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; #默认脚本路径
#fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; #此文件默认系统已提供,存放的相对路径为 prefix/conf
}
4.Nginx与php-fpm在同一服务器
阿里云下载图片:
#编译安装更方便自定义参数或选项,所以推荐大家使用源码编译 官方网站:www.php.net
---------------#源码编译nginx添加模块---------------
[root@nginx ~]# cd /usr/local
[root@nginx local]#rm -rf /nginx/ #删掉配置文件,重新源码安装。
nginx源码安装需要的模块
memc;srcache;echo
www.php.net官方网站下载新的软件包。
[root@Nginx ~]# cd nginx-1.26.1/
[root@Nginx nginx-1.26.1]# ./configure --prefix=/usr/local/nginx \
--user=nginx \ # 指定nginx运行用户
--group=nginx \ # 指定nginx运行组
--with-http_ssl_module \ # 支持https://
--with-http_v2_module \ # 支持http版本2
--with-http_realip_module \ # 支持ip透传
--with-http_stub_status_module \ # 支持状态页面
--with-http_gzip_static_module \ # 支持压缩
--with-pcre \ # 支持正则
--with-stream \ # 支持tcp反向代理
--with-stream_ssl_module \ # 支持tcp的ssl加密
--with-stream_realip_module \ # 支持tcp的透传ip
--add-module=/root/memc-nginx-module-0.20 \
--add-module=/root/srcache-nginx-module-0.33 \
--add-module=/root/echo-nginx-module-0.63 \
[root@nginx ~]# make && make install
---------------------#源码编译php-----------------
[root@nginx ~]# tar zxf php-8.3.9.tar.gz
[root@nginx ~]# cd php-8.3.9
[root@nginx php-8.3.9]# ./configure \
--prefix=/usr/local/php \ #安装路径
--with-config-file-path=/usr/local/php/etc \ #指定配置路径
--enable-fpm \ #用cgi方式启动程序
--with-fpm-user=nginx \ #指定运行用户身份
--with-fpm-group=nginx \
--with-curl \ #打开curl浏览器支持
--with-iconv \ #启用iconv函数,转换字符编码
--with-mhash \ #mhash加密方式扩展库
--with-zlib \ #支持zlib库,用于压缩http压缩传输
--with-openssl \ #支持ssl加密
--enable-mysqlnd \ #mysql数据库
--with-mysqli \
--with-pdo-mysql \
--disable-debug \ #关闭debug功能
--enable-sockets \ #支持套接字访问
--enable-soap \ #支持soap扩展协议
--enable-xml \ #支持xml
--enable-ftp \ #支持ftp
--enable-gd \ #支持gd库
--enable-exif \ #支持图片元数据
--enable-mbstring \ #支持多字节字符串
--enable-bcmath \ #打开图片大小调整,用到zabbix监控的时候用到了这个模块
--with-fpm-systemd #支持systemctl 管理cgi
[root@nginx php-8.3.9]# dnf install -y bzip2 systemd-devel libxml2-devel sqlite-devel libpng-devel libcurl-devel oniguruma-devel -y
oniguruma-devel下载的版本不一致无法适配。在阿里云镜像站下载对应的版本。dnf list oniguruma-devel查看版本。
阿里云https://developer.aliyun.com/mirror下载https://mirrors.aliyun.com/rockylinux/9.4/devel/x86_64/kickstart/Packages/o/oniguruma-devel-6.9.6-1.el9.5.x86_64.rpm
[root@nginx php-8.3.9]# make && make install
如果报错出现没有指定目标就重新./configure一下。
------------------php相关配置优化---------------
[root@nginx etc]# cd /usr/local/php/etc
[root@nginx etc]# ls
php-fpm.conf php-fpm.conf.default php-fpm.d php.ini
[root@nginx etc]# cp -p php-fpm.conf.default php-fpm.conf
[root@nginx etc]# vim php-fpm.conf
...
[global]
; Pid file
; Note: the default prefix is /usr/local/php/var
; Default Value: none
pid = run/php-fpm.pid
...
[root@nginx etc]# cd php-fpm.d/
[root@nginx php-fpm.d]#
cp www.conf.default www.conf -p
[root@nginx php-fpm.d]#
cd /root/php-8.3.9/
[root@nginx php-8.3.9]# cp php.ini-production /usr/local/php/etc/php.ini
[root@nginx php-8.3.9]# vim /usr/local/php/etc/php.ini
[Date] ; Defines the default timezone used by the date functions ; https://php.net/date.timezone date.timezone = Asia/Shanghai #修改时区
---------------------#生成启动文件------------------
[root@Nginx ~]# cd /root/php-8.3.9/
[root@Nginx php-8.3.9]# cp sapi/fpm/php-fpm.service /lib/systemd/system/
[root@nginx php-8.3.9]# vim /lib/systemd/system/php-fpm.service
....
#Mounts the /usr, /boot, and /etc directories read-only for processes invoked by this unit.
#ProtectSystem=full #注释该内容
.....
[root@Nginx php-8.3.9]# systemctl start php-fpm.service
[root@Nginx php-8.3.9]# netstat -antlupe | grep php tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 0 820758 176202/php-fpm: mas
5.Nginx配置转发
[root@nginx ~]# mkdir /data/web/php -p
[root@nginx conf.d]# vim ~/.bash_profile
...
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin
source ~/.bash_profile
[root@nginx conf.d]# cat /data/web/php/index.php #php测试页面
<?php
phpinfo();
?>
[root@nginx conf.d]# vim /usr/local/nginx/conf/nginx.conf
....
#gzip on; #在http模块里面添加
include "/usr/local/nginx/conf.d/*.conf";
....
[root@nginx conf.d]# vim /usr/local/nginx/conf.d/vhost.conf
server {
listen 80;
server_name www.timinglee.org;
root /data/web/html;
index index.html;
location ~ \.php$ {
root /data/web/php;
fastcgi_pass 172.25.254.100:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
[root@nginx conf.d]# nginx -s reload
[root@nginx conf.d]# vim /usr/local/php/etc/php-fpm.d/www.conf
....
listen = 0.0.0.0:90000
....
[root@nginx conf.d]# systemctl restart php
测试:
访问www.timinglee.org/index.php
6. php的动态扩展模块(php的缓存模块)
软件下载:PECL :: Package :: memcache
[root@nginx ~]# tar zxf memcache-8.2.tgz
[root@nginx ~]# cd memcache-8.2/
[root@nginx memcache-8.2]# yum install autoconf
phpize
[root@nginx memcache-8.2]# ./configure && make && make install
...
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/
[root@Nginx memcache-8.2]# ls /usr/local/php/lib/php/extensions/no-debug-non-zts-20230831/
memcache.so opcache.so
[root@nginx memcache-8.2]# systemctl restart php-fpm.service
#复制测试文件到nginx发布目录中
[root@Nginx ~]# cd memcache-8.2/
[root@nginx memcache-8.2]# ls
[root@nginx memcache-8.2]# cp example.php memcache.php /data/web/php/
[root@Nginx ~]# vim /data/web/php/memcache.php
.....
define('ADMIN_USERNAME','admin'); // Admin Username
define('ADMIN_PASSWORD','lee'); // Admin Password
define('DATE_FORMAT','Y/m/d H:i:s');
define('GRAPH_SIZE',200);
define('MAX_ITEM_DUMP',50);
$MEMCACHE_SERVERS[] = 'localhost:11211'; // add more as an array
#$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array
#配置php加载memcache模块
[root@Nginx ~]# vim /usr/local/php/etc/php.ini
....
;extension=zip
extension=memcache
;zend_extension=opcache
....
[root@Nginx ~]# systemctl reload php-fpm.service
[root@Nginx no-debug-non-zts-20230831]# php -m | grep mem
memcache
#部署memcached
[root@Nginx ~]# yum install memcached -y
[root@Nginx ~]# systemctl enable --now memcached.service
[root@nginx ~]# netstat -antlupe | grep memcache
tcp 0 0 127.0.0.1:11211 0.0.0.0:* LISTEN 977 158415 145205/memcached
tcp6 0 0 ::1:11211 :::* LISTEN 977 158416 145205/memcached
[root@Nginx ~]# cat /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS="-l 127.0.0.1,::1"
[root@Nginx ~]# systemctl restart memcached.service
测试:
访问 http://www.timinglee.org/example.php 不断刷新
访问 http://www.timinglee.org/memcache.php 查看命中效果.
[root@nginx ~]# ab -n1000 -c100 http://www.timinglee.org/index.php
bash: ab: command not found...
Install package 'httpd-tools' to provide command 'ab'? [N/y] y
* Waiting in queue...
* Loading list of packages....
The following packages have to be installed:
apr-1.7.0-11.el9.x86_64 Apache Portable Runtime library
apr-util-1.6.1-20.el9.x86_64 Apache Portable Runtime Utility library
apr-util-bdb-1.6.1-20.el9.x86_64 APR utility library Berkeley DB driver
apr-util-openssl-1.6.1-20.el9.x86_64 APR utility library OpenSSL crypto support
httpd-tools-2.4.51-7.el9_0.x86_64 Tools for use with the Apache HTTP Server
Proceed with changes? [N/y] y
* Waiting in queue...
* Waiting for authentication...
* Waiting in queue...
* Loading list of packages....
* Requesting data...
* Testing changes...
* Installing packages... Failed to install packages: PackageKit daemon disappeared
访问图片:
7.php高速缓存
[root@nginx ~]# vim /usr/local/nginx/conf.d/vhost.conf
upstream memcache {
server 127.0.0.1:11211;
keepalive 512;
}
server {
listen 80;
server_name www.timinglee.org;
root /data/web/html;
index index.html;
location /memc {
internal;
memc_connect_timeout 100ms;
memc_send_timeout 100ms;
memc_read_timeout 100ms;
set $memc_key $query_string; #使用内置变量$query_string来作为key
set $memc_exptime 300; #缓存失效时间300秒
memc_pass memcache;
}
location ~ \.php$ {
root /data/web/php;
set $key $uri$args; #设定key的值
srcache_fetch GET /memc $key; #检测mem中是否有要访问的php
srcache_store PUT /memc $key; #缓存为加载的php数据
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
[root@nginx ~]# 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
[root@nginx ~]# nginx -s reload
测试:
[root@nginx ~]# ab -n1000 -c100 http://www.timinglee.org/index.php
This is ApacheBench, Version 2.3 <$Revision: 1879490 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking www.timinglee.org (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software: nginx/1.26.1
Server Hostname: www.timinglee.org
Server Port: 80
Document Path: /index.php
Document Length: 74914 bytes
Concurrency Level: 100
Time taken for tests: 0.285 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 75098993 bytes
HTML transferred: 74914000 bytes
Requests per second: 3511.10 [#/sec] (mean)
Time per request: 28.481 [ms] (mean)
Time per request: 0.285 [ms] (mean, across all concurrent requests)
Transfer rate: 257500.10 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 1 2.1 0 13
Processing: 1 26 23.2 18 133
Waiting: 1 26 22.8 18 123
Total: 1 26 23.4 20 133
Percentage of the requests served within a certain time (ms)
50% 20
66% 30
75% 36
80% 42
90% 56
95% 78
98% 99
99% 104
100% 133 (longest request)
四.nginx 二次开发版本:编译安装 openresty
Nginx 是俄罗斯人发明的, Lua 是巴西几个教授发明的,中国人章亦春把 LuaJIT VM 嵌入到 Nginx 中, 实现了 OpenResty 这个高性能服务端解决方案 OpenResty® 是一个基于 Nginx 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方 模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服 务和动态网关。 OpenResty® 通过汇聚各种设计精良的 Nginx 模块(主要由 OpenResty 团队自主开发),从而将Nginx 有效地变成一个强大的通用 Web 应用平台。这样,Web 开发人员和系统工程师可以使用 Lua 脚本语言 调动 Nginx 支持的各种 C 以及 Lua 模块,快速构造出足以胜任 10K 乃至 1000K 以上单机并发连接的高 性能 Web 应用系统。 OpenResty 由于有功能强大且方便的的API,可扩展性更强,如果需要实现定制功能,OpenResty是个不错的选择。
[root@nginx ~]# systemctl stop nginx
[root@nginx ~]# netstat -antlulpe | grep nginx
[root@nginx ~]# killall -9 nginx #如果关不了,就杀掉。
[root@nginx ~]# ps -ef |grep nginx
avahi 878 1 0 Aug19 ? 00:00:00 avahi-daemon: running [nginx-2.local]
nginx 144832 144812 0 Aug19 ? 00:00:00 php-fpm: pool www
nginx 144833 144812 0 Aug19 ? 00:00:00 php-fpm: pool www
root 145516 145480 0 00:36 pts/0 00:00:00 grep --color=auto nginx
[root@nginx ~]# dnf -y install gcc pcre-devel openssl-devel perl
[root@nginx ~]# tar zxf openresty-1.25.3.1
[root@nginx ~]# cd openresty-1.25.3.1/
[root@nginx openresty-1.25.3.1]# ./configure \
--prefix=/usr/local/openresty \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_sub_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-http_ssl_module \
--without-http_memcached_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
....
cd ../..
Type the following commands to build and install:
gmake
gmake install
[root@nginx openresty-1.25.3.1]# gmake -j2 && gmake install
....
gmake[2]: Leaving directory '/root/openresty-1.25.3.1/build/nginx-1.25.3'
gmake[1]: Leaving directory '/root/openresty-1.25.3.1/build/nginx-1.25.3'
mkdir -p /usr/local/openresty/site/lualib /usr/local/openresty/site/pod /usr/local/openresty/site/manifest
ln -sf /usr/local/openresty/nginx/sbin/nginx /usr/local/openresty/bin/openresty
[root@nginx openresty-1.25.3.1]# cd /usr/local/openresty/
[root@nginx openresty]# ls
bin COPYRIGHT luajit lualib nginx pod resty.index site
[root@nginx openresty]# cd bin/
[root@nginx bin]# ll
total 168
-rwxr-xr-x 1 root root 19185 Aug 20 00:52 md2pod.pl
-rwxr-xr-x 1 root root 15994 Aug 20 00:52 nginx-xml2pod
lrwxrwxrwx 1 root root 37 Aug 20 00:52 openresty -> /usr/local/openresty/nginx/sbin/nginx
-rwxr-xr-x 1 root root 63650 Aug 20 00:52 opm
-rwxr-xr-x 1 root root 36881 Aug 20 00:52 resty
-rwxr-xr-x 1 root root 14957 Aug 20 00:52 restydoc
-rwxr-xr-x 1 root root 8873 Aug 20 00:52 restydoc-index
[root@nginx bin]# vim ~/.bash_
.bash_history .bash_logout .bash_profile
[root@nginx bin]# vim ~/.bash_profile
export PATH=$PATH:/usr/local/nginx/sbin:/usr/local/php/bin:/usr/local/php/sbin:/usr/local/openresty/bin
[root@nginx bin]# source ~/.bash_profile
[root@nginx bin]# openresty
[root@nginx bin]# netstat -antlulpe | grep 80
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 0 180114 159771/nginx: maste
tcp6 0 0 ::1:631 :::* LISTEN 0 22780 910/cupsd
测试:
浏览器访问172.25.254.100有openresty专属界面。
访问图片: