在http里面设置upstream组,其中包含三个服务器。在server的location块中的proxy_pass指令告诉Nginx将请求转发到这个组。
http {
upstream myapp {
server app1.example.com;
server app2.example.com;
server app3.example.com;
}
server {
listen 80;
server_name myapp.example.com;
location / {
proxy_pass http://myapp;
}
}
}
Nginx默认使用轮询算法来平均分配组中所有服务器的流量。
要调整流量的权重分配,可以在nginx配置文件的服务器块中使用“weight”参数。权重参数为每个服务器分配一个权重,权重较高的服务器将获得更大比例的流量.
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com weight=1;
server backend3.example.com weight=2;
}
在此示例中,backend1将收到比backend2多三倍的流量,backend3将收到比backend2多两倍的流量。
如果您想要添加备用机,可以在upstream块中添加多个server行,如下所示:
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com weight=1;
server backend3.example.com weight=2;
server backup1.example.com backup;
server backup2.example.com backup;
}
在此示例中,backup1和backup2是备用服务器,只有在所有其他服务器都不可用时才会接收流量。backup关键字指示Nginx将其视为备用服务器。
http {
upstream backend {
server backend1.example.com weight=3;
server backend2.example.com weight=1;
server backend3.example.com weight=2;
server backup1.example.com backup;
server backup2.example.com backup;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
#真实用户IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 健康检查
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_connect_timeout 2s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
# 会话保持
upstream ip_hash {
ip_hash;
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
# SSL / TLS
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
# 安全性
location /admin/ {
allow 192.168.1.0/24;
deny all;
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;
}
# 性能
worker_processes auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 100000;
worker_connections 1024;
keepalive_timeout 65;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
types_hash_max_size 2048;
server_tokens off;
client_max_body_size 100m;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
}
网友评论