NGINX

Posted 终究是想不起来

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NGINX相关的知识,希望对你有一定的参考价值。

1、nginx负载均衡中常见的算法及原理

1.1 round robin(默认)

轮询方式,依次将请求分配到各个后台服务器中,默认的负载均衡方式。 

适用于后台机器性能一致的情况。 

挂掉的机器可以自动从服务列表中剔除。

1.2 weight

根据权重来分发请求到不同的机器中,指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。  

例如:

upstream bakend     
server 192.168.0.14 weight=10;
server 192.168.0.15 weight=10;
1.3 IP_hash

根据请求者ip的hash值将请求发送到后台服务器中,可以保证来自同一ip的请求被打到固定的机器上,可以解决session问题。

例如:

upstream bakend     
ip_hash;
server 192.168.0.14:88;
server 192.168.0.15:80;
1.​4 fair

fair方法比起之前的几个算法要比较灵活一点是按照后端服务器的响应时间来进行分配,响应时间短的优先分配。

例如:

upstream test 
server 172.25.40.1:80;
servse 172.25.40.2:8080;
fair;
1.​5 url_hash

这种方法是按照URL的hash结果来分配请求,使URL定向到同一个服务器,在upstream中加入hash语句后,server语句不能写入weight等其他参数,这种算法一般在后端缓存的时候比较适合。

例如:

pstream test 
server squidIP1:3128;
servse squidIP2:3128;
hash $request_uri;
hash_method crc32;
T​ips

在Nginx upstream模块中,可以设定每台后端服务器在负载均衡调度中的状态,常用的状态有:

1、down,表示当前的server暂时不参与负载均衡

2、backup,预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的访问压力最低

3、max_fails,允许请求失败的次数,默认为1,当超过最大次数时,返回proxy_next_upstream模块定义的错误。

4、fail_timeout,请求失败超时时间,在经历了max_fails次失败后,暂停服务的时间。max_fails和fail_timeout可以一起使用。

Nignx负载均衡功能是通过upstream模块实现的,是基于内容和应用的7层交换负载均衡。Nginx负载均衡默认对后端服务器有健康检测能力,但是检测能力较弱,仅限于端口检测,在后端服务器比较少的情况下(10台及以下)负载均衡能力表现突出。

2、使用rewrite规则实现将所有到a域名的访问rewrite到b域名

[root@centos8 ~]#vim /apps/nginx/conf/conf.d/mobile.conf
server
listen 80;
server_name www.a.com;
location /
root "/data/nginx/html/mobile";
index index.html;
rewrite / http://www.b.com redirect;



server
listen 80;
server_name www.b.com;
location /
root "/nginx/html/";
index index.html;



[root@centos8 ~]#echo 111 > /data/nginx/html/mobile/index.html
[root@centos8 ~]#echo 222 > /nginx/html/index.html
[root@centos8 ~]#vim /etc/hosts
10.0.0.150 www.a.com www.b.com

[root@centos8 ~]#curl www.a.com
<html>
<head><title>302 Found</title></head>
<body>
<center><h1>302 Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

[root@centos8 ~]#curl -L www.a.com
222


3、实现反向代理客户端IP透传  

一级代理实现客户端IP透传

NGINX_nginx

[root@centos8 ~]# cat /apps/nginx/conf/conf.d/pc.conf
server
listen 80;
server_name www.magedu.org;
location /
index index.html index.php;
root /data/nginx/html/pc;
proxy_pass http://10.0.0.18;
#proxy_set_header X-Real-IP $remote_addr; #只添加客户端IP到请求报文头部,转发至后端服务器
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加客户端IP和反向代理服务器IP到请求报文头部


#重启nginx
[root@centos8 ~]#systemctl restart nginx

#后端Apache配置:
[root@centos8 ~]#vim /etc/httpd/conf/httpd.conf
LogFormat "%X-Forwarded-Fori %h %l %u %t \\"%r\\" %>s %b \\"%Refereri\\" \\"%User-Agenti\\"" combined
#重启apache访问web界面并验证apache日志
[root@centos8 ~]#cat /var/log/httpd/access_log
10.0.0.1 10.0.0.8 - - [04/Apr/2022:00:40:46 +0800] "GET / HTTP/1.0" 200 19 "-"
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.119 Safari/537.36"

