Nginx 介绍

1.1 引言

为什么要学习 Nginx
问题1:客户端到底要将请求发送给哪台服务器。
问题2:如果所有客户端的请求都发送给了服务器1。
问题3:客户端发送的请求可能是申请动态资源,也有申请静态资源。

  服务器搭建集群后

  在搭建集群后,使用Nginx做反向代理服务器

1.2 Nginx介绍

Nginx是由俄罗斯人研发的,应对Rambler网站,并在2004年发布的第一个版本。
Nginx特点:
1、稳定性极强,7*24小时不间断运行。
2、Nginx提供了非常丰富的配置实例。
3、占用内存极小,并发能力强。

Nginx的安装

2.1 安装Nginx

快速安装:
[root@localhost ~]# yum install -y epel-release
[root@localhost ~]# yum install -y nginx
[root@localhost ~]# systemctl start nginx
[root@localhost ~]# systemctl enable nginx
[root@localhost ~]# yum install -y php-fpm                #使Nginx支持php
[root@localhost ~]# systemctl start php-fpm
[root@localhost ~]# systemctl enable php-fpm

二进制源码编译安装详见:
https://www.ujslxw.com/2021/10/06/47.html

2.2 Nginx的配置文件

关于Nginx的核心配置文件nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;

# 以上统称为全局块    
# work_processes它的数值越大,Nginx的并发能力就越强
# error_log代表Nginx的错误日志存放的位置

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

# event块
# worker_connections它的数值越大,Nginx并发能力越强


# http块
# include代表引入一个外部文件——> /mine.types中放着大量的媒体类型
# include /etc/nginx/conf.d/*.conf;——>引入了conf.d目录下的以.conf为结尾的配置文件

