本篇博客记录了一种可能是最简单的使用nginx实现负载均衡的方式。

首先,安装nginx。不同的操作系统的安装方式不太一样,请参考 install nginx
<https://www.nginx.com/resources/wiki/start/topics/tutorials/install/>

然后,修改nginx的配置文件。如果是linux,配置文件位于/etc/nginx/nginx.conf。
user www-data; worker_processes auto; pid /run/nginx.pid; events {
worker_connections768; } http { ## # Basic Settings ## sendfile on; tcp_nopush
on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include
/etc/nginx/mime.types; default_type application/octet-stream;## # SSL Settings
## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_cipherson; ## # Logging Settings ## access_log /var
/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ##
gzipon; gzip_disable "msie6"; ## # Virtual Host Configs ## include
/etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; upstream myapp1 {
ip_hash; serverlocalhost:18080; server localhost:18081; server localhost:18082;
} server { listen8000; location / { proxy_pass http://myapp1; } } }
其中,我只加入了下面这几行
upstream myapp1 { ip_hash; server localhost:18080; server localhost:18081;
server localhost:18082; } server { listen 8000; location / { proxy_pass http:
//myapp1; } }
这几个概念我也不是很清楚,但工作原理是这样的:nginx监听本地的8000端口,并将请求转发到localhost:18080,localhost:18081和
localhost:18082
三个app中的一个,映射的策略是ip_hash,这个策略会对请求的ip进行hash运算并将结果映射到其中一个app,它能确保一个确定的请求ip会被映射到一个确定的服务,这样就连session的问题也不用考虑了。

配置完成后,你只需要在本地其三个服务,分别监听18080,18081和18082,然后打开浏览器访问localhost:8000,就会访问到你的其中一个服务。

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:637538335
关注微信