nginx 大家如果没用过那或多或少都应该听过, vue 的部署, 反向代理, 负载均衡 nginx 都能帮你做到.
今天主要说一下 nginx 负载均衡我们的项目, 如下图所示, 请求到达 nginx,nginx 再帮我们转发.
首先使用 Docker 安装 nginx.
docker pull nginx:latest
运行容器, 将本地的 8080 端口映射到容器内部的 80 端口.
docker run --name nginx -p 8080:80 -d nginx
查看 nginx 容器, 如果有错请看日志.
浏览器中访问一下
ok, 到此我们的 nginx 就已安装完成.
我们准备好 3 个以上的 webapi 的项目并发布.
进入 nginx 容器
Docker exec -it nginx bash
找到 nginx.conf 文件并作修改, nginx.conf 分为 http 块, events 块和 server 块, 此次主要在 server 块中做更改.
此时在 nginx 容器里面使用 vi 或者 VIM 没有用, 需要依次执行如下两条命令
- apt-get update
- apt-get install VIM
进入文件内, 末尾处指向了另一个文件, 没错这个文件里就是放 server 块配置内容
进入 etc/nginx/conf.d/default.conf 文件中并做修改
- upstream ServiceInstance{ #nginx 默认轮询下面的服务实例
- server ***.**.***.***:9007;
- server ***.**.***.***:9008;
- server ***.**.***.***:9009;
- }
- server {
- listen 80;
- server_name localhost;
- #charset koi8-r;
- #access_log /var/log/nginx/host.access.log main;
- location / {
- #root /usr/share/nginx/html;
- #index index.HTML index.htm; #请求到达后会进行转发
- proxy_pass http://ServiceInstance;
- }
- #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;
- }
- # proxy the PHP scripts to Apache listening on 127.0.0.1:80
- #
- #location ~ \.PHP$ {
- # proxy_pass http://127.0.0.1;
- #}
- # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
- #
- #location ~ \.PHP$ {
- # root HTML;
- # fastcgi_pass 127.0.0.1:9000;
- # fastcgi_index index.PHP;
- # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
- # include fastcgi_params;
- #}
- # deny access to .htaccess files, if Apache's document root
- # concurs with nginx's one
- #
- #location ~ /\.ht {
- # deny all;
- #}
- }
完成之后重启一下容器, 如果有错误请查看日志.
docker restart nginx
浏览器中调用一个接口查看
每一次都会轮询不同的服务实例, 负载均衡的预期就实现了!
我们也可以设置权重比例, weight 值越大, 请求到达此实例的次数就越多!
- upstream ServiceInstance{
- #nginx 默认轮询下面的服务实例
- server ***.**.***.***:9007 weight=1;
- server ***.**.***.***:9008 weight=2;
- server ***.**.***.***:9009 weight=3;
- }
各位同学也可慢慢研究, nginx 很强大的!
总结
来源: https://www.jb51.net/article/191121.htm