http {
    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  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;

        # server块
    # listen:代表Nginx监听的端口号
    # localhost:代表Nginx接收请求的ip
    
    server {
        listen       80;
        server_name  localhost;

                # location块
        # root:将接收到的请求根据/usr/share/nginx/html去查找静态资源
        # index:默认去上述的路径中找到index.html或者index.htm

        location / {
                root        /usr/share/nginx/html;
            index        index.html index.htm;    
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

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

Nginx实现反向代理

3.1 正向代理和反向代理介绍

正向代理:
1、正向代理服务是由客户端设立的。
2、客户端了解代理服务器和目标服务器都是谁。
3、帮助咱们实现突破访问权限,提高访问的速度,对目标服务器隐藏客户端的IP地址。

反向代理:
1、反向代理服务器是配置在服务端的。
2、客户端是不知道访问的到底是哪一台服务器。
3、到达负载均衡,并且可以隐藏服务器真正的IP地址。

3.2 基于Nginx实现反向代理

准备一个目标服务器
启动node1 Nginx Web服务器
配置反向代理服务器
编写Nginx的配置文件通过访问Nginx反向代理访问到Nginx Web服务器
[root@localhost ~]# vim /etc/nginx/conf.d/default.conf

server {
    listen          80;
    server_name     192.168.144.134;        #反向代理服务器IP地址
    # server_name 可以写域名也可以写ip地址

    # 基于反向代理访问到Linux for Meth首页
    location / {
        proxy_pass https://www.ujslxw.com/index.php;    # Linux for Meth首页
        index index.php index.html index.htm;
    }
}

3.3 关于Nginx的location路径映射

优先级关系:
(location) > (location /xxx/yyy/zzz/) > (location ^~) > (location ~,~*) > (location /起始路径) > (location /)
# 1. = 匹配
location = / {
    # 精准匹配,主机名后面不能带任何的字符串
}

# 2. 通用匹配
location / {
    # 匹配所有以/###开头的路径
}

# 3. 正则匹配
location ~ /xxx {
    # 匹配所有以/xxx开头的路径
}

# 4.匹配开头路径
location ^~ /images/ {
    # 匹配所有以/images开头的路径
}

# 5.匹配后缀
location ~* \.(jif|jpg|png)$ {
    # 匹配以gif或者jpg或者png为结尾的匹配
}

配置实验
访问192.168.144.134到达node2
访问192.168.144.134/index到达node1
访问192.168.144.134/index到达Linux for Meth首页
[root@localhost ~]# vim /etc/nginx/conf.d/default.conf
server {
    listen          80;
    server_name     192.168.144.134;
    # server_name 可以写域名也可以写ip地址

    # 基于反向代理访问到Nginx Web服务器node1
    location =  /index {
        proxy_pass http://192.168.144.135:80/;          # node1
        index index.php index.html index.htm;
}


    location ^~ /php/ {
        proxy_pass https://www.ujslxw.com/index.php;    # Linux for Meth首页
        index index.php index.html index.htm;
}


        # 基于反向代理访问到Nginx Web服务器node2
    location / {
        proxy_pass http://192.168.144.136:80/;          # node2
        index index.php index.html index.htm;
    }
}

Nginx负载均衡

Nginx为我们默认提供了三种负载均衡策略:
1.轮询:
将客户端发起的请求,平均的分配给每一台服务器
2.权重:
会将客户端的请求根据服务器的权重不同,分配不同的数量
3.ip_hash:
基于发起请求的ip地址不同,它始终会将请求发送到指定的服务器上

  在做负载均衡实验时遇到了一个问题,配置文件正确的时候,无法成功实现负载均衡。原因是在/etc/nginx/nginx.conf主配置文件下,include /etc/nginx/conf.d/*.conf;相当于将conf.d/目录下的配置文件插在include /etc/nginx/conf.d/*.conf;下面,从下往上匹配server块,相当于优先匹配nginx.conf下的server块,再匹配conf.d/目录下的server块,导致负载均衡实验失败。
  解决方案有两种:
  1、将nginx.conf下的include /etc/nginx/conf.d/*.conf;放置在server块的下方。
  2、注释掉nginx.conf中的默认server块

4.1 轮询

想实现Nginx轮询负载均衡机制只需要在文件中添加以下内容。
upstream 名字 {                # 该名字不要添加下划线,否则会出问题
    server ip:port;
    server ip:port;
    ...
}

server {
    listen 80;
    server_name localhost;
    
    location / {
        proxy_pass http://upstream的名字/;
    }
}

  示例:

[root@localhost conf.d]# vim default.conf
upstream my-server {
    server 192.168.144.134:80;
    server 192.168.144.134:8081;
}

server {
    listen 80;
    server_name localhost;
    
    location / {
    proxy_pass http://my-server/;
    }
}

4.2 权重

实现权重的方式
upstream 名字 {                # 该名字不要添加下划线,否则会出问题
    server ip:port weight=权重比例;
    server ip:port weight=权重比例;
    ...
}

server {
    listen 80;
    server_name localhost;
    
    location / {
        proxy_pass http://upstream的名字/;
    }
}

  示例:

[root@localhost conf.d]# vim default.conf
upstream my-server {
    server 192.168.144.135:80 weight=10;        # 每6次访问,其中有5次访问node1
    server 192.168.144.136:80 weight=2;            # 每6次访问,其中有1次访问node2
}

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://my-server/;
    }
}

4.3 ip_hash

ip_hash实现
[root@localhost conf.d]# vim default.conf
upstream my-server {
    ip_hash;
    # 加不加权重无所谓
    server 192.168.144.135:80 weight=10;        # 每6次访问,其中有5次访问node1
    server 192.168.144.136:80 weight=2;            # 每6次访问,其中有1次访问node2
}

server {
    listen 80;
    server_name localhost;

    location / {
        proxy_pass http://my-server/;
    }
}

Nginx动静分离

Nginx的并发能力公式
worker_processes*worker_connections/4 | 2 = Nginx最终的并发能力
动态资源需要/4,静态资源需要/2
Nginx通过动静分离,来提升Nginx的并发能力,更快的给用户响应

  动态资源需要4个连接数:

  静态资源需要2个连接数:

5.1 动态资源代理

# 配置如下
location / {
    proxy_pass 路径;
}

5.2 静态资源代理

# 配置如下
location / {
    root 静态资源路径;
    index 默认访问路径下的什么资源;
    autoindex on;    # 展示静态资源全部的内容,以列表的形式展开
}

# 在/data/html目录下添加index.html静态资源
# 在/data/img目录下添加了1.png静态资源
# 修改配置文件/etc/nginx/conf.d/default.conf

[root@localhost ~]# vim /etc/nginx/conf.d/default.conf 
server {
    listen 80;
    server_name 192.168.144.135:80;
    # 代理到html静态资源
    location /html {
        root /data;
        index index.php index.html index.htm;
}
    # 代理到img静态资源
    location /img {
        root /data;
        autoindex on;
}

Nginx集群

6.1 引言

单点故障,避免Nginx的宕机,导致整个程序的崩溃。
准备多台Nginx。
准备keepalived,监听Nginx的健康情况。
准备haproxy,提供一个虚拟的路径,统一的去接收用户的请求。

6.2 Nginx集群

使用脚本
#先准备好以下文件放入/opt/docker_nginx_cluster目录中
#然后启动容器    注意确保80、8081和8082端口未被占用(或者修改docker-compose.yml中的端口)
docker-compose up -d

然后我们访问8081端口可以看到master,访问8082端口可以看到slave
因为我们设置了81端口的master优先级未200比82端口的slave优先级100高,所以我们访问80端口看到的是master
现在我们模仿8081端口的nginx宕机了,将keep-master
docker stop 8081端口nginx容器的ID
这时我们再去访问80端口看到的就是slave了

  Dockerfile

FROM nginx:1.13.5-alpine

RUN apk update && apk upgrade

RUN apk add --no-cache bash curl ipvsadm iproute2 openrc keepalived

COPY entrypoint.sh /entrypoint.sh

RUN chmod +x /entrypoint.sh

CMD ["/entrypoint.sh"]

  entrypoint.sh

#!/bin/sh

#/usr/sbin/keepalvined -n -l -D -f /etc/keepalived/keepalived.conf --dont-fork --log-console &
/usr/sbin/keepalvined -D -f /etc/keepalived/keepalived.conf


nginx -g "daemon off;"

  docker-compose.yml

version: "3.1"
services:
  nginx_master:
    build:
      context: ./
      dockerfile: ./Dockerfile
    ports:
      -8081:80
    volumes:
      - ./index-master.html:/usr/share/nnginx/html/index.html
      - ./favicon.ico:/usr/share/nnginx/html/favicon.ico
      - ./keepalived-master.conf:/etv/keepalived/keepalived.conf
    networks:
      static-network:
        ipv4_address:172.20.128.2
    cap_add:
      - NET_ADMIN
  nginx_slave:
    build:
      context: ./
      dockerfile: ./Dockerfile
    ports:
      -8082:80
    volumes:
      - ./index-slave.html:/usr/share/nnginx/html/index.html
      - ./favicon.ico:/usr/share/nnginx/html/favicon.ico
      - ./keepalived-slave.conf:/etv/keepalived/keepalived.conf
    networks:
      static-network:
        ipv4_address:172.20.128.3
    cap_add:
      - NET_ADMIN
  proxy:
    image:  haproxy:1.7-apline
    ports:
      - 80:6301
    volumes:
      - ./happroxy.cfg:/usr/local/etc/haproxy/haproxy.cfg
    networks:
      - static-network
networks:
  static-network:
    ipam:
      congig:
        - subnet: 172.20.0.0/16

  keepalived-master.conf

vrrp_script chk_nginx {
    script "pidof nginx"
    interval 2
}

vrrp_instance VI_1 {
    state MASTER
    interface etch0    #容器内部的网卡名称
    virtual_router_id 33
    priority 200    #优先级
    advert_int 1
    
    autheentication {
        auth_type PASS
        auth_pass letmein
    }

    virtual_ipaddress {
        172.20.128.50    #虚拟路径
    }

    track_script {
        chk_nginx
    }
}

  keepalived-slave.conf

vrrp_script chk_nginx {
    script "pidof nginx"
    interval 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface etch0    #容器内部的网卡名称
    virtual_router_id 33
    priority 100    #优先级
    advert_int 1
    
    autheentication {
        auth_type PASS
        auth_pass letmein
    }

    virtual_ipaddress {
        172.20.128.50    #虚拟路径
    }

    track_script {
        chk_nginx
    }
}

  haproxy.cfg

global
    log 127.0.0.1 local0
    maxconn 4096
    daemon
    nbproc 4
    
defaults
    log 127.0.0.1 local3
    mode http
    option dontlognull
    option redispatch
    retries 2
    maxconn 2000
    balance roundrobin
    timeout connect 5000ms
    timeout client 5000ms
    timeout server 5000ms
    
frontend main
    bind *:6301
    default_backend webserver
    
backend webserveer
    server nginx_master 127.20.127.50:80 check inter 2000 rise 2 fall 5

  index-master.html

<h1>master!</h1>

  index-slave.html

<h1>slave!</h1>
最后修改:2021 年 10 月 06 日 10 : 48 PM
如果觉得我的文章对你有用,请随意赞赏