linux_9

1、对常用I/O模型进行比较说明

一、IO模型的四个特性

  1. 关注的是消息通信机制,即调用者在等待一件事情的处理结果时,被调用者是否提供完成状态的通知。

  • 同步:synchronous,被调用者并不提供事件的处理结果相关的通知消息,需要调用者主动询问事情是否处理完成

  • 异步:asynchronous,被调用者通过状态、通知或回调机制主动通知调用者被调用者的运行状态

      2、关注调用者在等待结果返回之前所处的状态

  • 阻塞:blocking,指IO操作需要彻底完成后才返回到用户空间,调用结果返回之前,调用者被挂起,干不了别的事情。

  • 非阻塞:nonblocking,指IO操作被调用后立即返回给用户一个状态值,而无需等到IO操作彻底完- 成,在最终的调用结果返回之前,调用者不会被挂起,可以去做别的事情。

二、网络 I/O 模型

阻塞型 I/O 模型(blocking IO)

阻塞IO模型是最简单的I/O模型,用户线程在内核进行IO操作时被阻塞。用户线程通过系统调用read发起I/O读操作,由用户空间转到内核空间。内核等到数据包到达后,然后将接收的数据拷贝到用户空间,完成read操作用户需要等待read将数据读取到buffer后,才继续处理接收的数据。整个I/O请求的过程中,用户线程是被阻塞的,这导致用户在发起IO请求时,不能做任何事情,对CPU的资源利用率不够

优点:程序简单,在阻塞等待数据期间进程/线程挂起,基本不会占用 CPU 资源

缺点:每个连接需要独立的进程/线程单独处理,当并发请求量大时为了维护程序,内存、线程切换开销较大,apache 的preforck使用的是这种模式。

非阻塞型 I/O 模型 (nonblocking IO)

用户线程发起IO请求时立即返回。但并未读取到任何数据,用户线程需要不断地发起IO请求,直到数据到达后,才真正读取到数据,继续执行。即 “轮询”机制存在两个问题:如果有大量文件描述符都要等,那么就得一个一个的read。这会带来大量的Context Switch(read是系统调用,每调用一次就得在用户态和核心态切换一次)。轮询的时间不好把握。这里是要猜多久之后数据才能到。等待时间设的太长,程序响应延迟就过大;设的太短,就会造成过于频繁的重试,干耗CPU而已,是比较浪费CPU的方式,一般很少直接使用这种模型,而是在其他IO模型中使用非阻塞IO这一特性。

多路复用 I/O 型(I/O multiplexing)

多路复用IO指一个线程可以同时(实际是交替实现,即并发完成)监控和处理多个文件描述符对应各自的IO,即复用同一个线程一个线程之所以能实现同时处理多个IO,是因为这个线程调用了内核中的SELECT,POLL或EPOLL等系统调用,从而实现多路复用IO

优点:可以基于一个阻塞对象,同时在多个描述符上等待就绪,而不是使用多个线程(每个文件描述符一个线程),这样可以大大节省系统资源

缺点:当连接数较少时效率相比多线程+阻塞 I/O 模型效率较低,可能延迟更大,因为单个连接处理需要 2 次系统调用,占用时间会有增加

信号驱动式 I/O 模型 (signal-driven IO)

信号驱动I/O的意思就是进程现在不用傻等着,也不用去轮询。而是让内核在数据就绪时,发送信号通知进程。调用的步骤是:通过系统调用sigaction ,并注册一个信号处理的回调函数,该调用会立即返回,然后主程序可以继续向下执行,当有I/O操作准备就绪,即内核数据就绪时,内核会为该进程产生一个SIGIO信号,并回调注册的信号回调函数,这样就可以在信号回调函数中系统调用recvfrom 获取数据,将用户进程所需要的数据从内核空间拷贝到用户空间。此模型的优势在于等待数据报到达期间进程不被阻塞。用户主程序可以继续执行,只要等待来自信号处理函数的通知。在信号驱动式 I/O 模型中,应用程序使用套接口进行信号驱动 I/O,并安装一个信号处理函数,进程继续运行并不阻塞当数据准备好时,进程会收到一个 SIGIO 信号,可以在信号处理函数中调用 I/O 操作函数处理数据。

优点:线程并没有在等待数据时被阻塞,内核直接返回调用接收信号,不影响进程继续处理其他请求因此可以提高资源的利用率

缺点:信号 I/O 在大量 IO 操作时可能会因为信号队列溢出导致没法通知

异步 I/O 模型 (asynchronous IO)

异步I/O 与 信号驱动I/O最大区别在于,信号驱动是内核通知用户进程何时开始一个I/O操作,而异步I/O是由内核通知用户进程I/O操作何时完成,两者有本质区别,相当于不用去饭店场吃饭,直接点个外卖,把等待上菜的时间也给省了。相对于同步I/O,异步I/O不是顺序执行。用户进程进行aio_read系统调用之后,无论内核数据是否准备好,都会直接返回给用户进程,然后用户态进程可以去做别的事情。等到socket数据准备好了,内核直接复制数据给进程,然后从内核向进程发送通知。IO两个阶段,进程都是非阻塞的。信号驱动IO当内核通知触发信号处理程序时,信号处理程序还需要阻塞在从内核空间缓冲区拷贝数据到用户空间缓冲区这个阶段,而异步IO直接是在第二个阶段完成后,内核直接通知用户线程可以进行后续操作了

优点:异步 I/O 能够充分利用 DMA 特性,让 I/O 操作与计算重叠

缺点:要实现真正的异步 I/O,操作系统需要做大量的工作。目前 Windows 下通过 IOCP 实现了真正的

三、五种IO对比

这五种 I/O 模型中,越往后,阻塞越少,理论上效率也是最优前四种属于同步 I/O,因为其中真正的 I/O操作(recvfrom)将阻塞进程/线程,只有异步 I/O 模型才与 POSIX 定义的异步 I/O 相匹配。

 

 

 

2、nginx中的模块分类及常见核心模块有哪些

Nginx核心模块

  • user

  • pid

  • include

  • worker_processes

  • worker_cpu_affinity

  • worker_priority

  • worker_rlimit_nofile

  • daemon

  • master_process

  • error_log

  • events

Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件驱动机制 、进程管理等核心功能标准HTTP模块提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应头设置 等等可选HTTP模块主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如: Flash多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等邮件服务模块实现反向代理功能,包括TCP协议代理第三方模块是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等

Nginx模块可分为:

  • 核心模块

  • Nginx 服务器正常运行必不可少的模块,提供错误日志记录 、配置文件解析 、事件

  • 驱动机制 、进程管理等核心功能

  • 标准HTTP模块

  • 提供 HTTP 协议解析相关的功能,比如: 端口配置 、 网页编码设置 、 HTTP响应

  • 头设置 等等

  • 可选HTTP模块

  • 主要用于扩展标准的 HTTP 功能,让 Nginx 能处理一些特殊的服务,比如: Flash

  • 多媒体传输 、解析 GeoIP 请求、 网络传输压缩 、 安全协议 SSL 支持等

  • 邮件服务模块

  • 实现反向代理功能,包括TCP协议代理

  • 第三方模块

  • 是为了扩展 Nginx 服务器应用,完成开发者自定义功能,比如: Json 支持、 Lua 支持等

核心模块介绍

user

作用:

进程运行使用的用户和组

示例:

user www www; 

Syntax:	user user [group];
Default:	
user nobody nobody;
Context:	main
Defines user and group credentials used by worker processes. If group is omitted, a group whose name equals that of user is used.

pid

作用:

指定存储nginx主进程号的文件路径

示例:

pid logs/nginx.pid; 

Syntax:	pid file;
Default:	
pid logs/nginx.pid;
Context:	main
Defines a file that will store the process ID of the main process.

include

作用:指明包含进来的其他配置文件

示例:

