1. 项目概述:Nginx全栈部署的双系统实战场景
在当今的Web服务架构中,Nginx作为高性能的反向代理和Web服务器,已成为运维工程师和开发者的标配工具。而Rocky Linux与Ubuntu作为企业级和开发者友好的Linux发行版代表,各自拥有独特的优势。这次我们将通过双系统环境,完整演示Nginx从安装到配置的全流程实战。
选择Rocky Linux 10和Ubuntu 24.04这对组合有其特殊考量:Rocky Linux作为RHEL的替代品,继承了其稳定性和企业级特性,适合生产环境;而Ubuntu则以丰富的软件包和开发者生态见长,是快速原型开发的理想选择。通过这两种系统的对比实践,读者可以掌握不同Linux生态下的Nginx部署技巧。
提示:双系统部署并非简单的重复操作,不同发行版的软件管理工具(yum/dnf vs apt)、服务管理方式(systemd vs upstart)、默认配置路径等差异,都会影响最终的Nginx部署效果。
2. 环境准备与系统安装要点
2.1 硬件需求与分区方案
对于实验环境,建议至少满足以下配置:
- CPU:4核及以上(Nginx的worker进程数与CPU核心数相关)
- 内存:8GB(运行多个虚拟机或容器时需要更多)
- 存储:100GB SSD(系统分区+交换空间+数据存储)
双系统分区方案示例(UEFI模式):
/boot/efi 500MB EFI系统分区 /boot 1GB 引导分区 swap 4GB 交换空间(内存≤8GB时建议为内存的1.5倍) / 50GB 根分区(Rocky Linux) / 50GB 根分区(Ubuntu) /home 剩余空间 共享数据分区2.2 系统安装关键步骤
Rocky Linux 10安装注意事项:
- 安装介质选择:推荐使用Minimal ISO减少不必要的软件包
- 软件选择:务必勾选"Standard"或"Server with GUI"(如需图形界面)
- 网络配置:建议静态IP,便于后续Nginx测试
- 防火墙设置:安装时暂时关闭firewalld,后续再配置
Ubuntu 24.04特有配置:
- 安装类型选择"Normal installation"即可
- 更新选项:建议勾选"Install third-party software"
- 磁盘分区:使用LVM便于后期扩容
- 用户创建:避免使用root直接登录,配置sudo权限
3. 双系统下的Nginx安装与配置差异
3.1 软件源配置与安装命令对比
在Rocky Linux 10中:
# 添加EPEL仓库 sudo dnf install epel-release -y # 安装Nginx sudo dnf install nginx -y # 启动服务 sudo systemctl enable --now nginx在Ubuntu 24.04中:
# 更新软件包索引 sudo apt update # 安装Nginx sudo apt install nginx -y # 启动服务 sudo systemctl enable --now nginx注意:Ubuntu默认源中的Nginx版本可能较旧,如需最新版可添加官方仓库:
sudo add-apt-repository ppa:nginx/stable sudo apt update3.2 关键配置文件路径差异
| 文件/目录 | Rocky Linux 10 路径 | Ubuntu 24.04 路径 |
|---|---|---|
| 主配置文件 | /etc/nginx/nginx.conf | /etc/nginx/nginx.conf |
| 默认站点配置 | /etc/nginx/conf.d/default.conf | /etc/nginx/sites-enabled/default |
| 日志文件 | /var/log/nginx/ | /var/log/nginx/ |
| 默认网站根目录 | /usr/share/nginx/html | /var/www/html |
4. Nginx核心配置实战
4.1 基础性能调优参数
编辑/etc/nginx/nginx.conf中的events和http块:
user nginx; worker_processes auto; # 自动匹配CPU核心数 events { worker_connections 1024; # 每个worker进程处理连接数 multi_accept on; # 同时接受多个新连接 use epoll; # 事件驱动模型(Linux特有) } http { sendfile on; # 零拷贝传输 tcp_nopush on; # 优化数据包发送 tcp_nodelay on; # 禁用Nagle算法 keepalive_timeout 65; # 长连接超时 types_hash_max_size 2048; # 类型哈希表大小 # 包含MIME类型定义 include /etc/nginx/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"'; access_log /var/log/nginx/access.log main; error_log /var/log/nginx/error.log warn; # 包含其他配置 include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; }4.2 虚拟主机配置示例
在Rocky Linux中创建/etc/nginx/conf.d/example.com.conf:
server { listen 80; server_name example.com www.example.com; root /var/www/example.com/html; index index.html index.htm; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php8.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } # 静态资源缓存 location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { expires 30d; add_header Cache-Control "public, no-transform"; } }在Ubuntu中创建/etc/nginx/sites-available/example.com:
server { listen 80; server_name example.com www.example.com; root /var/www/example.com/html; index index.html index.htm; location / { try_files $uri $uri/ =404; } # 启用Gzip压缩 gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; # 错误页面定制 error_page 404 /404.html; error_page 500 502 503 504 /50x.html; }启用Ubuntu站点配置:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ sudo nginx -t # 测试配置 sudo systemctl reload nginx5. 安全加固与性能优化
5.1 基础安全配置
- 禁用server tokens(隐藏Nginx版本信息):
server_tokens off;- 限制HTTP方法:
location / { limit_except GET POST HEAD { deny all; } }- 防止点击劫持:
add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; add_header X-XSS-Protection "1; mode=block";- SSL配置(使用Let's Encrypt证书):
# 在Rocky Linux中: sudo dnf install certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com # 在Ubuntu中: sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d example.com -d www.example.com5.2 性能优化技巧
- 调整worker进程数:
worker_processes auto; # 通常设置为CPU核心数 worker_rlimit_nofile 65535; # 每个worker能打开的文件描述符数量- 连接优化:
events { worker_connections 4096; accept_mutex on; accept_mutex_delay 100ms; }- 缓冲区优化:
client_body_buffer_size 16K; client_header_buffer_size 1k; client_max_body_size 8m; large_client_header_buffers 4 8k;- 启用HTTP/2:
listen 443 ssl http2;6. 常见问题排查与解决方案
6.1 启动问题排查
- 端口冲突(80/443被占用):
sudo netstat -tulnp | grep ':80\|:443' sudo kill <PID> # 终止占用进程- 配置文件语法错误:
sudo nginx -t # 测试配置 journalctl -xe --no-pager -u nginx # 查看详细日志- SELinux相关问题(Rocky Linux特有):
# 查看SELinux拒绝日志 sudo ausearch -m avc -ts recent # 临时解决方案 sudo setenforce 0 # 永久解决方案 sudo semanage fcontext -a -t httpd_sys_content_t "/var/www(/.*)?" sudo restorecon -Rv /var/www6.2 性能问题诊断
- 查看Nginx状态:
sudo systemctl status nginx sudo ps aux | grep nginx- 监控连接数:
netstat -an | grep :80 | wc -l ss -ant | grep ESTAB | wc -l- 压力测试工具(ab):
ab -n 1000 -c 100 http://example.com/- 慢请求分析:
# 在配置中添加 log_format timed_combined '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time $pipe';7. 双系统间的配置迁移与同步
7.1 配置文件的兼容性处理
由于Rocky Linux和Ubuntu的Nginx默认配置存在差异,迁移时需要注意:
- 路径转换:
# Rocky Linux → Ubuntu sed -i 's|/usr/share/nginx/html|/var/www/html|g' nginx.conf sed -i 's|/etc/nginx/conf.d/|/etc/nginx/sites-enabled/|g' nginx.conf # Ubuntu → Rocky Linux sed -i 's|/var/www/html|/usr/share/nginx/html|g' nginx.conf sed -i 's|/etc/nginx/sites-enabled/|/etc/nginx/conf.d/|g' nginx.conf- 服务管理命令统一化:
# 使用systemctl统一管理 sudo systemctl start|stop|restart|reload|status nginx7.2 使用Git进行配置版本控制
- 初始化配置仓库:
sudo mkdir /etc/nginx/git sudo chown -R $USER:$USER /etc/nginx/git cd /etc/nginx/git git init- 创建.gitignore:
*.swp *.bak sites-enabled/* !sites-enabled/default- 添加配置并提交:
cp /etc/nginx/nginx.conf . cp -r /etc/nginx/conf.d/ . # Rocky Linux # 或 cp -r /etc/nginx/sites-available/ . # Ubuntu git add . git commit -m "Initial Nginx config"8. 高级应用场景扩展
8.1 负载均衡配置
upstream backend { least_conn; # 最少连接算法 server 192.168.1.10:8080 weight=3; server 192.168.1.11:8080; server 192.168.1.12:8080 backup; } server { location / { proxy_pass http://backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }8.2 缓存加速配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off; server { location / { proxy_cache my_cache; proxy_cache_valid 200 304 12h; proxy_cache_valid any 10m; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; add_header X-Proxy-Cache $upstream_cache_status; } }8.3 日志分析与监控
- 使用GoAccess实时分析:
sudo apt install goaccess # Ubuntu sudo dnf install goaccess # Rocky Linux goaccess /var/log/nginx/access.log --log-format=COMBINED --real-time-html --port=7890- 配置Prometheus监控:
location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; }- Grafana仪表板导入ID:12708(Nginx官方仪表板)
9. 系统特定优化技巧
9.1 Rocky Linux特有优化
- 调整文件描述符限制:
echo "nginx soft nofile 65535" | sudo tee -a /etc/security/limits.conf echo "nginx hard nofile 65535" | sudo tee -a /etc/security/limits.conf- 内核参数优化:
# /etc/sysctl.conf net.core.somaxconn = 65535 net.ipv4.tcp_max_syn_backlog = 65535 net.ipv4.tcp_tw_reuse = 19.2 Ubuntu特有优化
- 使用PPOLL事件驱动:
events { use ppoll; }- 调整swappiness:
echo "vm.swappiness = 10" | sudo tee -a /etc/sysctl.conf sudo sysctl -p- 启用TCP BBR拥塞控制:
echo "net.core.default_qdisc=fq" | sudo tee -a /etc/sysctl.conf echo "net.ipv4.tcp_congestion_control=bbr" | sudo tee -a /etc/sysctl.conf sudo sysctl -p10. 容器化部署方案
10.1 Docker Compose部署
创建docker-compose.yml:
version: '3' services: nginx: image: nginx:latest container_name: nginx ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./conf.d:/etc/nginx/conf.d - ./logs:/var/log/nginx - ./html:/usr/share/nginx/html restart: unless-stopped networks: - frontend networks: frontend: driver: bridge10.2 Kubernetes部署示例
创建nginx-deployment.yaml:
apiVersion: apps/v1 kind: Deployment metadata: name: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:latest ports: - containerPort: 80 volumeMounts: - name: nginx-config mountPath: /etc/nginx/nginx.conf subPath: nginx.conf volumes: - name: nginx-config configMap: name: nginx-config --- apiVersion: v1 kind: Service metadata: name: nginx spec: selector: app: nginx ports: - protocol: TCP port: 80 targetPort: 80 type: LoadBalancer创建ConfigMap:
kubectl create configmap nginx-config --from-file=nginx.conf