systemctl stop firewalld # 停止防火墙 systemctl disable firewalld # 禁用防火墙开机启动 setenforce 0 # 临时关闭SELinux
yum -y install gcc pcre-devel zlib-devel
wget https://nginx.org/download/nginx-1.27.5.tar.gz tar -zxvf nginx-1.27.5.tar.gz cd nginx-1.27.5/
./configure --prefix=/usr/local/nginx
make -j4 # 使用4核并行编译加速 make install
vim /etc/systemd/system/nginx.service
[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
systemctl daemon-reload
命令 | 描述 |
---|---|
systemctl start nginx |
启动Nginx服务 |
systemctl stop nginx |
停止Nginx服务 |
systemctl restart nginx |
重启Nginx服务 |
systemctl status nginx |
查看服务状态 |
nginx -s reload |
重载配置文件 |
nginx -t |
测试配置文件语法 |
# 方法1:使用netstat netstat -ntlp | grep nginx # 方法2:使用lsof lsof -i :80 # 方法3:使用ss ss -tunlp | grep :80
浏览器访问服务器IP地址,应看到Nginx欢迎页面
编辑Nginx配置文件:
vim /usr/local/nginx/conf/nginx.conf
upstream tomcatCluster { server localhost:8080 weight=2; # 权重2 server localhost:8081 weight=2; # 权重2 server localhost:8082 weight=6; # 权重6 }
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; } }
systemctl restart nginx
cd /usr/local/tomcat cp -r t1 t2 # 复制实例 cp -r t1 t3 # 复制实例
# 编辑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
# 在t1实例中: echo 'T1 Instance
' > t1/webapps/ROOT/index.jsp # 在t2实例中: echo 'T2 Instance
' > t2/webapps/ROOT/index.jsp # 在t3实例中: echo 'T3 Instance
' > 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进程