Nginx全场景配置指南:从基础部署到高可用架构

一、环境准备与编译安装

1.1 系统环境初始化

在Ubuntu/Debian系统上执行基础环境配置,建议使用root用户操作:

  1. # 更新软件包索引并安装编译工具链
  2. apt update && apt install -y \
  3. build-essential \
  4. libpcre3 libpcre3-dev \
  5. zlib1g zlib1g-dev \
  6. libssl-dev \
  7. curl wget git

关键组件说明:

  • pcre:正则表达式支持库
  • zlib:Gzip压缩功能依赖
  • openssl:HTTPS加密传输必需

1.2 源码编译安装流程

创建专用安装脚本(install_nginx.sh)实现自动化部署:

  1. #!/bin/bash
  2. # 创建专用用户组
  3. groupadd -r nginx && useradd -r -g nginx -s /sbin/nologin nginx
  4. # 下载源码包(建议从官网获取最新稳定版)
  5. cd /tmp
  6. wget http://nginx.org/download/nginx-1.24.0.tar.gz
  7. tar zxvf nginx-*.tar.gz
  8. cd nginx-*
  9. # 关键编译参数配置
  10. ./configure \
  11. --prefix=/usr/local/nginx \
  12. --user=nginx \
  13. --group=nginx \
  14. --with-http_ssl_module \ # HTTPS支持
  15. --with-http_v2_module \ # HTTP/2协议
  16. --with-http_realip_module \ # 真实IP获取
  17. --with-http_stub_status_module \ # 状态监控
  18. --with-http_gzip_static_module \ # 静态压缩
  19. --with-pcre \ # 正则支持
  20. --with-stream # 四层代理支持
  21. make && make install

1.3 systemd服务管理

创建服务管理文件实现开机自启:

  1. [Unit]
  2. Description=High performance web server
  3. After=network.target
  4. [Service]
  5. Type=forking
  6. PIDFile=/usr/local/nginx/logs/nginx.pid
  7. ExecStartPre=/usr/local/nginx/sbin/nginx -t
  8. ExecStart=/usr/local/nginx/sbin/nginx
  9. ExecReload=/usr/local/nginx/sbin/nginx -s reload
  10. ExecStop=/usr/local/nginx/sbin/nginx -s quit
  11. PrivateTmp=true
  12. [Install]
  13. WantedBy=multi-user.target

服务管理命令:

  1. systemctl daemon-reload
  2. systemctl enable nginx
  3. systemctl start nginx

二、静态网站服务配置

2.1 目录结构规划

遵循FHS标准创建目录结构:

  1. mkdir -p /var/www/static-site/{html,logs,conf}
  2. chown -R nginx:nginx /var/www/static-site
  3. chmod -R 750 /var/www/static-site

目录功能说明:

  • html/:存放静态资源文件
  • logs/:访问日志和错误日志
  • conf/:站点专属配置(可选)

2.2 基础配置示例

主配置文件(/usr/local/nginx/conf/nginx.conf)关键片段:

  1. http {
  2. include mime.types;
  3. default_type application/octet-stream;
  4. # 日志格式定义
  5. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  6. '$status $body_bytes_sent "$http_referer" '
  7. '"$http_user_agent" "$http_x_forwarded_for"';
  8. server {
  9. listen 80;
  10. server_name example.com;
  11. access_log /var/www/static-site/logs/access.log main;
  12. error_log /var/www/static-site/logs/error.log warn;
  13. root /var/www/static-site/html;
  14. index index.html index.htm;
  15. location / {
  16. try_files $uri $uri/ =404;
  17. expires 30d; # 静态资源缓存
  18. add_header Cache-Control "public";
  19. }
  20. }
  21. }

2.3 性能优化建议

  1. Gzip压缩

    1. gzip on;
    2. gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    3. gzip_min_length 1k;
    4. gzip_comp_level 6;
  2. 静态资源缓存

    1. location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    2. expires 1y;
    3. access_log off;
    4. add_header Cache-Control "public, immutable";
    5. }