include vs/*.conf;

Syntax:	include file | mask;
Default:	—
Context:	any
Includes another file, or files matching the specified mask, into configuration. Included files should consist of syntactically correct directives and blocks.

Usage example:

include mime.types;
include vhosts/*.conf;

worker_processes

作用:

worker进程的数量,应小于等于cpu核心数,auto为当前主机cpu核心数

范例:

worker_processes 4;

Syntax:	worker_processes number | auto;
Default:	
worker_processes 1;
Context:	main
Defines the number of worker processes.

The optimal value depends on many factors including (but not limited to) the number of CPU cores, the number of hard disk drives that store data, and load pattern. When one is in doubt, setting it to the number of available CPU cores would be a good start (the value “auto” will try to autodetect it).

The auto parameter is supported starting from versions 1.3.8 and 1.2.5.

worker_cpu_affinity

作用:

配置CPU亲和,将worker进程与通过cpumask与指定cpu绑定,减少切换造成的CPU时间损耗.

范例:

worker_cpu_affinity 0001 0010 0100 1000;

Syntax:	worker_cpu_affinity cpumask ...;
worker_cpu_affinity auto [cpumask];
Default:	—
Context:	main
Binds worker processes to the sets of CPUs. Each CPU set is represented by a bitmask of allowed CPUs. There should be a separate set defined for each of the worker processes. By default, worker processes are not bound to any specific CPUs.

For example,

worker_processes    4;
worker_cpu_affinity 0001 0010 0100 1000;
binds each worker process to a separate CPU, while

worker_processes    2;
worker_cpu_affinity 0101 1010;
binds the first worker process to CPU0/CPU2, and the second worker process to CPU1/CPU3. The second example is suitable for hyper-threading.

The special value auto (1.9.10) allows binding worker processes automatically to available CPUs:

worker_processes auto;
worker_cpu_affinity auto;
The optional mask parameter can be used to limit the CPUs available for automatic binding:

worker_cpu_affinity auto 01010101;
The directive is only available on FreeBSD and Linux.

worker_priority

作用:

指定worker进程的nice值,范围[-20,20]

范例:

worker_priority -10;

Syntax:	worker_priority number;
Default:	
worker_priority 0;
Context:	main
Defines the scheduling priority for worker processes like it is done by the nice command: a negative number means higher priority. Allowed range normally varies from -20 to 20.

Example:

worker_priority -10;

worker_rlimit_nofile

作用:

指定worker进程能够打开的最大文件数

范例:

worker_rlimite_nofile 2000;

Syntax:	worker_rlimit_nofile number;
Default:	—
Context:	main
Changes the limit on the maximum number of open files (RLIMIT_NOFILE) for worker processes. Used to increase the limit without restarting the main process.

daemon

作用:

是否已守护进程方式运行Nginx

范例:

daemon on


Syntax:	daemon on | off;
Default:	
daemon on;
Context:	main
Determines whether nginx should become a daemon. Mainly used during development.

master_process

作用:是否已master-worker模型运行Nginx。该指令适用于 nginx 开发人员。

范例:

master_process on;

Syntax:	master_process on | off;
Default:	
master_process on;
Context:	main
Determines whether worker processes are started. This directive is intended for nginx developers.

error_log

作用:

配置错误日志路径和日志文件名

范例:

error_log logs/error.log error;

Syntax:	error_log file [level];
Default:	
error_log logs/error.log error;
Context:	main, http, mail, stream, server, location
Configures logging. Several logs can be specified on the same configuration level (1.5.2). If on the main configuration level writing a log to a file is not explicitly defined, the default file will be used.

The first parameter defines a file that will store the log. The special value stderr selects the standard error file. Logging to syslog can be configured by specifying the “syslog:” prefix. Logging to a cyclic memory buffer can be configured by specifying the “memory:” prefix and buffer size, and is generally used for debugging (1.7.11).

The second parameter determines the level of logging, and can be one of the following: debug, info, notice, warn, error, crit, alert, or emerg. Log levels above are listed in the order of increasing severity. Setting a certain log level will cause all messages of the specified and more severe log levels to be logged. For example, the default level error will cause error, crit, alert, and emerg messages to be logged. If this parameter is omitted then error is used.

For debug logging to work, nginx needs to be built with --with-debug, see “A debugging log”.
The directive can be specified on the stream level starting from version 1.7.11, and on the mail level starting from version 1.9.0.

events

作用:

事件驱动相关配置

范例:

events {                                  #事件驱动相关配置
    use epoll;                            #指明并发连接请求的处理方式
    worker_connections 2048;              #每个worker进程能够打开的最大并发连接数
    #accpet mutex on | off;               
    #处理新连接的方式,on意味着由每个worker轮流处理新请求,off意味着每个新请求到达都会通知所有worker进程
}

Syntax:	events { ... }
Default:	—
Context:	main
Provides the configuration file context in which the directives that affect connection processing are specified.

 

 

 

 

 

3、描述nginx中worker_processes、worker_cpu_affinity、worker_rlimit_nofile、worker_connections配置项的含义

nginx 配置文件格式说明

  • 配置文件由指令与指令块构成

  • 每条指令以;分号结尾,指令与值之间以空格符号分隔

  • 可以将多条指令放在同一行,用分号分隔即可,但可读性差,不推荐

  • 指令块以{ }大括号将多条指令组织在一起,且可以嵌套指令块

  • include语句允许组合多个配置文件以提升可维护性

  • 使用#符号添加注释,提高可读性

  • 使用$符号使用变量

  • 部分指令的参数支持正则表达式

worker_processes

启动Nginx工作进程的数量,一般设为和CPU核心数相同,auto:自动检测,设置为当前主机cpu的核心数

worker_processes [number | auto];  
 
[root@centos7 ~]#ps aux|grep nginx
root       1301  0.0  0.0  46344  2020 ?        Ss   18:52   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      2011  0.0  0.1  46772  2276 ?        S    21:21   0:00 nginx: worker process
root       2211  0.0  0.0 112808   968 pts/1    S+   22:54   0:00 grep --color=auto nginx
 
#将工作进程的数量设置为2个
[root@centos7 ~]#vim /apps/nginx/conf/nginx.conf
worker_processes  2;
[root@centos7 ~]#nginx -s reload
[root@centos7 ~]#ps aux|grep nginx
root       1301  0.0  0.1  46232  2060 ?        Ss   18:52   0:00 nginx: master process /apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
nginx      2241  0.0  0.0  46652  1932 ?        S    23:02   0:00 nginx: worker process
nginx      2242  0.0  0.0  46652  1932 ?        S    23:02   0:00 nginx: worker process

worker_cpu_affinity

将Nginx工作进程绑定到指定的CPU核心,默认Nginx是不进行进程绑定的,绑定并不是意味着当前nginx进程独占以一核心CPU,但是可以保证此进程不会运行在其他核心上,这就极大减少了nginx的工作进程在不同的cpu核心上的来回跳转,减少了CPU对进程的资源分配与回收以及内存管理等,因此可以有效的提升nginx服务器的性能

worker_cpu_affinity 00000001 00000010 00000100 00001000 | auto;
 
CPU MASK: 00000001:0号CPU
          00000010:1号CPU
          10000000:7号CPU
 
[root@centos7 ~]#ps axo pid,cmd,psr |grep nginx
  1301 nginx: master process /apps   1
  2241 nginx: worker process         0
  2242 nginx: worker process         0
  2340 grep --color=auto nginx       1
 
#将第一个工作进程绑定到 CPU0,将第二个工作进程绑定到 CPU1
[root@centos7 ~]#vim /apps/nginx/conf/nginx.conf
worker_processes  2;
worker_cpu_affinity 01 10;
[root@centos7 ~]#nginx -s reload
[root@centos7 ~]#ps axo pid,cmd,psr |grep nginx
  1274 nginx: master process /apps   0
  2029 nginx: worker process         0
  2030 nginx: worker process         1
  2036 grep --color=auto nginx       1

worker_rlimit_nofile

所有worker进程能打开的文件数量上限,包括:Nginx的所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接,另一个考虑因素是实际的并发连接数不能超过系统级别的最大打开文件数的限制。最好与ulimit -n 或者limits.conf的值保持一致。用于在不重新启动主进程的情况下增加限制

#设置工作进程的最大打开文件数为65536
[root@centos7 ~]#vim /apps/nginx/conf/nginx.conf
worker_rlimit_nofile 65536;
 
[root@centos7 ~]#ulimit -n 100000
[root@centos7 ~]#ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7835
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 100000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 7835
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
 
#修改PAM资源限制
[root@centos7 ~]#vim /etc/security/limits.conf
*                soft    core            unlimited
*                hard    core            unlimited
*                soft    nproc           1000000
*                hard    nproc           1000000
*                soft    nofile          1000000
*                hard    nofile          1000000
*                soft    memlock         32000
*                hard    memlock         32000
*                soft    msgqueue        8192000
*                hard    msgqueue        8192000
 
#重启生效
[root@centos7 ~]#reboot
[root@centos7 ~]#ulimit -n
1000000
[root@centos7 ~]#ulimit -a
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 7835
max locked memory       (kbytes, -l) 32000
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1000000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 8192000
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1000000
virtual memory          (kbytes, -v) unlimited

worker_connections

设置单个工作进程可以同时打开的最大连接数。这个数字包括所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接。另一个考虑是实际同时连接数不能超过当前最大打开文件数限制,可以通过 worker_rlimit_nofile更改。

  • 作为web服务器的时候最大并发数为:worker_connections * worker_processes

  • 作为反向代理的时候为:(worker_connections * worker_processes)/2

[root@centos7 ~]#vim /apps/nginx/conf/nginx.conf
events {
    worker_connections  10240;
    accept_mutex on;
    multi_accept on;
}
 
[root@centos7 ~]#nginx -s reload

Nginx性能优化建议

Syntax:accept_mutex on | off;
Default:accept_mutex off;
Context:events
#建议设置为accept_mutex on;

如果accept_mutex启用,工作进程将依次接受新连接,默认为off。否则,将通知所有工作进程有关新连接的信息,如果新连接量较低,则某些工作进程可能只是浪费系统资源,在高并发场景下,建议设置为on。

Syntax:multi_accept on | off;
Default:multi_accept off;
Context:events
#建议设置为multi_accept on; 

如果multi_accept禁用,工作进程将一次接受一个新连接,默认为off。开启后,工作进程将一次接受所有新连接。建议设置为on

 

 

 

4、编译安装nginx,实现多域名 https

nginx服务器              10.0.0.131(主机名:centos7-01)

客户端                       10.0.0.132(主机名:centos7-02)

一、编译安装nginx

#安装依赖包
[root@centos7-01 ~]# yum -y install gcc pcre-devel openssl-devel zlib-devel
#创建账号
[root@centos7-01 ~]# useradd -s /sbin/nologin nginx
#下载nginx-1.18,注意需要提前安装wget程序
[root@centos7-01 ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
#解压缩
[root@centos7-01 ~]# ls
anaconda-ks.cfg  nginx-1.18.0.tar.gz
[root@centos7-01 ~]# tar xf nginx-1.18.0.tar.gz
[root@centos7-01 ~]# cd nginx-1.18.0/
[root@centos7-01 nginx-1.18.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
#创建文件夹
[root@centos7-01 nginx-1.18.0]# mkdir -p  /apps/nginx
#编译
[root@centos7-01 nginx-1.18.0]# ./configure --prefix=/apps/nginx \
--user=nginx \
--group=nginx \
--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
[root@centos7-01 nginx-1.18.0]# make -j 2
#安装
[root@centos7-01 nginx-1.18.0]# make install
#修改文件夹权限
[root@centos7-01 nginx-1.18.0]# chown -R nginx.nginx /apps/nginx/
#生成的目录
[root@centos7-01 nginx-1.18.0]# ll /apps/nginx/
total 0
drwxr-xr-x 2 nginx nginx 333 Jun 15 06:24 conf
drwxr-xr-x 2 nginx nginx  40 Jun 15 06:24 html
drwxr-xr-x 2 nginx nginx   6 Jun 15 06:24 logs
drwxr-xr-x 2 nginx nginx  19 Jun 15 06:24 sbin
#conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。

#html:保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。

#logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。

#sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

#验证版本及编译参数
[root@centos7-01 nginx-1.18.0]# ls /apps/nginx/sbin/
nginx
#创建软连接
[root@centos7-01 nginx-1.18.0]# ln -s /apps/nginx/sbin/nginx /usr/sbin/
#查看版本
[root@centos7-01 nginx-1.18.0]# nginx -v
nginx version: nginx/1.18.0
#查看编译参数
[root@centos7-01 nginx-1.18.0]# nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --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

#创建service文件
[root@centos7-01 nginx-1.18.0]# vim /usr/lib/systemd/system/nginx.service
[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
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target

##创建目录存放pid
[root@centos7-01 nginx-1.18.0]# mkdir /apps/nginx/run/
[root@centos7-01 nginx-1.18.0]# chown -R nginx.nginx /apps/nginx/run/
#修改配置文件
[root@centos7-01 nginx-1.18.0]# vim /apps/nginx/conf/nginx.conf
#配置文件加入pid路径
pid        /apps/nginx/run/nginx.pid;
#验证 Nginx 自启动文件
[root@centos7-01 nginx-1.18.0]# systemctl daemon-reload
[root@centos7-01 nginx-1.18.0]# systemctl enable --now nginx
#80端口已启动
[root@centos7-01 nginx-1.18.0]# ss -ntl
State       Recv-Q Send-Q                                                Local Address:Port                                                               Peer Address:Port              
LISTEN      0      128                                                               *:22                                                                            *:*                  
LISTEN      0      100                                                       127.0.0.1:25                                                                            *:*                  
LISTEN      0      128                                                            [::]:80                                                                         [::]:*                  
LISTEN      0      128                                                            [::]:22                                                                         [::]:*                  
LISTEN      0      100                                                           [::1]:25                                                                         [::]:*  

#pid已自动生成
[root@centos7-01 nginx-1.18.0]# ll /apps/nginx/run/
total 4
-rw-r--r-- 1 root root 5 Jun 15 06:38 nginx.pid
#客户端测试验证
[root@centos7-02 ]# curl -I 10.0.0.131
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Wed, 15 Jun 2022 06:40:15 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Wed, 15 Jun 2022 06:24:53 GMT
Connection: keep-alive
ETag: "62a97b35-264"
Accept-Ranges: bytes

二、实现多域名

#新建PC web站点和Mobile web站点
#定义子配置文件路径
[root@centos7-01 nginx-1.18.0]# mkdir /apps/nginx/conf/conf.d
#加入子配置文件路径
[root@centos7-01 nginx-1.18.0]# vim /apps/nginx/conf/nginx.conf 
http {
    include       mime.types;
    default_type  application/octet-stream;
    include       /apps/nginx/conf/conf.d/*.conf; #在配置文件的最后面添加此行,注意不要放在最前面,会导致前面的命令无法生效
#创建PC站点目录
[root@centos7-01 nginx-1.18.0]# mkdir /data/nginx/html/pc/ -pv
mkdir: created directory ‘/data’
mkdir: created directory ‘/data/nginx’
mkdir: created directory ‘/data/nginx/html’
mkdir: created directory ‘/data/nginx/html/pc/’
#创建Mobile站点目录
[root@centos7-01 nginx-1.18.0]# mkdir /data/nginx/html/mobile/ -pv
mkdir: created directory ‘/data/nginx/html/mobile/’
#创建两个站点的内容
[root@centos7-01 nginx-1.18.0]# echo "pc website" > /data/nginx/html/pc/index.html
[root@centos7-01 nginx-1.18.0]# echo "mobile website" > /data/nginx/html/mobile/index.html
#创建PC网站配置
[root@centos7-01 nginx-1.18.0]# vim /apps/nginx/conf/conf.d/pc.conf
server{
   listen 80;
   server_name www.linuxma.org;
   location / {
       root /data/nginx/html/pc;
  }
}
#nginx -t检测语法、nginx -s reload优雅重启服务
[root@centos7-01 nginx-1.18.0]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@centos7-01 nginx-1.18.0]# nginx -s reload
#客户端测试访问,先改下hosts
[root@centos7-02 ~]# vim /etc/hosts
10.0.0.131 www.linuxma.org
[root@centos7-02 ~]# curl www.linuxma.org
pc website

#创建Mobile网站配置
[root@centos7-01 nginx-1.18.0]# cd /apps/nginx/conf/conf.d/
[root@centos7-01 conf.d]# ls
pc.conf
[root@centos7-01 conf.d]# cp pc.conf mobile.conf
[root@centos7-01 conf.d]# vim mobile.conf
server{
   listen 80;
   server_name m.linuxma.org;
   location / {
       root /data/nginx/html/mobile;
  }
}
[root@centos7-01 conf.d]# nginx -s reload
#客户端测试访问,先改下hosts
[root@centos7-02 ~]# vim /etc/hosts
10.0.0.131 www.linuxma.org m.linuxma.org
[root@centos7-02 ~]# curl m.linuxma.org
mobile website

三、实现多域名 https

nginx 的https 功能基于模块ngx_http_ssl_module实现,因此如果是编译安装的nginx要使用参数ngx_http_ssl_module开启ssl功能,但是作为nginx的核心功能,yum安装的nginx默认就是开启的,编译安装的nginx需要指定编译参数–with-http_ssl_module开启

Nginx 支持基于单个IP实现多域名的功能,并且还支持单IP多域名的基础之上实现HTTPS,其实是基于Nginx的 SNI(Server Name Indication)功能实现,SNI是为了解决一个Nginx服务器内使用一个IP绑定多个域名和证书的功能,其具体功能是客户端在连接到服务器建立SSL链接之前先发送要访问站点的域名(Hostname),这样服务器再根据这个域名返回给客户端一个合适的证书

[root@centos7-01 conf.d]# nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --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

#配置参数如下:
ssl on | off;
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen [ssl]替代
listen 443 ssl;

ssl_certificate /path/to/file;
#指向包含当前虚拟主机和CA的两个证书信息的文件,一般是crt文件

ssl_certificate_key /path/to/file;
#当前虚拟主机使用的私钥文件,一般是key文件

ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
#支持ssl协议版本,早期为ssl现在是TLS,默认为后三个

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];

#配置ssl缓存
off: #关闭缓存
none: #通知客户端支持ssl session cache,但实际不支持
builtin[:size]:#使用OpenSSL内建缓存,为每worker进程私有
[shared:name:size]:#在各worker之间使用一个共享的缓存,需要定义一个缓存名称和缓存空间大小,一兆可以存储4000个会话信息,多个虚拟主机可以使用相同的缓存名称

ssl_session_timeout time;
#客户端连接可以复用ssl session cache中缓存的有效时长,默认5m

#生成PC站点自签名证书
[root@centos7-01 conf.d]# cd /apps/nginx/conf/conf.d/
[root@centos7-01 conf.d]# ls
mobile.conf  pc.conf
[root@centos7-01 conf.d]# pwd
/apps/nginx/conf/conf.d
#创建签名目录
[root@centos7-01 conf.d]# mkdir ssl
#脚本实现自签名证书
[root@centos7-01 conf.d]# cd ssl/
[root@centos7-01 ssl]# vim certificate.sh
[root@centos7-01 ssl]# cat certificate.sh 
#!/bin/bash
CA_SUBJECT="/O=linuxma/CN=ca.linuxma.org"
SUBJECT="/C=CN/ST=guangdong/L=guangzhou/O=linuxma/CN=www.linuxma.org"
SERIAL=34
EXPIRE=3650
FILE=linuxma.org

openssl req  -x509 -newkey rsa:2048 -subj $CA_SUBJECT -keyout ca.key -nodes -days 3650 -out ca.crt

openssl req -newkey rsa:2048 -nodes -keyout ${FILE}.key  -subj $SUBJECT -out ${FILE}.csr

openssl x509 -req -in ${FILE}.csr  -CA ca.crt -CAkey ca.key -set_serial $SERIAL  -days $EXPIRE -out ${FILE}.crt

chmod 600 ${FILE}.key ca.key


[root@centos7-01 ssl]# bash -n certificate.sh
[root@centos7-01 ssl]# bash certificate.sh
Generating a 2048 bit RSA private key
.....................................+++
...................+++
writing new private key to 'ca.key'
-----
Generating a 2048 bit RSA private key
.............+++
.....................................................................................................................................................................................+++
writing new private key to 'linuxma.org.key'
-----
Signature ok
subject=/C=CN/ST=guangdong/L=guangzhou/O=linuxma/CN=www.linuxma.org
Getting CA Private Key

[root@centos7-01 ssl]# ls
ca.crt  ca.key  certificate.sh  linux2022.com.crt  linux2022.com.csr  linux2022.com.key
#合并CA和服务器证书成一个文件,注意服务器证书在前
[root@centos7-01 ssl]# cat linuxma.org.crt ca.crt > www.linuxma.org.crt
[root@centos7-01 ssl]# mv linuxma.org.key www.linuxma.org.key
[root@centos7-01 ssl]# ll www.linuxma.org.*
-rw-r--r-- 1 root root 2258 Jun 15 07:08 www.linuxma.org.crt
-rw------- 1 root root 1708 Jun 15 07:07 www.linuxma.org.key
#PC web站点https 配置
[root@centos7-01 ssl]# cd ..
[root@centos7-01 conf.d]# pwd
/apps/nginx/conf/conf.d
[root@centos7-01 conf.d]# ls
mobile.conf  pc.conf  ssl
[root@centos7-01 conf.d]# 
[root@centos7-01 conf.d]# vim pc.conf
server{
   listen 80;
   listen 443 ssl;
   ssl_certificate /apps/nginx/conf/conf.d/ssl/www.linuxma.org.crt;
   ssl_certificate_key /apps/nginx/conf/conf.d/ssl/www.linuxma.org.key;
   ssl_session_cache shared:sslcache:20m;
   ssl_session_timeout 10m;

   server_name www.linuxma.org;
   location / {
     root /data/nginx/html/pc;
  }
}
[root@centos7-01 conf.d]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@centos7-01 conf.d]# nginx -s reload
#客户端测试访问
[root@centos7-02 ~]# curl https://www.linuxma.org -k
pc website

#生成Mobile站点自签名证书
[root@centos7-01 conf.d]# cd ssl/
[root@centos7-01 ssl]# vim certificate.sh
#!/bin/bash
CA_SUBJECT="/O=linuxma/CN=ca.linuxma.org"
SUBJECT="/C=CN/ST=guangdong/L=guangzhou/O=linuxma/CN=m.linuxma.org"
SERIAL=34
EXPIRE=3650
FILE=m.linuxma.org

openssl req  -x509 -newkey rsa:2048 -subj $CA_SUBJECT -keyout ca.key -nodes -days 3650 -out ca.crt

openssl req -newkey rsa:2048 -nodes -keyout ${FILE}.key  -subj $SUBJECT -out ${FILE}.csr

openssl x509 -req -in ${FILE}.csr  -CA ca.crt -CAkey ca.key -set_serial $SERIAL  -days $EXPIRE -out ${FILE}.crt

chmod 600 ${FILE}.key ca.key
#删除之前无用的证书文件
[root@centos7-01 ssl]# rm -f ca*
[root@centos7-01 ssl]# rm -f linuxma.org.c*
[root@centos7-01 ssl]# ls
certificate.sh  www.linuxma.org.crt  www.linuxma.org.key
[root@centos7-01 ssl]# bash certificate.sh
Generating a 2048 bit RSA private key
....................................................................+++
.........+++
writing new private key to 'ca.key'
-----
Generating a 2048 bit RSA private key
...................+++
........................................................................................................................................+++
writing new private key to 'm.linuxma.org.key'
-----
Signature ok
subject=/C=CN/ST=guangdong/L=guangzhou/O=linuxma/CN=m.linuxma.org
Getting CA Private Key
[root@centos7-01 ssl]# ls
ca.crt  ca.key  certificate.sh  m.linuxma.org.crt  m.linuxma.org.csr  m.linuxma.org.key  www.linuxma.org.crt  www.linuxma.org.key
#合并证书文件
[root@centos7-01 ssl]# cat m.linuxma.org.crt ca.crt > m.linuxma.org.pem
#Mobile web站点https 配置
[root@centos7-01 ssl]# cd ..
[root@centos7-01 conf.d]# pwd
/apps/nginx/conf/conf.d
[root@centos7-01 conf.d]# ls
mobile.conf  pc.conf  ssl
[root@centos7-01 conf.d]# vim mobile.conf
server{
   listen 80;
   listen 443 ssl;
   ssl_certificate /apps/nginx/conf/conf.d/ssl/m.linuxma.org.pem;
   ssl_certificate_key /apps/nginx/conf/conf.d/ssl/m.linuxma.org.key;
   ssl_session_cache shared:sslcache:20m;
   ssl_session_timeout 10m;

   server_name m.linuxma.org;
   location / {
     root /data/nginx/html/mobile;
  }
}
#检测语法、重启服务
[root@centos7-01 conf.d]# nginx -t
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful
[root@centos7-01 conf.d]# nginx -s reload
#客户端测试访问
[root@centos7-02 ~]# curl https://m.linuxma.org -k
mobile website

 

 

 

 

 

5、nginx负载均衡中常见的算法及原理有哪些?

rr轮询

wrr加权轮询

ip_hash源地址hash

least_conn最少连接

可以基于ngx_http_upstream_module模块提供服务器分组转发、权重分配、状态监测、调度算法等高级功能。

#自定义一组服务器,配置在http块内
upstream name {
    server .....
    ......
}
 
#示例
upstream backend {
    server backend1.example.com weight=5;
    server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
    server unix:/tmp/backend3;
    
    server backup1.example.com backup;
}

server address [parameters];#配置一个后端web服务器,配置在upstream内,至少要有一个server服务器配置。定义服务器的address和其他parameters 。该地址可以指定为域名或 IP 地址,带有可选端口。如果未指定端口,则使用端口80。

#server支持的parameters如下:weight=number #设置服务器的权重,默认为1,实现类似于LVS中的WRR加权轮询、WLC加权最少连接等

max_conns=number #给当前后端server设置最大活动链接数,默认为0,表示没有限制

max_fails=number #设置在参数设置的持续时间内与服务器通信的不成功尝试次数。后端服务器的下线条件,当客户端访问时,对本次调度选中的后端服务器连续进行检测多少次,如果都失败就标记为不可用。默认情况下,不成功的尝试次数设置为 1。可以设置为3。当客户端访问时,才会利用TCP触发对探测后端服务器健康性检查,而非周期性的探测

fail_timeout=time #后端服务器的上线条件,对已经检测到处于不可用的后端服务器,每隔此时间间隔再次进行检测是否恢复可用,如果发现可用,则将后端服务器参与调度,默认为10秒,可以设置为1秒。

backup #设置为备份服务器,当主服务器不可用时,才会启用此备用服务器#注意:该参数不能与 hash、ip_hash和random 随机负载均衡算法一起使用。

random [two [method]]; #该指令出现在版本 Nginx1.15.1版本中。#随机负载均衡算法,将请求传递到随机选择的服务器,同时考虑服务器的权重。可选two参数指示 nginx 随机选择两个服务器,然后使用指定的method. 默认方法是least_conn,将请求传递给活动连接数最少的服务器。

down #将服务器标记为不可用状态,可以平滑下线后端服务器

resolve #监控服务器域名对应的IP地址变化,此指令为Nginx的商业版本所支持当server定义的是主机名的时候,当A记录发生变化会自动应用新IP而不用重启Nginx为了使此参数起作用,resolver必须在 http块或相应的upstream块中指定该指令。

rr轮询

rr轮询算法为nginx默认调度算法,按客户端请求顺序把客户端的请求逐一分配到不同的后端节点服务器,这相当于LVS中的rr轮询算法。如果后端节点服务器宕机,宕机的服务器会被自动从节点服务器池中剔除,以使客户端的用户访问不受影响。新的请求会分配给正常的服务器

    upstream webservers {
        server 10.0.0.17;
        server 10.0.0.27;
}
#首先需要先安装httpd 10.0.0.17和 10.0.0.27是测试页需先安装httpd并启动,并把默认页面的index.html内容改为各自的IP地址
#/etc/hosts设置好域名解析  www.linuxma.org
#代码实现nginx安装到/apps/nginx目录
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#vim /apps/nginx/conf/conf.d/pc.conf
server{
    listen 80;
    server_name www.linux.org;
    location / {
        root /data/nginx/html/pc;
        proxy_pass http://webservers;
    }
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
 
#Nginx默认带健康性检查
#后端服务器健康性检查,停掉后端10.0.0.27的Apache服务器,再次测试
[root@httpd ~]#hostname -I
10.0.0.27
[root@httpd ~]#systemctl stop httpd
[root@client ~]#http://www.linuxma.org/
10.0.0.17
[root@client ~]#http://www.linuxma.org/
10.0.0.17
[root@client ~]#http://www.linuxma.org/
10.0.0.17

wrr加权轮询

在rr轮询算法的基础上加上权重,即为权重轮询算法。权重越高,在被访问的概率越大 。可以根据服务器的配置和性能指定权重值大小,达到合理有效的地利用主机资源

upstream webservers {
    server 10.0.0.17 weight=2;
    server 10.0.0.27 weight=8;
}
#代码实现
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         server 10.0.0.17:80 weight=3;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27

ip_hash源地址hash

源地址hash调度算法,基于的客户端的remote_addr(源地址IPv4的前24位或整个IPv6地址)做hash计算,以实现会话保持。该方法确保来自同一客户端的请求将始终传递到同一服务器,除非该服务器不可用。在该服务器不可用的情况下,客户端请求将被传递到另一台服务器。很可能,它也将始终是同一台服务器。注意:当负载均衡算法为ip_hash时,后端服务器在负载均衡调度中的状态不能有weight和backup

upstream webservers {
    ip_hash;
    server 10.0.0.17;
    server 10.0.0.27;
}
如果需要临时下线其中一台服务器,则应使用down参数对其进行标记,以保留客户端 IP 地址的当前散列。
upstream backend {
    ip_hash;
    server 10.0.0.17;
    server 10.0.0.27;
    server 10.0.0.37 down;
}
#代码实现
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         ip_hash;
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27

least_conn最少连接

最少连接调度算法,优先将客户端请求调度到当前连接最少的后端服务器,相当于LVS中的WLC加权最少连接算法。同时考虑服务器的权重,如果后端服务器的连接数都相同时,则使用WRR加权轮询调度算法

upstream backserver { 
    least_conn;
    server 10.0.0.17; 
    server 10.0.0.27; 
} 
#代码实现
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         least_conn;
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证,后端服务器的连接数都相同时,则使用WRR加权轮询调度算法,默认权重是1
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27
[root@client ~]#curl http://www.linuxma.org/
10.0.0.17
[root@client ~]#curl http://www.linuxma.org/
10.0.0.27

hash KEY [consistent] 一致性hash算法

基于指定请求报文中首部字段或者URI等key做hash计算。可以包含文本、key变量及其组合如果consistent指定了参数,将使用ketama一致性hash算法。该方法确保在将服务器添加到组或从组中删除时,只有少数密钥将重新映射到不同的服务器。这有助于为缓存服务器实现更高的缓存命中率一致性hash算法适用于后端是Cache服务器(如varnish)时使用,consistent定义使用一致性hash运算,一致性hash基于取模运算注意:从组中添加或删除服务器可能会导致将大部分密钥重新映射到不同的服务器

#hash $request_uri consistent;  #基于用户请求的uri做hash,使用一致性hash运算
 
#hash $cookie_sessionid  #基于cookie中的sessionid这个key进行hash调度,实现会话绑定
 
#基于用户请求的uri做hash
#代码实现
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         hash $request_uri;
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
[root@nginx2 html]#pwd
/apps/nginx/html
[root@nginx2 html]#for i in {1..10};do echo 10.0.0.17 test$i > test$i.html;done
[root@nginx2 html]#ls
50x.html    test10.html  test2.html  test4.html  test6.html  test8.html
index.html  test1.html   test3.html  test5.html  test7.html  test9.html
[root@nginx2 html]#cat test1.html
10.0.0.17 test1
[root@nginx2 html]#cat test2.html
10.0.0.17 test2
 
[root@httpd html]#pwd
/var/www/html
[root@httpd html]#for i in {1..10};do echo 10.0.0.27 test$i > test$i.html;done
[root@httpd html]#ls
index.html   test1.html  test3.html  test5.html  test7.html  test9.html
test10.html  test2.html  test4.html  test6.html  test8.html
 
#测试验证
[root@client ~]#curl http://www.linuxma.org/test1.html
10.0.0.27 test1
[root@client ~]#curl http://www.linuxma.org/test1.html
10.0.0.27 test1
[root@client ~]#curl http://www.linuxma.org/test1.html
10.0.0.27 test1
[root@client ~]#curl http://www.linuxma.org/test2.html
10.0.0.27 test2
[root@client ~]#curl http://www.linuxma.org/test3.html
10.0.0.27 test3
[root@client ~]#curl http://www.linuxma.org/test4.html
10.0.0.17 test4
[root@client ~]#curl http://www.linuxma.org/test4.html
10.0.0.17 test4
[root@client ~]#curl http://www.linuxma.org/test4.html
10.0.0.17 test4
[root@client ~]#curl http://www.linuxma.org/test4.html
10.0.0.17 test4
 
#基于用户请求的uri做hash,使用一致性hash运算
#代码实现
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         hash $request_uri consistent;
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证
[root@client ~]#curl http://www.linuxma.org/test3.html
10.0.0.27 test3
[root@client ~]#curl http://www.linuxma.org/test3.html
10.0.0.27 test3
[root@client ~]#curl http://www.linuxma.org/test3.html
10.0.0.27 test3
[root@client ~]#curl http://www.linuxma.org/test3.html
10.0.0.27 test3
 
 
#基于Cookie实现会话绑定
#代码实现
[root@client ~]#curl -b 'name=xiaoming' http://www.linuxma.org/test3.html
10.0.0.27 test3
[root@nginx1 ~]#vim /apps/nginx/conf/nginx.conf
http {
     upstream webservers {
         hash $cookie_name consistent;
         server 10.0.0.17:80;
         server 10.0.0.27:80;
    }
 
[root@nginx1 ~]#nginx -t
[root@nginx1 ~]#nginx -s reload
 
#测试验证
[root@client ~]#curl -b 'name=xiaoming' http://www.linuxma.org/test4.html
10.0.0.17 test4
[root@client ~]#curl -b 'name=xiaoming' http://www.linuxma.org/test3.html
10.0.0.17 test3
[root@client ~]#curl -b 'name=xiaoming' http://www.linuxma.org/test2.html
10.0.0.17 test2
[root@client ~]#curl -b 'name=xiaoming' http://www.linuxma.org/test1.html
10.0.0.17 test1
 
#修改cookie值
[root@client ~]#curl -b 'name=xiaohong' http://www.linuxma.org/test1.html
10.0.0.17 test1
 
#再次测试
[root@client ~]#curl -b 'name=xiaohong' http://www.linuxma.org/test2.html
10.0.0.17 test2
[root@client ~]#curl -b 'name=xiaohong' http://www.linuxma.org/test3.html
10.0.0.17 test3
[root@client ~]#curl -b 'name=xiaohong' http://www.linuxma.org/test4.html
10.0.0.17 test4
 
#停掉后端Nginx2服务器
[root@nginx2 html]#hostname -I
10.0.0.17
[root@nginx2 html]#systemctl stop nginx
 
#再次测试,之前绑定的会话会丢失,会自动调度到另一台服务器
[root@client ~]#curl -b 'name=xiaohong' http://www.linuxma.org/test4.html
10.0.0.27 test4

 

 

 

 

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

rewrite 指令

rewrite是通过正则表达式的匹配来改变URI,可以同时存在一个或多个指令,是按照顺序依次对URI进行匹配,rewrite主要是针对用户的请求的URL和URI来做具体的处理的。nginx的rewrite的官方文档: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

语法格式:

Syntax:	rewrite regex replacement [flag];
Default:	—
Context:	server, location, if

正则表达式格式:

.	#匹配除换行符以外的任意字符
\w	#匹配字母或数字或下划线或汉字
\s	#匹配任意的空白符
\d	#匹配数字
\b	#匹配单词的开始或结束
^	#匹配字付串的开始
$	#匹配字符串的结束
*	#匹配重复零次或更多次
+	#匹配重复一次或更多次
?	#匹配重复零次或一次
(n)	#匹配重复n次
{n,}	#匹配重复n次或更多次
{n,m}	#匹配重复n到m次
*?	#匹配重复任意次,但尽可能少重复
+?	#匹配重复1次或更多次,但尽可能少重复
??	#匹配重复0次或1次,但尽可能少重复
{n,m}?	#匹配重复n到m次,但尽可能少重复
{n,}?	#匹配重复n次以上,但尽可能少重复
\W	#匹配任意不是字母,数字,下划线,汉字的字符
\S	#匹配任意不是空白符的字符
\D	#匹配任意非数字的字符
\B	#匹配不是单词开头或结束的位置
[^x]	#匹配除了x以外的任意字符
[^devops]	#匹配除了devops这几个字母以外的任意字符

rewrite flag的使用

利用nginx的rewrite的指令,可以实现url的重新跳转,rewrite有四种不同的flag,分别是redirect(临时重定向302)、permanent(永久重定向301)、break和last。其中前两种是跳转型flag,后两种是代理型

  • 跳转型指由客户端浏览器重新对新地址进行请求

  • 代理型是在WEB服务器内部实现跳转

flag 说明

redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求;使用相对路径,或者http://或https://开头,状态码:302

permanent;
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求,状态码:301

break;
#重写完成后,停止对当前URL在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使用
#适用于一个URL一次重写

last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,而后对新的URL启动新一轮重写检查,不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户

301永久重定向

域名永久型调整,即域名永远跳转至另外一个新的域名,之前的域名再也不使用,跳转记录可以缓存到客户端浏览器永久重定向会缓存DNS解析记录, 浏览器中有 from disk cache 信息,即使nginx服务器无法访问,浏览器也会利用缓存进行重定向

实例:实现域名的永久重定向

#安装好nginx后准备好配置文件
[root@centos7-01 conf.d]# pwd
/apps/nginx/conf/conf.d
[root@centos7-01 conf.d]# ls
mobile.conf  pc.conf 
[root@centos7-01 conf.d]# vim pc.conf 
server {
    listen 80;
    server_name www.linuxma.org;
    location / {
        root /data/nginx/html/pc;
        index index.html index.hml;
        rewrite / http://baidu.com permanent;
    }
}
[root@centos7-01 conf.d]# nginx -s reload
#测试访问,已经跳转到http://baidu.com,显示为301永久重定向
[root@centos7-02 ~]# curl www.linuxma.org -ikL
HTTP/1.1 301 Moved Permanently
Server: nginx/1.18.0
Date: Wed, 15 Jun 2022 08:17:35 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: http://baidu.com

用宿主机访问www.linuxma.org一下查看浏览器中有 from disk cache 信息

302临时重定向

域名临时重定向,告诉浏览器域名不是固定重定向到当前目标域名,后期可能随时会更改,因此浏览器不会缓存当前域名的解析记录,而浏览器会缓存永久重定向的DNS解析记录,这也是临时重定向与永久重定向最大的本质区别。

实例:实现域名的临时重定向

#安装好nginx后准备好配置文件
[root@centos7-01 conf.d]# pwd
/apps/nginx/conf/conf.d
[root@centos7-01 conf.d]# ls
mobile.conf  pc.conf 
[root@centos7-01 conf.d]# vim pc.conf 
server {
    listen 80;
    server_name www.linuxma.org;
    location / {
        root /data/nginx/html/pc;
        index index.html index.hml;
        rewrite / http://baidu.com redirect;
    }
}
[root@centos7-01 conf.d]# nginx -s reload
#测试访问,已经跳转到http://baidu.com,显示为302临时重定向
[root@centos7-02 ~]# curl www.linuxma.org -ikL
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0
Date: Wed, 15 Jun 2022 08:21:09 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: http://baidu.com

用宿主机访问www.linuxma.org一下查看浏览器中没有 from disk cache 信息

 

 

 

 

 

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

关闭防火墙                   systemctl disable --now firewalld

系统版本                      CentOS 7.9

nginx版本                    1.18.0

nginx服务器                10.0.0.131(主机名:centos7-01)

web服务器                  10.0.0.132(主机名:centos7-02)

客户端                         10.0.0.133(主机名:centos7-03)

一、反向代理

反向代理配置参数

proxy_pass;
#用来设置将客户端请求转发给的后端服务器的主机,可以是主机名(将转发至后端服务做为主机头首部)、IP地址:端口的方式
#也可以代理到预先设置的主机群组,需要模块ngx_http_upstream_module支持

proxy_hide_header field;
#用于nginx作为反向代理的时候,在返回给客户端http响应时,隐藏后端服务器相应头部的信息,可以设置在http,server或location块
proxy_hide_header ETag;
#隐藏后端服务器ETag首部字段

proxy_set_header;
#可更改或添加客户端的请求头部信息内容并转发至后端服务器,比如在后端服务器想要获取客户端的真实IP的时候,就要更改每一个报文的头部

#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#添加客户端IP和反向代理服务器IP到请求报文头部

“X-Forwarded-For”客户端请求标头字段,$remote_addr附加变量,用逗号分隔。
如果客户端请求标头中不存在“X-Forwarded-For”字段,
则该$proxy_add_x_forwarded_for变量等于该$remote_addr变量。

proxy_set_header X-Real-IP $remote_addr;
#添加HOST到报文头部,如果客户端为NAT上网那么其值为客户端的共用的公网IP地址,常用于在日之中记录客户端的真实IP地址。

#在后端httpd服务器修改配置,添加日志记录X-Forwarded-For字段
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" combined

反向代理缓存配置参数

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_path;
#设置缓存的路径和其他参数。缓存数据存储在文件中。

#在http配置定义缓存信息
#定义缓存保存路径,proxycache会自动创建
proxy_cache_path /data/nginx/proxycache

levels=1:2:2 
#定义缓存目录结构层次,1:2:2可以生成2^4x2^8x2^8=2^20=1048576个目录

keys_zone=proxycache:20m 
#指内存中缓存的大小,主要用于存放key和metadata(如:使用次数),一般1M可存放8000个左右的key

inactive=120s 
#缓存有效时间

max_size=1g; 
#最大磁盘占用空间,磁盘存入文件内容的缓存空间最大值

proxy_cache_key $request_uri; 
#对指定的数据进行MD5的运算做为缓存的key

proxy_cache_key $scheme$proxy_host$uri$is_args$args;
#默认情况下,指令的值接近字符串

proxy_cache proxycache;
#调用缓存功能,需要定义在相应的配置段,如server{...};或者location等

proxy_cache_valid 200 302 301 10m; 
#指定的状态码返回的数据缓存多长时间

proxy_cache_valid any 1m; 
#除指定的状态码返回的数据以外的缓存多长时间,必须设置,否则不会缓存

响应报文头部配置参数

add_header X-Via $server_addr; 
#当前nginx主机的IP

add_header X-Cache $upstream_cache_status; 
#是否缓存命中

add_header X-Accel $server_name; 
#客户访问的FQDN

nginx服务器配置

定义反向代理
[root@centos7-01 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server{
   listen 80;
    server_name www.linux.org;
    location / {
        proxy_pass http://10.0.0.132;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
[root@nginx1 conf.d]#nginx -t
[root@nginx1 conf.d]#nginx -s reload

#开启日志格式,记录x_forwarded_for
[root@centos7-01 ~]# vim /apps/nginx/conf/nginx.conf
http {
    include       mime.types;
    default_type  application/octet-stream;
    include       /apps/nginx/conf/conf.d/*.conf;
    proxy_cache_path /data/nginx/proxycache levels=1:1:1 keys_zone=proxycache:20m inactive=120s max_size=1g;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;
   
[root@nginx1 conf.d]#nginx -s reload

web服务器配置

[root@centos7-02 ~]# yum -y install httpd
#后端Apache服务器配置日志格式
[root@centos7-02 ~]# vim /etc/httpd/conf/httpd.conf
#在<IfModule log_config_module>下修改日志格式
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-For}i\"" combined
#设置访问页面
[root@centos7-02 ~]# vim /var/www/html/index.html
10.0.0.132
#启动httpd
[root@centos7-02 ~]# systemctl start httpd
root /data/nginx/html/pc;


#客户端测试
#/etc/hosts设置好域名解析  www.linux.org
[root@centos7-03 ~]# vim /etc/hosts
10.0.0.131 www.linux.org
#已经可以访问web服务器页面
[root@centos7-03 ~]# curl http://www.linux.org
10.0.0.132
#web服务器查看日志有记录到客户端IP
[root@centos7-02 ~]# tail -f /var/log/httpd/access_log
10.0.0.131 - - [16/Jun/2022:07:27:47 +0000] "GET / HTTP/1.0" 200 11 "-" "curl/7.29.0" "10.0.0.133"

 

 

 

 

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

关闭防火墙                      systemctl disable --now firewalld

系统版本                          CentOS 7.9

nginx服务器                    10.0.0.131 (主机名:centos7-01)(Nginx php-fpm 运行web服务)

数据库服务器                   10.0.0.132(主机名:centos7-02)

Nginx(1.18.0)           http://nginx.org/download/nginx-1.18.0.tar.gz

MySQL(5.7.37 )        https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz

PHP(7.4.11)              https://www.php.net/distributions/php-7.4.11.tar.xz

Wordpress(6.0)        https://cn.wordpress.org/latest-zh_CN.tar.gz

一、部署数据库

[root@centos7-02 ~]# cat install_mysql5.7.sh 
#!/bin/bash
 
. /etc/init.d/functions 
SRC_DIR=`pwd`
MYSQL='mysql-5.7.37-linux-glibc2.12-x86_64.tar.gz'
COLOR='echo -e \E[01;31m'
END='\E[0m'
MYSQL_ROOT_PASSWORD=magedu
 
 
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/
    cat > /etc/my.cnf <<-EOF
[mysqld]
server-id=1
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
	sleep 3
    [ $? -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

#创建wordpress数据库和用户并授权
[root@centos7-02 ~]# mysql -uroot -pmagedu
MySQL [(none)]> create database wordpress;
Query OK, 1 row affected (0.001 sec)

MySQL [(none)]> create user wordpress@'10.0.0.%' identified by '123456';
Query OK, 0 rows affected (0.001 sec)

MySQL [(none)]> grant all on wordpress.* to wordpress@'10.0.0.%';
Query OK, 0 rows affected (0.001 sec)
#验证MySQL账户权限

二、nginx服务器编译安装PHP

#安装依赖包
[root@centos7-01 ~]# yum -y install gcc openssl-devel libxml2-devel bzip2-devel libmcrypt-devel sqlite-devel oniguruma-devel
#将安装包上传到nginx服务器
[root@centos7-01 ~]# cd /usr/local/src
[root@centos7-01 src]# ls
php-7.4.11.tar.xz  wordpress-6.0-zh_CN.tar.gz
#解压缩php
[root@centos7-01 src]# tar xf php-7.4.11.tar.xz 
[root@centos7-01 src]# cd php-7.4.11
#创建目录
[root@centos7-01 php-7.4.11]# mkdir /apps/php74 -p
#编译
[root@centos7-01 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

#安装
[root@centos7-01 php-7.4.11]# make && make install
#php 配置文件
[root@centos7-01 php-7.4.11]# cp php.ini-production /etc/php.ini
[root@centos7-01 php-7.4.11]# cd /apps/php74/etc
[root@centos7-01 etc]# cp php-fpm.conf.default php-fpm.conf
[root@centos7-01 etc]# cd php-fpm.d/
[root@centos7-01 php-fpm.d]# cp www.conf.default www.conf
#修改配置原有的user = nobody和group = nobody改为www
[root@centos7-01 php-fpm.d]# vim www.conf
[www]
user = www
group = www
listen = 127.0.0.1:9000  #监听地址及IP
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  #慢日志路径
#创建用户
[root@centos7-01 php-fpm.d]# useradd -r -s /sbin/nologin www
#创建访问日志文件路径
[root@centos7-01 php-fpm.d]# mkdir /apps/php74/log
#启动并验证 php-fpm 服务
[root@centos7-01 php-fpm.d]# systemctl daemon-reload
[root@centos7-01 php-fpm.d]# systemctl daemon-reload
[root@centos7-01 php-fpm.d]# systemctl enable --now php-fpm
Created symlink from /etc/systemd/system/multi-user.target.wants/php-fpm.service to /usr/lib/systemd/system/php-fpm.service.
[root@centos7-01 php-fpm.d]# ss -ntlp
State       Recv-Q Send-Q                                                Local Address:Port                                                               Peer Address:Port              
LISTEN      0      128                                                               *:80                                                                            *:*                   users:(("nginx",pid=11403,fd=6),("nginx",pid=7971,fd=6))
LISTEN      0      128                                                               *:22                                                                            *:*                   users:(("sshd",pid=950,fd=3))
LISTEN      0      100                                                       127.0.0.1:25                                                                            *:*                   users:(("master",pid=1154,fd=13))
LISTEN      0      128                                                               *:443                                                                           *:*                   users:(("nginx",pid=11403,fd=12),("nginx",pid=7971,fd=12))
LISTEN      0      128                                                       127.0.0.1:9000                                                                          *:*                   users:(("php-fpm",pid=54573,fd=9),("php-fpm",pid=54572,fd=9),("php-fpm",pid=54571,fd=7))
LISTEN      0      128                                                            [::]:22                                                                         [::]:*                   users:(("sshd",pid=950,fd=4))
LISTEN      0      100                                                           [::1]:25                                                                         [::]:*  

[root@centos7-01 php-fpm.d]# ps -ef |grep php
root      54571      1  0 12:06 ?        00:00:00 php-fpm: master process (/apps/php74/etc/php-fpm.conf)
www       54572  54571  0 12:06 ?        00:00:00 php-fpm: pool www
www       54573  54571  0 12:06 ?        00:00:00 php-fpm: pool www
root      54578  11294  0 12:07 pts/0    00:00:00 grep --color=auto php

三、nginx服务器编译安装nginx

#安装依赖包
[root@centos7-01 ~]# yum -y install gcc pcre-devel openssl-devel zlib-devel
#创建账号
[root@centos7-01 ~]# useradd -s /sbin/nologin nginx
#下载nginx-1.18,注意需要提前安装wget程序
[root@centos7-01 ~]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
#解压缩
[root@centos7-01 ~]# ls
anaconda-ks.cfg  nginx-1.18.0.tar.gz
[root@centos7-01 ~]# tar xf nginx-1.18.0.tar.gz
[root@centos7-01 ~]# cd nginx-1.18.0/
[root@centos7-01 nginx-1.18.0]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  README  src
#创建文件夹
[root@centos7-01 nginx-1.18.0]# mkdir -p  /apps/nginx
#编译
[root@centos7-01 nginx-1.18.0]# ./configure --prefix=/apps/nginx \
--user=nginx \
--group=nginx \
--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
[root@centos7-01 nginx-1.18.0]# make -j 2
#安装
[root@centos7-01 nginx-1.18.0]# make install
#修改文件夹权限
[root@centos7-01 nginx-1.18.0]# chown -R nginx.nginx /apps/nginx/
#生成的目录
[root@centos7-01 nginx-1.18.0]# ll /apps/nginx/
total 0
drwxr-xr-x 2 nginx nginx 333 Jun 15 06:24 conf
drwxr-xr-x 2 nginx nginx  40 Jun 15 06:24 html
drwxr-xr-x 2 nginx nginx   6 Jun 15 06:24 logs
drwxr-xr-x 2 nginx nginx  19 Jun 15 06:24 sbin
#conf:保存nginx所有的配置文件,其中nginx.conf是nginx服务器的最核心最主要的配置文件,其他的.conf则是用来配置nginx相关的功能的,例如fastcgi功能使用的是fastcgi.conf和fastcgi_params两个文件,配置文件一般都有个样板配置文件,是文件名.default结尾,使用的使用将其复制为并将default去掉即可。

#html:保存了nginx服务器的web文件,但是可以更改为其他目录保存web文件,另外还有一个50x的web文件是默认的错误页面提示页面。

#logs:用来保存nginx服务器的访问日志错误日志等日志,logs目录可以放在其他路径,比如/var/logs/nginx里面。

#sbin:保存nginx二进制启动脚本,可以接受不同的参数以实现不同的功能。

#验证版本及编译参数
[root@centos7-01 nginx-1.18.0]# ls /apps/nginx/sbin/
nginx
#创建软连接
[root@centos7-01 nginx-1.18.0]# ln -s /apps/nginx/sbin/nginx /usr/sbin/
#查看版本
[root@centos7-01 nginx-1.18.0]# nginx -v
nginx version: nginx/1.18.0
#查看编译参数
[root@centos7-01 nginx-1.18.0]# nginx -V
nginx version: nginx/1.18.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/nginx --user=nginx --group=nginx --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

#创建service文件
[root@centos7-01 nginx-1.18.0]# vim /usr/lib/systemd/system/nginx.service
[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
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target

##创建目录存放pid
[root@centos7-01 nginx-1.18.0]# mkdir /apps/nginx/run/
[root@centos7-01 nginx-1.18.0]# chown -R nginx.nginx /apps/nginx/run/
#修改配置文件
[root@centos7-01 nginx-1.18.0]# vim /apps/nginx/conf/nginx.conf
#配置文件加入pid路径
pid        /apps/nginx/run/nginx.pid;
#验证 Nginx 自启动文件
[root@centos7-01 nginx-1.18.0]# systemctl daemon-reload
[root@centos7-01 nginx-1.18.0]# systemctl enable --now nginx
#80端口已启动
[root@centos7-01 nginx-1.18.0]# ss -ntl
State       Recv-Q Send-Q                                                Local Address:Port                                                               Peer Address:Port              
LISTEN      0      128                                                               *:22                                                                            *:*                  
LISTEN      0      100                                                       127.0.0.1:25                                                                            *:*                  
LISTEN      0      128                                                            [::]:80                                                                         [::]:*                  
LISTEN      0      128                                                            [::]:22                                                                         [::]:*                  
LISTEN      0      100                                                           [::1]:25                                                                         [::]:*  

#pid已自动生成
[root@centos7-01 nginx-1.18.0]# ll /apps/nginx/run/
total 4
-rw-r--r-- 1 root root 5 Jun 15 06:38 nginx.pid
#配置 Nginx 支持 fastcgi
[root@centos7-01 php-fpm.d]# vim /apps/nginx/conf/nginx.conf
   include       mime.types;
   default_type application/octet-stream;
   sendfile       on;
   keepalive_timeout  65;
   server {
       listen       80;
       server_name www.linux.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$ {                         #实现php-fpm
           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;
       } 
   }
#准备 php 测试页
[root@centos7-01 php-fpm.d]# mkdir -p /data/nginx/wordpress
[root@centos7-01 php-fpm.d]# vim /data/nginx/wordpress/test.php
<?php
  phpinfo();
?>
#宿主机浏览器打开测试,宿主机配置C:\Windows\System32\drivers\etc\hosts文件加入10.0.0.131 www.linux666666.org
www.linux.org/ping
www.linxu.org/pm_status
www.linux.org/test.php

访问测试

四、nginx服务器部署WordPress

#解压缩
[root@centos7-01 src]# tar xf wordpress-6.0-zh_CN.tar.gz 
[root@centos7-01 src]# ls
php-7.4.11  php-7.4.11.tar.xz  wordpress  wordpress-6.0-zh_CN.tar.gz
#拷贝文件
[root@centos7-01 src]# cp -r wordpress/* /data/nginx/wordpress
#修改权限
[root@centos7-01 src]#  chown -R www.www /data/nginx/wordpress/

初始化web页面

#配置允许上传大文件
#注意:默认只支持1M以下文件上传,要利用php程序上传大图片,还需要修改下面三项配置,最大上传由三项值
的最小值决定
#直接上传大于1M文件,会出现下面413错误
#nginx上传文件大小限制
[root@centos7-01 ~]# vim /apps/nginx/conf/nginx.conf
server {
       client_max_body_size 10m; #默认值为1M
.....
#php上传文件大小限制
[root@centos7-01 ~]# vim /etc/php.ini
post_max_size = 30M   #默认值为8M
upload_max_filesize = 20M  #默认值为2M
[root@centos7-01 ~]# #systemctl restart nginx php-fp
#配置 php 开启 opcache 加速

#编辑php.ini配置文件
[root@centos7-01 ~]# vim /etc/php.ini
[opcache]
; Determines if Zend OPCache is enabled
zend_extension=opcache.so                                                       
                            opcache.enable=1
.....
[root@centos7-01 ~]# systemctl restart php-fpm

#配置 php 开启 opcache 加速,找到[opcache],位置加入以下内容
[root@centos7-01 ~]# vim /etc/php.ini
[opcache]
zend_extension=opcache.so
opcache.enable=1
[root@centos7-01 ~]# systemctl restart php-fpm

浏览器访问测试页确认开启opcache加速

 

 

 

 

 

 

9、简述keepalived工作原理

Keepalived主要用于解决各种服务集群的高可用性问题,高可用集群类型主要包括LB(Load Balance负载均衡)、HA(High Availability高可用集群)和HPC(High Performance Computing高性能集群)三大类,其中我们主要关注的是前两类。

​ 在LB中我们可能会用到LVS来达到负载均衡,但集群前面的调度器依然可能会存在单点失败问题,因此可以用到keepalived。keepalived在设计之初就是为了配合LVS解决单点失败问题,并在后期加入了VRRP协议,能为Nginx、MySQL和HAProxy等服务的集群提供高可用解决方案。因此在了解keepalived工作原理前,我们先来看下什么是VRRP。

VRRP

​  VRRP(Virtual Router Redundancy Protocol),虚拟路由冗余协议,它借鉴了物理路由器的技术,并逐渐引用到Linux系统中,成为了keepalived软件的核心组件,用于解决静态网关单点风险。VRRP协议是一种容错协议,它保证了当某一台路由出现故障时,另一台路由器能及时替代出现故障的路由器进行工作,从而保持网络通信的连续性和可靠性。

VRRP网络层硬件实现

​ 当企业内网服务器数量较多时,可能会用到多台路由器,以下图为例,201.1.1.1和201.1.1.2为使用公网IP的路由器,172开头的为使用内网IP的能提供具体服务的服务器。

由于路由器只有一个入口和一个出口,可能会出现以下情况:

​ ①当用户通过路由器向企业内网服务器发出服务请求时,可能是由201.1.1.1或201.1.1.2中任意一台向内网服务器进行转发,并且每一台路由器和内网服务器之间是类似于绑定的状态,而且当某一台路由器出现故障时,指向该路由器的内网服务器将无法对外提供服务,并不能解决单点失败问题。

​ ②如果内网服务器指向多台路由器,当用户发送服务请求时,由于企业内网和经过公网路由一般做NAT转换,可能会导致用户收到的第一个包来自201.1.1.1,第二个包则是来自201.1.1.2,无法判断出是否是同一个用户或出现用户无法登录等情况。该方法虽然在一定程度上解决了内网服务器的负载均衡,但会导致无法上网等情况。

​ 针对以上问题,我们可以虚拟出一个VIP地址201.1.1.3,让内网服务器的网关都指向该VIP,该VIP是流动的,并不固定在201.1.1.1或201.1.1.2上。当用户发起服务请求时会到达201.1.1.3这个VIP,如果VIP此刻正处于201.1.1.1这个路由器上,就由201.1.1.1向内网服务器进行转发,响应报文的出口由VIP出去;当201.1.1.1出现故障时,VIP就会通过201.1.1.2这台路由器来向内网服务器进行服务请求的转发,并且最终出口还是VIP的地址201.1.1.3,从而解决了高可用问题。

VRRP相关术语

    VRRP相关术语包括以下几种:

    ①虚拟路由器:Virtual Router,由一个Master路由器和多个Backup路由器组成,主机将虚拟路由器当作默认网关。

    ②虚拟路由器标识:VRID(0-255),唯一标识虚拟路由器,有相同VRID的一组路由器构成一个虚拟路由器。

    ③虚拟IP地址(VIP):Virtual IP,一个虚拟路由器可以拥有一个或多个IP地址;

    ④虚拟MAC地址(VMAC):Virutal MAC (00-00-5e-00-01-VRID),一个虚拟路由器拥有一个虚拟MAC地址,通常情况下虚拟路由器回应ARP请求使用的是虚拟MAC地址,只有虚拟路由器做特殊配置的时候,才回应接口的真实 MAC 地址。

    ⑤物理路由器,该术语主要注意三部分内容:master(主设备),虚拟路由器中承担报文转发任务的路由器;backup(备用设备),master路由器出现故障时,能够代替master路由器工作的路由器;priority(优先级),VRRP根据优先级来确定虚拟路由器中每台路由器的地位。

VRRP相关技术

    VRRP相关技术包括:

    ①通告:主要是对外通告心跳和优先级等,并且通告是周期性的,具体时间可以自定义;

    ②工作方式:工作方式分抢占式和非抢占式两种,在抢占式中,如果备用设备的优先级比主设备优先级高,则主动将自己切换成主设备;在非抢占式中,如果主设备没有出现故障,备用设备即使被设置了更高的优先级也不会成为主设备。

    ③安全认证:安全认证包括无认证、简单字符认证(利用预共享秘钥等方式来实现)和MD5认证三种。

    ④工作模式:VRRP工作模式包括主/备模式和主/主模式两种,在主/备模式下虚拟出一台路由器即可,而在主/主模式需虚拟出两台路由器,并且要将彼此设为主/备。

 

keepalived工作原理    keepalived是基于VRRP协议的软件实现,其原生设计目的为了高可用ipvs服务。

keepalived功能

    keepalived的功能包括以下几点:

    ①基于VRRP协议完成地址流动;

    ②为VIP地址所在的节点生成ipvs规则(在配置文件中预先定义) ;

    ③为ipvs集群的各RS做健康状态检测;

    ④基于脚本调用接口完成脚本中定义的功能,进而影响集群事务,以此支持Nginx、HAProxy等服务。

keepalived架构

    keepalived架构如下图所示,可分为用户空间核心组件、控制组件、IO复用器和内存管理组件四部分。

  ①用户空间核心组件包括:VRRP Stack(VIP消息通告)、Checkers(监测real server)、System call(实现 vrrp 协议状态转换时调用脚本的功能)、SMTP(邮件组件)、IPVS wrapper(生成IPVS规则)、Netlink Reflector(网络接口)和WatchDog(监控进程);

    ②控制组件主要是提供keepalived.conf 的解析器,以完成Keepalived配置;

    ③IO复用器可以针对网络目的而优化的自己的线程抽象;

    ④内存管理组件可以为某些通用的内存管理功能(例如分配,重新分配,发布等)提供访问权限。

keepalived工作原理

    在了解了以上知识后,我们可以总结keepalived工作原理:

    ①keepalived服务对之间通过VRRP来进行通信,VRRP利用竞选机制来确定主节点和备用节点,优先级高的作为主节点,优先级低的作为备用节点;

    ②主节点在工作时会优先获得所有的资源,而备用节点则是处于等待状态。只有在主节点出现故障时,备用节点才会接管主节点的资源,并作为新的主节点对外提供服务;

    ③keepalived服务对中,只有主节点的服务器会一直发送VRRP广播包来传递heartbeat信息,告诉备用节点它还活着,此时备用节点不会抢占主节点资源;

    ④当主节点出现故障不可用时,备用节点因无法接收到主节点发送的VRRP广播,就会启动相关服务接管主节点的资源,保证业务的连续性。而当之前出现故障的主节点恢复正常后,现有的由备用节点转变过来的主节点会自动释放已接管的资源,重新由恢复正常的主节点接管。

 

 

 

 

 

 

10、编译安装haproxy

准备环境

由于centos7之前版本自带的lua版本比较低并不符合HAProxy要求的lua最低版本(5.3)的要求,因此需要编译安装较新版本的lua环境,然后才能编译安装HAProxy,过程如下

#当前系统版本
[root@centos7-01 ~]# lua -v
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
#安装基础命令及编译依赖环境
[root@centos7-01 ~]# yum install gcc readline-devel -y
#下载lua
[root@centos7-01 ~]# wget http://www.lua.org/ftp/lua-5.4.4.tar.gz
#解压缩
[root@centos7-01 ~]# tar xvf lua-5.4.4.tar.gz -C /usr/local/src
#编译安装
[root@centos7-01 ~]# cd /usr/local/src/lua-5.4.4/
[root@centos7-01 lua-5.4.4]# make linux test
#查看编译安装的版本
[root@centos7-01 lua-5.4.4]# src/lua -v
Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio

编译安装HAProxy

#下载HAProxy
[root@centos7-01 ~]# wget https://www.haproxy.org/download/2.4/src/haproxy-2.4.15.tar.gz
#HAProxy 2.0以上版本编译参数:
[root@centos7-01 ~]# yum -y install gcc openssl-devel pcre-devel systemd-devel
[root@centos7-01 ~]# tar xvf haproxy-2.4.15.tar.gz -C /usr/local/src
#编译安装
[root@centos7-01 ~]# cd /usr/local/src/haproxy-2.4.15/
[root@centos7-01 haproxy-2.4.15]# 
#查看安装方法
[root@centos7-01 haproxy-2.4.15]# less INSTALL
[root@centos7-01 haproxy-2.4.15]# less Makefile
[root@centos7-01 haproxy-2.4.15]# make ARCH=x86_64 TARGET=linux-glibc USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_LUA=1 LUA_INC=/usr/local/src/lua-5.4.4/src/ LUA_LIB=/usr/local/src/lua-5.4.4/src/
[root@centos7-01 haproxy-2.4.15]# make install PREFIX=/apps/haproxy
#软链接
[root@centos7-01 haproxy-2.4.15]# ln -s /apps/haproxy/sbin/haproxy /usr/sbin/
#验证HAProxy版本
[root@centos7-01 haproxy-2.4.15]# which haproxy
/usr/sbin/haproxy
#大写-V选项显示版本和帮助用法
[root@centos7-01 haproxy-2.4.15]# haproxy -v
HAProxy version 2.4.15-7782e23 2022/03/14 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.15.html
Running on: Linux 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64
[root@centos7-01 haproxy-2.4.15]# #haproxy -V
[root@centos7-01 haproxy-2.4.15]# haproxy -V
HAProxy version 2.4.15-7782e23 2022/03/14 - https://haproxy.org/
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.15.html
Running on: Linux 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020 x86_64
Usage : haproxy [-f <cfgfile|cfgdir>]* [ -vdVD ] [ -n <maxconn> ] [ -N <maxpconn> ]
        [ -p <pidfile> ] [ -m <max megs> ] [ -C <dir> ] [-- <cfgfile>*]
        -v displays version ; -vv shows known build options.
        -d enters debug mode ; -db only disables background mode.
        -dM[<byte>] poisons memory with <byte> (defaults to 0x50)
        -V enters verbose mode (disables quiet mode)
        -D goes daemon ; -C changes to <dir> before loading files.
        -W master-worker mode.
        -Ws master-worker mode with systemd notify support.
        -q quiet mode : don t display messages
        -c check mode : only check config files and exit
        -n sets the maximum total # of connections (uses ulimit -n)
        -m limits the usable amount of memory (in MB)
        -N sets the default, per-proxy maximum # of connections (0)
        -L set local peer name (default to hostname)
        -p writes pids of all children to this file
        -de disables epoll() usage even when available
        -dp disables poll() usage even when available
        -dS disables splice usage (broken on old kernels)
        -dG disables getaddrinfo() usage
        -dR disables SO_REUSEPORT usage
        -dL dumps loaded object files after config checks
        -dr ignores server address resolution failures
        -dV disables SSL verify on servers side
        -dW fails if any warning is emitted
        -dD diagnostic mode : warn about suspicious configuration statements
        -sf/-st [pid ]* finishes/terminates old pids.
        -x <unix_socket> get listening sockets from a unix socket
        -S <bind>[,<bind options>...] new master CLI
#准备HAProxy启动文件
[root@centos7-01 haproxy-2.4.15]# vim /usr/lib/systemd/system/haproxy.service
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target
#配置文件
[root@centos7-01 haproxy-2.4.15]# mkdir /etc/haproxy
[root@centos7-01 haproxy-2.4.15]# vim /etc/haproxy/haproxy.cfg
global
    maxconn 100000
    chroot /apps/haproxy
    stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
    #uid 99
    #gid 99
    user haproxy
    group haproxy
    daemon
    #nbproc 4
    #cpu-map 1 0
    #cpu-map 2 1
    #cpu-map 3 2
    #cpu-map 4 3
    pidfile /var/lib/haproxy/haproxy.pid
    log 127.0.0.1 local2 info

defaults
    option http-keep-alive
    option forwardfor
    maxconn 100000
    mode http
    timeout connect 300000ms
    timeout client 300000ms
    timeout server 300000ms

listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri /haproxy-status
    stats auth haadmin:123456

listen web_port
    bind 10.0.0.131:80
    mode http
    log global
    server web1 127.0.0.1:8080 check inter 3000 fall 2 rise 5
#启动 haproxy
#准备socket文件目录
[root@centos7-01 haproxy-2.4.15]# mkdir /var/lib/haproxy
#设置用户和目录权限
[root@centos7-01 haproxy-2.4.15]# useradd -r -s /sbin/nologin -d /var/lib/haproxy haproxy
#启动
[root@centos7-01 haproxy-2.4.15]# systemctl enable --now haproxy
#验证 haproxy 状态
[root@centos7-01 ~]# systemctl status haproxy
● haproxy.service - HAProxy Load Balancer
   Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendor preset: disabled)
   Active: active (running) since Thu 2022-06-16 22:56:48 UTC; 5s ago
  Process: 1480 ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q (code=exited, status=0/SUCCESS)
 Main PID: 1483 (haproxy)
   CGroup: /system.slice/haproxy.service
           ├─1483 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
           └─1486 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid

Jun 16 22:56:48 centos7-01 systemd[1]: Starting HAProxy Load Balancer...
Jun 16 22:56:48 centos7-01 systemd[1]: Started HAProxy Load Balancer.
Jun 16 22:56:48 centos7-01 haproxy[1483]: [NOTICE]   (1483) : New worker #1 (1486) forked
Jun 16 22:56:48 centos7-01 haproxy[1483]: [WARNING]  (1486) : Server web_port/web1 is DOWN, reason: Layer4 connection problem, info: "Connection refused", check duration: 2...ng in queue.
Jun 16 22:56:48 centos7-01 haproxy[1483]: [NOTICE]   (1486) : haproxy version is 2.4.15-7782e23
Jun 16 22:56:48 centos7-01 haproxy[1483]: [NOTICE]   (1486) : path to executable is /usr/sbin/haproxy
Jun 16 22:56:48 centos7-01 haproxy[1483]: [ALERT]    (1486) : proxy 'web_port' has no server available!
Hint: Some lines were ellipsized, use -l to show in full.

 

浏览器登录验证,用户名haadmin 密码123456

posted @   海阔天空1122  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示