nginx实现负载均衡

我们在做后端架构的时候,肯定会遇到很多有关负载均衡的问题。

下面我们就来探讨以下,nginx的负载均衡怎么去实现。

其实,在nginx中我们想要实现负载均衡是很简单的,只需要在nginx.conf中进行一些配置就行了。

首先我们来讲一下,关于nginx负载均衡的知识。

所谓,nginx反向代理负载均衡,简单点来说就是,我们的前端nginx反向代理http服务器,拿到请求后,将这些请求分发给我们的后端服务器。

这里我们想实现的小例子是:当我们我的前端nginx方向代理服务器拿到关于image的请求的时候,就将这些请求,分发给后端服务器。

(我们已经在nginx上安装了ecshop,这个例子,可以实现当访问ecshop页面的时候,将图片的请求,分发给其它的服务器。ecshop怎么安装,这里不做赘述,我前面的文章中有提到)

我们这样实现:当访问ecshop页面的时候(80端口),将图片的请求分发给81和82两个端口(我们在nginx中配置两个虚拟服务器分别监听81和82两个端口)

我们这样设置nginx.conf配置文件。

#gzip on;

http {
include mime.types;
default_type application/octet-stream;

#将log_format打开

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#设置upstream 这里我们起名文imgserver

upstream imgserver {
server 111.231.226.228:81 weight=1 max_fails=2 fail_timeout=3;
server 111.231.226.228:82 weight=1 max_fails=2 fail_timeout=3;
}

#设置两个虚拟服务器,分别监听81/82端口
server {
listen 81;
server_name localhost;
root html;

#设置虚拟服务器的访问日志
access_log logs/81-access.log main;
}
server {
listen 82;
server_name localhost;
root html;
access_log logs/82-access.log main;
}
server {
listen 80;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
index index.php index.html index.htm;
}

#当访问图片的时候,将请求分发给imgserver
location ~ .(jpg|png|gif|jpeg){

#设置xforwarded,以便后端服务器能够知道是哪一个客户端发来的请求。
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://imgserver;
}

nginx.conf设置好后,记得重启nginx:[root@VM_16_2_centos nginx]# ./sbin/nginx -s reload

访问ecshop。

然后,查看我们的81-access.log 和 82-access.log 

tail 81-access.log

tail 82-access.log

可以看到,都有信息,代表设置成功,81和82两台虚拟服务器都有被用到。

原文地址:https://www.cnblogs.com/573734817pc/p/10126709.html