三、负载均衡实战配置

3.1 基础架构设计

典型三层架构:

  1. 客户端 负载均衡层 应用服务层 数据存储层

3.2 upstream配置示例

  1. upstream backend_pool {
  2. # 权重轮询(默认)
  3. server 192.168.1.101:8080 weight=5;
  4. server 192.168.1.102:8080 weight=3;
  5. # IP Hash算法(会话保持)
  6. # ip_hash;
  7. # 最少连接数算法
  8. # least_conn;
  9. # 健康检查参数
  10. keepalive 32;
  11. }

3.3 负载均衡策略对比

策略类型 配置指令 适用场景
轮询 默认 后端服务器性能相近
权重轮询 weight=N 服务器性能不均衡
IP Hash ip_hash 需要会话保持的场景
最少连接数 least_conn 长连接较多的应用
最短响应时间 fair(需模块) 动态内容服务

3.4 完整代理配置

  1. server {
  2. listen 80;
  3. server_name api.example.com;
  4. location / {
  5. proxy_pass http://backend_pool;
  6. proxy_set_header Host $host;
  7. proxy_set_header X-Real-IP $remote_addr;
  8. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  9. # 连接超时设置
  10. proxy_connect_timeout 60s;
  11. proxy_read_timeout 300s;
  12. proxy_send_timeout 300s;
  13. # 缓冲区设置
  14. proxy_buffer_size 4k;
  15. proxy_buffers 8 16k;
  16. proxy_busy_buffers_size 32k;
  17. }
  18. }

四、高可用集群部署

4.1 Keepalived配置

主节点配置示例:

  1. vrrp_script chk_nginx {
  2. script "/usr/local/bin/check_nginx.sh"
  3. interval 2
  4. weight -20
  5. }
  6. vrrp_instance VI_1 {
  7. state MASTER
  8. interface eth0
  9. virtual_router_id 51
  10. priority 100
  11. advert_int 1
  12. authentication {
  13. auth_type PASS
  14. auth_pass 1111
  15. }
  16. virtual_ipaddress {
  17. 192.168.1.200/24
  18. }
  19. track_script {
  20. chk_nginx
  21. }
  22. }

4.2 健康检查脚本

  1. #!/bin/bash
  2. # check_nginx.sh
  3. if [ -f /var/run/nginx.pid ]; then
  4. if kill -0 $(cat /var/run/nginx.pid); then
  5. exit 0
  6. else
  7. exit 1
  8. fi
  9. else
  10. exit 1
  11. fi

4.3 故障转移流程

  1. 主节点故障检测
  2. VIP资源接管
  3. 备用节点启动Nginx
  4. 发送告警通知

五、监控与维护

5.1 状态监控接口

  1. server {
  2. listen 8080;
  3. server_name localhost;
  4. location /nginx_status {
  5. stub_status on;
  6. allow 127.0.0.1;
  7. deny all;
  8. }
  9. }

状态指标说明:

  • Active connections:当前活动连接数
  • accepts:已接受的连接数
  • handled:已处理的连接数
  • requests:总请求数
  • Reading/Writing/Waiting:连接状态分布

5.2 日志分析方案

推荐使用ELK技术栈:

  1. Filebeat收集日志
  2. Logstash处理过滤
  3. Elasticsearch存储索引
  4. Kibana可视化分析

5.3 定期维护任务

  1. # 每日日志切割
  2. 0 0 * * * /usr/local/nginx/sbin/nginx -s reopen
  3. # 每周配置检查
  4. 0 3 * * 0 /usr/local/nginx/sbin/nginx -t && echo "Config test passed" || alert
  5. # 每月性能优化
  6. 0 2 1 * * sync && echo 3 > /proc/sys/vm/drop_caches

本文通过系统化的配置讲解和实战案例,完整呈现了Nginx从基础部署到高可用集群的全链路技术方案。建议读者结合实际业务场景进行参数调优,定期关注官方安全公告及时升级版本。对于大规模部署场景,可考虑结合容器编排技术实现更灵活的资源管理。