1.虚拟机安装3个centos
2.三台服务器IP:
192.168.191.129(主)
192.168.191.130
192.168.191.131
3.分别在3台服务器的vhost目录下新建配置文件,我这里统一命名为load_balance.conf
主服务器配置如下:
upstream load_balance { # 设置负载均衡的机器列表(采用轮询的方式) server 192.168.191.130:80; server 192.168.191.131:80; } server { listen 80; server_name www.upstream.com upstream.com; location / { #设置反向代理 proxy_pass http://load_balance; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ { # 设置静态文件的反向代理 proxy_pass http://load_balance; expires 30d; } location ~ .*.(js|css)?$ { # 设置静态文件的反向代理 proxy_pass http://load_balance; expires 12h; } }
从服务器配置如下:
1 server { 2 listen 80; 3 server_name www.upstream.com upstream.com; 4 index index.html index.htm index.php; 5 root /home/wwwroot/load_balance; 6 7 location ~ .php$ { 8 include /usr/local/nginx/conf/fastcgi.conf; 9 fastcgi_pass unix:/tmp/php-cgi.sock; 10 fastcgi_param SCRIPT_FILENAME /home/wwwroot/load_balance$fastcgi_script_name; 11 } 12 13 location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ 14 { 15 expires 30d; 16 } 17 18 19 location ~ .*.(js|css)?$ 20 { 21 expires 12h; 22 } 23 }
重启nginx服务
service nginx restart
然后在 /home/wwwroot/load_balance 目录新建文件,输出不同的内容,测试
访问http://www.upstream.com/刷新页面,基本上是每刷新一次,更换一次,实现了负载均衡