#Nginx配置:
[root@centos8 conf.d]# cat /apps/nginx/conf/nginx.conf
"$http_x_forwarded_for" #默认日志格式就有此配置

#重启nginx访问web界面并验证日志格式:
10.0.0.8 - - [04/Apr/2022:16:40:51 +0800] "GET / HTTP/1.0" 200 24 "-"
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.119 Safari/537.36" "10.0.0.1"

4、利用LNMP实现wordpress站点搭建

#环境准备:
nginx+php+wordpress 10.0.0.152
mysql+redis 10.0.0.162
1. 部署数据库
2. 部署PHP
3. 部署NGINX
4. 部署Wordpress
5. PHP扩展session模块支持Redis

#在10.0.0.162编写脚本实现mysqk数据库一键安装
[root@localhost ~]# cat install_mysql.sh
#!/bin/bash
#
#**********************************************************************************************
#Author: tanliang
. /etc/init.d/functions
SRC_DIR=`pwd`
MYSQL=mysql-8.0.19-linux-glibc2.12-x86_64.tar.xz
COLOR=echo -e \\E[01;31m
END=\\E[0m
MYSQL_ROOT_PASSWORD=123456


check ()
if [ $UID -ne 0 ]; then
action "当前用户不是root,安装失败" false
exit 1
fi

cd $SRC_DIR
if [ ! -e $MYSQL ];then
$COLOR"缺少$MYSQL文件"$END
$COLOR"请将相关软件放在$SRC_DIR目录下"$END
exit
elif [ -e /usr/local/mysql ];then
action "数据库已存在,安装失败" false
exit
else
return
fi



install_mysql()
$COLOR"开始安装MySQL数据库..."$END
yum -y -q install libaio numactl-libs libaio &> /dev/null
cd $SRC_DIR
tar xf $MYSQL -C /usr/local/
MYSQL_DIR=`echo $MYSQL| sed -nr s/^(.*[0-9]).*/\\1/p`
ln -s /usr/local/$MYSQL_DIR /usr/local/mysql
chown -R root.root /usr/local/mysql/
id mysql &> /dev/null || useradd -s /sbin/nologin -r mysql ; action "创建mysql用户";

echo PATH=/usr/local/mysql/bin/:$PATH > /etc/profile.d/mysql.sh
. /etc/profile.d/mysql.sh
ln -s /usr/local/mysql/bin/* /usr/bin/
[ -d /data/mysql ] || mkdir -p /data/mysql
cat > /etc/my.cnf <<EOF
[mysqld]
server-id=`hostname -I|cut -d. -f4`
log-bin
datadir=/data/mysql
socket=/data/mysql/mysql.sock
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock
EOF


mysqld --initialize --user=mysql --datadir=/data/mysql
cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
chkconfig --add mysqld
chkconfig mysqld on
service mysqld start
[ $? -ne 0 ] && $COLOR"数据库启动失败,退出!"$END;exit;
MYSQL_OLDPASSWORD=`awk /A temporary password/print $NF /data/mysql/mysql.log`
mysqladmin -uroot -p$MYSQL_OLDPASSWORD password $MYSQL_ROOT_PASSWORD&>/dev/null
action "数据库安装完成"


check
install_mysql

#执行脚本进行数据库安装
[root@localhost ~]# bash install_mysql.sh
开始安装MySQL数据库...
创建mysql用户 [ OK ]
Starting MySQL. [ OK ]
数据库安装完成 [ OK ]

#创建数据库和用户并授权
[root@localhost ~]# mysql -uroot -p123456

mysql> create database wordpress;
Query OK, 1 row affected (0.01 sec)

mysql> create user wordpress@10.0.0.% identified by 123456;
Query OK, 0 rows affected (0.00 sec)

mysql> grant all on wordpress.* to wordpress@10.0.0.%;
Query OK, 0 rows affected (0.00 sec)

#在10.0.0.152wordpress上连接数据库测试
#安装mysql客户端
[root@localhost ~]#yum install -y mysql
[root@localhost ~]# mysql -uwordpress -h10.0.0.162 -p123456
ERROR 2059 (HY000): Authentication plugin caching_sha2_password cannot be loaded: /usr/lib64/mysql/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

连接MySQL数据库时会出现Authentication plugin caching_sha2_password cannot be loaded的错误。
出现这个原因是mysql8 之前的版本中加密规则是mysql_native_password,而在mysql8之后,加密规则是caching_sha2_password, 解决问题方法是把mysql用户登录密码加密规则还原成mysql_native_password.

#返回10.0.0.162,修改密码规则
mysql> ALTER USER wordpress@10.0.0.% IDENTIFIED BY password PASSWORD EXPIRE NEVER;
Query OK, 0 rows affected (0.00 sec)

mysql> ALTER USER wordpress@10.0.0.% IDENTIFIED WITH mysql_native_password BY 123456;
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.01 sec)

#返回10.0.0.152连接数据库
[root@localhost ~]# mysql -uwordpress -h10.0.0.162 -p123456
Welcome to the MariaDB monitor. Commands end with ; or \\g.
Your MySQL connection id is 31
Server version: 8.0.19 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type help; or \\h for help. Type \\c to clear the current input statement.

MySQL [(none)]>


#10.0.0.152上编写脚本安装php-fpm
[root@localhost]#vim install_php.sh
yum -y install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel &>/dev/null
cd /usr/local/src
wget https://www.php.net/distributions/php-7.4.11.tar.xz &>/dev/null
tar -xf php-7.4.11.tar.xz
cd php-7.4.11
./configure --prefix=/apps/php74 --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-openssl --with-zlib --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --enable-mbstring --enable-xml --enable-sockets --enable-fpm --enable-maintainer-zts --disable-fileinfo &>/dev/null
make&&make install &>/dev/null
cp /usr/local/src/php-7.4.11/php.ini-production /etc/php.ini
cp /apps/php74/etc/php-fpm.conf.default /apps/php74/etc/php-fpm.conf
cp /apps/php74/etc/php-fpm.d/www.conf.default /apps/php74/etc/php-fpm.d/www.conf
cat >/apps/php74/etc/php-fpm.d/www.conf <<eof
[www]
user = www
group = www
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
pm.status_path = /pm_status
ping.path = /ping
access.log = log/$pool.access.log
slowlog = log/$pool.log.slow
eof
useradd -r -s /sbin/nologin www
mkdir /apps/php74/log
/apps/php74/sbin/php-fpm -t &>/dev/null
[ $? -ne 0 ] && echo "php-fpm启动失败,退出!";exit;
cp /usr/local/src/php-7.4.11/sapi/fpm/php-fpm.service /usr/lib/systemd/system/
systemctl daemon-reload
systemctl enable --now php-fpm &>/dev/null
[ $? -eq 0 ] && echo "php-fpm is enabled";
pstree -p |grep php &>/dev/null
[ $? -eq 0 ] && echo "php-fpm sever is running";

[root@localhost ~]# bash install_php.sh
php-fpm is enabled
php-fpm sever is running



#编写nginx安装脚本进行安装
[root@localhost ~]# cat install_nginx.sh
#!/bin/bash
yum -y install gcc pcre-devel openssl-devel zlib-devel &>/dev/null
[ $? -eq 0 ] && echo "gcc pcre-devel openssl-devel zlib-devel is install";

cd /usr/local/src/
wget http://nginx.org/download/nginx-1.18.0.tar.gz &>/dev/null
tar xf nginx-1.18.0.tar.gz
cd nginx-1.18.0/
./configure --prefix=/apps/nginx --user=www --group=www --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module &>/dev/null
[ $? -eq 0 ] && echo "编译完成";
make &>/dev/null
make install &>/dev/null
[ $? -eq 0 ] && echo "nginx编译安装完成";
cat >/usr/lib/systemd/system/nginx.service <<eof
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/apps/nginx/run/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP \\$MAINPID
ExecStop=/bin/kill -s TERM \\$MAINPID
[Install]
WantedBy=multi-user.target
eof

mkdir /apps/nginx/run/ -p
mv /apps/nginx/conf/nginx.conf,.bak
cat >/apps/nginx/conf/nginx.conf <<eof
worker_processes 1;
pid /apps/nginx/run/nginx.pid;
events
worker_connections 1024;
http
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server
listen 80;
server_name www.magedu.org;
location /
root /data/nginx/wordpress;
index index.php index.html index.htm;

error_page 500 502 503 504 /50x.html;
location = /50x.html
root html;

location ~ \\.php$
root /data/nginx/wordpress;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME \\$document_root\\$fastcgi_script_name;
include fastcgi_params;

location ~ ^/(ping|pm_status)$
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param PATH_TRANSLATED \\$document_root\\$fastcgi_script_name;



eof
ln -s /apps/nginx/sbin/nginx /usr/sbin/nginx
/apps/nginx/sbin/nginx -t &>/dev/null
[ $? -eq 0 ] && echo "configuration file /apps/nginx/conf/nginx.conf test is successful!";
systemctl daemon-reload
systemctl enable --now nginx &>/dev/null
[ $? -eq 0 ] && echo "nginx启动成功!";
mkdir -p /data/nginx/wordpress
cat> /data/nginx/wordpress/test.php <<eof
<?php
phpinfo();
?>
eof

[root@localhost ~]# bash install_nginx.sh
nginx编译安装完成
configuration file /apps/nginx/conf/nginx.conf test is successful!
nginx启动成功!

#测试访问php测试页正常
[root@localhost ~]#curl localhost/test.php


#在10.0.0.152上部署wordpress
[root@www ~]# tar xf wordpress-5.4.1-zh_CN.tar.gz
[root@www ~]# cp -r wordpress/* /data/nginx/wordpress
[root@www ~]# chown -R www.www /data/nginx/wordpress/
#在windows访问http://www.magedu.org
[root@www ~]# vim /data/nginx/wordpress/wp-config.php
#在wordpress写文章并发布
#验证发表的文章网页访问http://www.magedu.org
[root@www ~]# tree /data/nginx/wordpress/wp-content/uploads/
/data/nginx/wordpress/wp-content/uploads/
└── 2022
└── 03
└── timg.jpg

2 directories, 1 file
You have mail in /var/spool/mail/root
#配置允许上传大文件
#注意:默认只支持1M以下文件上传,要利用php程序上传大图片,还需要修改下面三项配置,最大上传由三项值的最小值决定
#nginx上传文件大小限制
[root@centos7 ~]#vim /apps/nginx/conf/nginx.conf
server
      client_max_body_size 10m; #默认值为1M
.....
#php上传文件大小限制
[root@centos7 ~]#vim /etc/php.ini
post_max_size = 30M   #默认值为8M
upload_max_filesize = 20M  #默认值为2M
[root@centos7 ~]#systemctl restart nginx php-fpm


#安全加固
[root@www ~]# vim /apps/nginx/conf/nginx.conf
worker_processes 1;
pid /apps/nginx/run/nginx.pid;
events
worker_connections 1024;
http
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server
listen 80;
server_name www.magedu.org;
client_max_body_size 10m;
server_tokens off;#添加此行,隐藏nginx版本
location /
root /data/nginx/wordpress;
index index.php index.html index.htm;

error_page 500 502 503 504 /50x.html;
location = /50x.html
root html;

location ~ \\.php$
root /data/nginx/wordpress;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_hide_header X-Powered-By;#添加此行

location ~ ^/(ping|pm_status)$
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_script_name;



[root@www ~]# systemctl reload nginx

#开启opcache加速
[root@www ~]# vim /etc/php.ini
[opcache]
; Determines if Zend OPCache is enabled
zend_extension=opcache.so                                                      
opcache.enable=1
[root@www ~]# #systemctl restart php-fpm

#PHP 扩展session模块支持redis
PECL是 PHP 扩展的存储库,提供用于下载和开发 PHP 扩展的所有已知扩展和托管功能的目录
官方链接: http://pecl.php.net/package-stats.php
github: https://github.com/phpredis/phpredis
github安装文档: https://github.com/phpredis/phpredis/blob/develop/INSTALL.markdown
开始在 PHP 中使用 Redis 前, 需要确保已经安装了 redis 服务及 PHP redis 驱动,
PHP redis 驱动下载地址为:https://github.com/phpredis/phpredis/releases

#在10.0.0.152上安装PHP redis 驱动
[root@www ~]# cd /usr/local/src/
[root@www ~]#tar xf phpredis-5.3.3.tar.gz
[root@www src]# cd phpredis-5.3.3/
[root@www phpredis-5.3.3]#/apps/php74/bin/phpize
[root@www phpredis-5.3.3]# ./configure --with-php-config=/apps/php74/bin/php-config
[root@www phpredis-5.3.3]#make -j 2 && make install
[root@www phpredis-5.3.3]#
[root@www phpredis-5.3.3]# ll /apps/php74/lib/php/extensions/no-debug-zts-20190902/
total 9588
-rwxr-xr-x 1 root root 4647668 Mar 29 15:53 opcache.a
-rwxr-xr-x 1 root root 2509416 Mar 29 15:53 opcache.so
-rwxr-xr-x 1 root root 2658240 M 30 02:31 redis.so

#编辑php配置文件支持redis

[root@www phpredis-5.3.3]# vim /etc/php.ini
extension=redis.so    #文件最后一行添加此行,路径可省略
[root@www phpredis-5.3.3]#
[root@www phpredis-5.3.3]# systemctl restart php-fpm
#windows网页访问http://www.magedu.org/test.php验证redis模块价值成功

#在10.0.0.162上安装和配置 redis 服务
[root@localhost ~]# yum install -y redis
[root@localhost ~]# vim /etc/redis.conf
bind 0.0.0.0
requirepass 123456
[root@localhost ~]#systemctl enable --now redis
[root@localhost ~]#ss -tnlp

#在10.0.0.152主机配置php的session保存在redis服务
[root@localhost ~]#vim /etc/php.ini
[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
session.save_handler = redis
session.save_path = "tcp://10.0.0.162:6379?auth=123456"  
[root@localhost ~]#systemctl restart php-fpm
#验证
[root@www phpredis-5.3.3]# curl localhost/test.php|grep -i session.save_handler
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0<tr><td class="e">session.save_handler</td><td class="v">redis</td><td class="v">redis</td></tr>
100 71733 0 71733 0 0 9305k 0 --:--:-- --:--:-- --:--:-- 9.7M


#10.0.0.152准备 php实现 session 的测试页面
[root@www phpredis-5.3.3]# cat /data/nginx/wordpress/session.php
<?php
session_start();
//redis用session_id作为key 并且是以string的形式存储
$redisKey = PHPREDIS_SESSION: . session_id();
// SESSION 赋值测试
$_SESSION[message] = "Hello, Im in redis";
$_SESSION[arr] = [1, 2, 3, 4, 5, 6];
echo $_SESSION["message"] , "<br/>";
echo "Redis key =   " . $redisKey . "<br/>";
echo "以下是从Redis获取的数据", "<br/>";
// 取数据
$redis = new Redis();
$redis->connect(10.0.0.162, 6379);
$redis->auth(123456);
echo $redis->get($redisKey);
?>

#网页访问http://www.magedu.org/session.php
[root@localhost ~]# redis-cli -h 10.0.0.162 -a 123456
10.0.0.162:6379> keys *
(empty list or set)
10.0.0.162:6379> keys *
1) "PHPREDIS_SESSION:mgmr764old1jghlgqf6q5om8hj"
10.0.0.162:6379> get PHPREDIS_SESSION:mgmr764old1jghlgqf6q5om8hj
"message|s:19:\\"Hello, Im in redis\\";arr|a:6:i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;"
10.0.0.162:6379>

以上是关于NGINX的主要内容,如果未能解决你的问题,请参考以下文章

Nginx负载均衡

NGINX

nginx负载均衡配置策略

nginx upstream的五种分配方式

Nginx中的upstream 分配方法

Nginx——nginx作为静态资源web服务(配置语法)