http { upstream my_upstream { server tomcat1.example.com; server tomcat2.example.com; } server { listen 80; location / { proxy_set_header Host $host; proxy_pass http://my_upstream; } } }NGINX 还可以针对 TCP 应用程序(如 MySQL)和 UDP 应用程序,如 DNS 和 RADIUS 进行负载均衡,对于 TCP 应用程序,配置模板:
stream { upstream my_upstream { server server1.example.com:1234; server server2.example.com:2345; } server { listen 1123 [udp]; proxy_pass my_upstream; } }目前 Nginx 支持几种负载均衡策略,为 HTTP、TCP 和 UDP 提供多种负载均衡方式,所有这些方式都能够选择分配到每个上游服务器的流量的权重:
upstream tomcat_group { server 192.168.1.16:8080 down; server 192.168.1.18:8080 weight=2; server 192.168.1.13:8080; server 192.168.1.12:8080 backup; }down: 表示当前的 Web Server 暂时不参与负载。
backup: 其它所有的非 Backup Server Down 或者忙的时候,请求 Backup 机器,所以这台机器压力会最轻。
nginx user nginx; pid /run/nginx.pid; worker_processes auto; worker_rlimit_nofile 100000; events { worker_connections 2048; multi_accept on; } http { sendfile on; access_log off; error_log /data/log/nginx-1.8/error.log error; # 缓存数据目录,Ngnix 不会主动创建需要手动创建 proxy_cache_path /data/nginx-1.8/cache levels=1:2 keys_zone=cache_zone:10m inactive=60m; server { listen 80; server_name localhost; root /usr/local/services/nginx-1.8/html/; location / { } # 堆代码 duidaima.com # 缓存配置 location ~.*\.(gif|jpg|png|css|js)(.*) { # 设置是否开启对后端响应的缓存,如果开启的话,参数值就是zone的名称 proxy_cache cache_zone; # 响应状态码为200 302时,10分钟有效 proxy_cache_valid 200 302 10m; # 缓存过期时间 expires 1d; add_header X-Proxy-Cache $upstream_cache_status; } } }
sudo firewall-cmd --zone=public --permanent --add-service=http另外大部分情况 Linux 服务器从配置完成到服务运行都会产生关机状况,如果有特殊情况关机了,就需要手动启动这些 Nginx 服务,这里可以将 Nginx 设置为开机自启服务:
# 设置开机自启 sudo systemctl enable nginx # 关闭开机自启 sudo systemctl disable nginx