一、环境准备与依赖安装
1. 关闭防火墙和SELinux(仅限测试环境)
systemctl stop firewalld # 停止防火墙 systemctl disable firewalld # 禁用防火墙开机启动 setenforce 0 # 临时关闭SELinux
2. 安装编译依赖
yum -y install gcc pcre-devel zlib-devel
3. 下载并解压Nginx源码
wget https://nginx.org/download/nginx-1.27.5.tar.gz tar -zxvf nginx-1.27.5.tar.gz cd nginx-1.27.5/
二、编译安装Nginx
1. 配置编译选项
./configure --prefix=/usr/local/nginx
2. 编译并安装
make -j4 # 使用4核并行编译加速 make install
三、Nginx服务管理
1. 创建systemd服务文件
vim /etc/systemd/system/nginx.service
2. 添加以下内容:
[Unit] Description=nginx server After=network.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/usr/local/nginx/sbin/nginx -s reload ExecStop=/usr/local/nginx/sbin/nginx -s quit PrivateTmp=true [Install] WantedBy=multi-user.target
3. 重新加载systemd配置
systemctl daemon-reload
4. 常用命令
命令 | 描述 |
---|---|
systemctl start nginx |
启动Nginx服务 |
systemctl stop nginx |
停止Nginx服务 |
systemctl restart nginx |
重启Nginx服务 |
systemctl status nginx |
查看服务状态 |
nginx -s reload |
重载配置文件 |
nginx -t |
测试配置文件语法 |
四、验证安装与端口检查
1. 验证端口监听
# 方法1:使用netstat netstat -ntlp | grep nginx # 方法2:使用lsof lsof -i :80 # 方法3:使用ss ss -tunlp | grep :80
2. 访问测试
浏览器访问服务器IP地址,应看到Nginx欢迎页面
五、负载均衡配置实战
1. 配置上游服务器组
编辑Nginx配置文件:
vim /usr/local/nginx/conf/nginx.conf
2. 在http块中添加负载均衡配置
upstream tomcatCluster { server localhost:8080 weight=2; # 权重2 server localhost:8081 weight=2; # 权重2 server localhost:8082 weight=6; # 权重6 }
3. 配置反向代理规则
server { listen 80; server_name localhost; # 静态资源服务 location / { root /usr/local/nginx/html/; index index.html index.htm; } # API请求代理 location ~^/api/ { rewrite ^/api/(.*)$ /$1 break; # URL重写 proxy_pass http://tomcatCluster; # 转发到服务器组 proxy_redirect default; # 可选:添加代理头信息 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }
4. 重启Nginx使配置生效
systemctl restart nginx
六、后端服务器准备(Tomcat示例)
1. 创建多个Tomcat实例
cd /usr/local/tomcat cp -r t1 t2 # 复制实例 cp -r t1 t3 # 复制实例
2. 修改各实例端口
# 编辑server.xml修改以下端口 vim t1/conf/server.xml # 修改8005, 8080, 8009 vim t2/conf/server.xml # 修改8006, 8081, 8010 vim t3/conf/server.xml # 修改8007, 8082, 8011
3. 创建区分页面
# 在t1实例中: echo '<h1 style="color:red">T1 Instance</h1>' > t1/webapps/ROOT/index.jsp # 在t2实例中: echo '<h1 style="color:blue">T2 Instance</h1>' > t2/webapps/ROOT/index.jsp # 在t3实例中: echo '<h1 style="color:green">T3 Instance</h1>' > t3/webapps/ROOT/index.jsp
七、验证负载均衡效果
启动所有Tomcat实例
访问
http://your-server-ip/api/
多次刷新页面,观察不同Tomcat实例的响应
查看响应头中的
X-Backend-Server
确认请求分发情况
性能优化建议
# 在http块中添加以下优化参数 http { # 连接优化 keepalive_timeout 65; keepalive_requests 1000; # 缓冲优化 client_body_buffer_size 10K; client_header_buffer_size 1k; client_max_body_size 8m; large_client_header_buffers 4 4k; # 超时设置 client_body_timeout 12; client_header_timeout 12; send_timeout 10; # 开启Gzip压缩 gzip on; gzip_types text/plain text/css application/json; }
生产环境注意事项:
保持防火墙开启状态,仅开放必要端口
配置SELinux策略而非完全禁用
定期更新Nginx版本修复安全漏洞
使用非root用户运行Nginx进程