单台服务器模拟负载均衡

找到nginx的配置文件nginx.conf,我的是在

 打开nginx.conf文件,include引入负载均衡配置的其它的要用的.conf文件

 

配置文件,8082.conf和8083.conf是两个nginx.conf配置文件,模拟两个服务器,8081.conf是实现负载均衡的一个文件,记得放开端口

 nginx文件,(8082.conf和8083.conf)

server {
//设置自己对应的端口号
listen       8082;
//指向自己的nginx.conf文件
root   /www/server/nginx/conf/nginx.conf;
//自己的ip地址
server_name  自己的ip地址;
#charset koi8-r;
#access_log  /var/log/nginx/log/host.access.log  main;
#
location / {
   index index.php index.html index.htm;
}
#error_page  404              /404.html;
#redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   /usr/share/nginx/html;
}
#pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ .php$ {
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
include        fastcgi_params;
}
}

负载均衡文件:(当有实际的服务器的时候 server直接引入实际的IP地址既可,那两个模拟的nginx配置文件也可不要)

#负载均衡配置1
upstream www.test1.com { 	#设置网络负载均衡,且取名为 www.test1.com (随便取)
	ip_hash;	#指定负载均衡算法,通过获取IP的hash值指定到对应的服务器

	server 172.16.15.76:8066 weight=10;	#第一台web服务器地址,权重为10 权重越大访问的几率越高

	server 172.16.25.76:8077 down;		#第二台 down表示负载过重或者不参与负载

	server 172.16.0.8:8066 max_fails=3 fail_timeout=30s; #max_fails失败超过指定次数会暂停或请求转往其它服务器  fail_timout 失败超过指定次数后暂停时间

	server 172.16.0.18:8077 backup;	#没有其它服务器时或down时才会请求backup服务器
}
#负载均衡配置2
upstream www.test2.com {
#这里没有指定负载均衡的算法,所以使用了默认的HTTP负载均衡算法 - 加权轮询。
	server 172.16.0.21:8066;
	server 192.168.76.98:8066; 
}

#服务器配置1
server {
	listen 80;
	server_name www.test1.com; 

	location /{
#将server节点下的location节点中的proxy_pass配置为:http:// + upstream名称,即
		proxy_pass http://www.test1.com;    #使用哪个代理配置 这里指定使用名为 www.test1.com 的负载均衡配置

    #proxy_set_header 可设置请求头-并将头信息传递到服务器端,如果不设置,服务器接收到的将是负载均衡服务器的信息
		proxy_set_header Host $host;	#设置主机头

		proxy_set_header X-Real-IP $remote_addr; #将客户端真实地址转发给服务器,以便服务器获取客户端真实IP

		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #多重代理的话,获取并设置原始客户端的IP
} 
} 
#服务器配置2
server {
	listen 80;
	server_name www.test2.com; 

	location /{
		proxy_pass http://www.test2.com;	#指定代理的后端服务器地址和端口,这里指定使用名为 www.test2.com 的负载均衡配置
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
	}
}

配置完成后重启Nginx服务,在sbin目录下 执行:

 ./nginx -s reload

猜你喜欢

转载自blog.csdn.net/weixin_45604963/article/details/119893753