一、环境准备与编译安装
1.1 系统环境初始化
在Ubuntu/Debian系统上执行基础环境配置,建议使用root用户操作:
# 更新软件包索引并安装编译工具链apt update && apt install -y \build-essential \libpcre3 libpcre3-dev \zlib1g zlib1g-dev \libssl-dev \curl wget git
关键组件说明:
pcre:正则表达式支持库zlib:Gzip压缩功能依赖openssl:HTTPS加密传输必需
1.2 源码编译安装流程
创建专用安装脚本(install_nginx.sh)实现自动化部署:
#!/bin/bash# 创建专用用户组groupadd -r nginx && useradd -r -g nginx -s /sbin/nologin nginx# 下载源码包(建议从官网获取最新稳定版)cd /tmpwget http://nginx.org/download/nginx-1.24.0.tar.gztar zxvf nginx-*.tar.gzcd nginx-*# 关键编译参数配置./configure \--prefix=/usr/local/nginx \--user=nginx \--group=nginx \--with-http_ssl_module \ # HTTPS支持--with-http_v2_module \ # HTTP/2协议--with-http_realip_module \ # 真实IP获取--with-http_stub_status_module \ # 状态监控--with-http_gzip_static_module \ # 静态压缩--with-pcre \ # 正则支持--with-stream # 四层代理支持make && make install
1.3 systemd服务管理
创建服务管理文件实现开机自启:
[Unit]Description=High performance web serverAfter=network.target[Service]Type=forkingPIDFile=/usr/local/nginx/logs/nginx.pidExecStartPre=/usr/local/nginx/sbin/nginx -tExecStart=/usr/local/nginx/sbin/nginxExecReload=/usr/local/nginx/sbin/nginx -s reloadExecStop=/usr/local/nginx/sbin/nginx -s quitPrivateTmp=true[Install]WantedBy=multi-user.target
服务管理命令:
systemctl daemon-reloadsystemctl enable nginxsystemctl start nginx
二、静态网站服务配置
2.1 目录结构规划
遵循FHS标准创建目录结构:
mkdir -p /var/www/static-site/{html,logs,conf}chown -R nginx:nginx /var/www/static-sitechmod -R 750 /var/www/static-site
目录功能说明:
html/:存放静态资源文件logs/:访问日志和错误日志conf/:站点专属配置(可选)
2.2 基础配置示例
主配置文件(/usr/local/nginx/conf/nginx.conf)关键片段:
http {include mime.types;default_type application/octet-stream;# 日志格式定义log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';server {listen 80;server_name example.com;access_log /var/www/static-site/logs/access.log main;error_log /var/www/static-site/logs/error.log warn;root /var/www/static-site/html;index index.html index.htm;location / {try_files $uri $uri/ =404;expires 30d; # 静态资源缓存add_header Cache-Control "public";}}}
2.3 性能优化建议
-
Gzip压缩:
gzip on;gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;gzip_min_length 1k;gzip_comp_level 6;
-
静态资源缓存:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {expires 1y;access_log off;add_header Cache-Control "public, immutable";}
三、负载均衡实战配置
3.1 基础架构设计
典型三层架构:
客户端 → 负载均衡层 → 应用服务层 → 数据存储层
3.2 upstream配置示例
upstream backend_pool {# 权重轮询(默认)server 192.168.1.101:8080 weight=5;server 192.168.1.102:8080 weight=3;# IP Hash算法(会话保持)# ip_hash;# 最少连接数算法# least_conn;# 健康检查参数keepalive 32;}
3.3 负载均衡策略对比
| 策略类型 | 配置指令 | 适用场景 |
|---|---|---|
| 轮询 | 默认 | 后端服务器性能相近 |
| 权重轮询 | weight=N |
服务器性能不均衡 |
| IP Hash | ip_hash |
需要会话保持的场景 |
| 最少连接数 | least_conn |
长连接较多的应用 |
| 最短响应时间 | fair(需模块) |
动态内容服务 |
3.4 完整代理配置
server {listen 80;server_name api.example.com;location / {proxy_pass http://backend_pool;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;# 连接超时设置proxy_connect_timeout 60s;proxy_read_timeout 300s;proxy_send_timeout 300s;# 缓冲区设置proxy_buffer_size 4k;proxy_buffers 8 16k;proxy_busy_buffers_size 32k;}}
四、高可用集群部署
4.1 Keepalived配置
主节点配置示例:
vrrp_script chk_nginx {script "/usr/local/bin/check_nginx.sh"interval 2weight -20}vrrp_instance VI_1 {state MASTERinterface eth0virtual_router_id 51priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}virtual_ipaddress {192.168.1.200/24}track_script {chk_nginx}}
4.2 健康检查脚本
#!/bin/bash# check_nginx.shif [ -f /var/run/nginx.pid ]; thenif kill -0 $(cat /var/run/nginx.pid); thenexit 0elseexit 1fielseexit 1fi
4.3 故障转移流程
- 主节点故障检测
- VIP资源接管
- 备用节点启动Nginx
- 发送告警通知
五、监控与维护
5.1 状态监控接口
server {listen 8080;server_name localhost;location /nginx_status {stub_status on;allow 127.0.0.1;deny all;}}
状态指标说明:
- Active connections:当前活动连接数
- accepts:已接受的连接数
- handled:已处理的连接数
- requests:总请求数
- Reading/Writing/Waiting:连接状态分布
5.2 日志分析方案
推荐使用ELK技术栈:
- Filebeat收集日志
- Logstash处理过滤
- Elasticsearch存储索引
- Kibana可视化分析
5.3 定期维护任务
# 每日日志切割0 0 * * * /usr/local/nginx/sbin/nginx -s reopen# 每周配置检查0 3 * * 0 /usr/local/nginx/sbin/nginx -t && echo "Config test passed" || alert# 每月性能优化0 2 1 * * sync && echo 3 > /proc/sys/vm/drop_caches
本文通过系统化的配置讲解和实战案例,完整呈现了Nginx从基础部署到高可用集群的全链路技术方案。建议读者结合实际业务场景进行参数调优,定期关注官方安全公告及时升级版本。对于大规模部署场景,可考虑结合容器编排技术实现更灵活的资源管理。