Nginx配置简单说明及负载均衡配置

220 阅读3分钟

1. nginx 基础配置

# 全局配置
worker_processes  4;  # 工作进程数,通常设置为 CPU 核心数

error_log  /var/log/nginx/error.log warn;  # 错误日志文件及级别
pid        /var/run/nginx.pid;  # 存放 Nginx 进程 ID 的文件路径


# 事件模块配置
events {
    worker_connections  1024;  # 单个工作进程允许的最大连接数
}


# HTTP 模块配置
http {
    include       /etc/nginx/mime.types;  # 包含 MIME 类型映射文件
    default_type  application/octet-stream;  # 默认的 MIME 类型

    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                     '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent"';  # 自定义日志格式

    access_log /var/log/nginx/access.log main;  # 访问日志文件及使用的格式

    sendfile on;  # 开启 sendfile 优化传输
    tcp_nopush on;  # 开启 TCP nopush(适当减少 TCP 包数量)
    tcp_nodelay on;  # 开启 TCP nodelay(降低延迟)

    keepalive_timeout  65;  # 设置 Keep-alive 超时时间

    gzip  on;  # 开启 GZIP 压缩
    gzip_min_length 1000;
    gzip_types text/plain application/json application/javascript text/css application/xml;

    include /etc/nginx/conf.d/*.conf;  # 包含其他的配置文件
    
    # 负载均衡配置
    upstream backend {
        server backend1.example.com;      # 后端服务器 1
        server backend2.example.com;      # 后端服务器 2

        # 轮询(round-robin)方式。请求会按顺序分发到后端服务器,支持权重。
        # server backend1.example.com weight=3;
        # server backend2.example.com weight=1;

        # IP 散列。根据客户端 IP 地址进行散列,相同 IP 的请求会发送到同一台后端服务器
        # ip_hash;
    }


    # 示例 server 配置块
    server {
        listen       80;  # 监听的端口
        server_name  example.com;  # 服务器名称

        location / {
            root   /usr/share/nginx/html;  # 网站根目录
            index  index.html index.htm;  # 默认首页文件名
        }

        location /api {
            rewrite ^/api(/.*)$ $1 break;  # 将 /api 替换成空

            proxy_pass http://backend;  # 代理到后端服务器
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        error_page 500 502 503 504  /50x.html;  # 错误页面映射
        location = /50x.html {
            root   /usr/share/nginx/html;
        }
    }
}


这个示例配置文件涵盖了一些基本的 Nginx 配置,包括工作进程数、错误日志、访问日志、连接数、GZIP 压缩等。在 server 配置块中,定义了一个简单的网站,处理 /api 前缀的请求,并将其代理到名为 backend 的上游服务器。

在这个配置文件中,我们添加了一个名为 backendupstream 配置,用于实现负载均衡。在这个示例中,我们有两个后端服务器(backend1.example.combackend2.example.com)。我们可以选择以下几种负载均衡策略:

  1. 轮询(round-robin) :默认的负载均衡策略,请求会按顺序分发到后端服务器。可以通过指定 weight 参数给每个服务器分配请求的权重。
  2. IP 散列(ip_hash) :根据客户端 IP 地址进行散列,使得来自相同 IP 的请求被发送到同一台后端服务器。将散列算法改为 ip_hash

要启用某种负载均衡策略,请取消对应策略的注释。在 location /api 中,我们已经将代理设置为 proxy_pass http://backend;,这样请求会被转发到负载均衡器上,在负载均衡器中配置的后端服务器之间进行分发。

2. 配置负载均衡使用

配置文件

注意如果要重写路径使用rewrite进行重写


worker_processes  1;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
    
    upstream backend {
    ip:hash;
    # upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。 weight=3
      server 127.0.0.1:8888 weight=1;
      server 127.0.0.1:9999 weight=2;
    }

    server {
        listen       80;
        server_name  yinuosnowball.top;

         location /api {
      
            # 使用 proxy_pass 代理请求到上游服务器 backend(负载均衡)
            proxy_pass http://backend;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        location /{
             root   html/dist;
             try_files $uri $uri/ /index.html;
		         index  index.html index.htm;
        }
        

        
        #location /welcome{
        #  proxy_pass http://localhost:50000/welcome;
        #}

       error_page   500 502 503 504 /50x.html;
        location = /50x.html {
            root   html;
        }
    }
     server {
       listen           443 ssl;
        server_name      localhost;
        ssl_certificate       www.hzsunrise.top_bundle.pem; 
        ssl_certificate_key   www.hzsunrise.top.key;
        location /{
            root   html/dist;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }
   }
    
}


使用express写两个node服务端

=========== 第一台 ============
const express = require('express')


const app = express()


app.get('/api/admin', (req, res) => {
	console.log('打印***8888',8888)
	res.json({
		code: 200,
		msg:'第一台服务器'
	})
})

app.listen(8888, () => {
	console.log('第一台服务器', 'http://localhost:8888');
})



const express = require('express')

=========== 第二台 ============
const app = express()


app.get('/api/admin', (req, res) => {
	console.log('打印***9999',9999)
	res.json({
		code: 200,
		msg:'第二台服务器'
	})
})

app.listen(9999, () => {
	console.log('第二台服务器', 'http://localhost:9999');
})


使用pm2 启动两个程序 pm2 start index.js index2.js

image.png

打开日志 pm2 logs

使用apifox 进行压测

image.png

结果如下:根据不同的权重进行分配访问次数

image.png