配置流程
具体就是官网下载后配置config文件,非常简单,大多教程都有,不做过多赘述
这里主要描述一下配置时如何看反馈
首先就是如何确定nginx启动了
访问nginx的基础配置,localhost:80,如果出现图2界面,就说明nginx已经启动了
然后就可以配置自己的负载均衡
upstream backend {
server 127.0.0.1:8081;
server 127.0.0.1:8082;
# 可以添加更多的后端服务器
# server 127.0.0.1:8083;
# ...
}
server {
listen 8080;
location / {
proxy_pass http://backend; # 使用后端服务器池
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 负载均衡算法,默认为轮询,也可以使用其他算法如ip_hash、least_conn等
# 比如:least_conn;
}
}
讲解一下含义,upstream backend这里是设置参数backend,在后面的location中的proxy_pass中会使用到,每个server就是一个服务,listen就是监听哪个端口,location后面跟的就是跳转前置,也就是你在浏览器访问的网址。
例如想要通过访问index直接访问到"localhost:8081/login/hello",就在location后面设置"/index",里面的proxy_pass后面设置"http://backend/login/hello",这样访问"localhost:8080/index",nginx就会自动把服务转发到后端的"localhost:8080/index"
弄清楚这个原理在调试的时候就会很方便了
说的有什么不对的地方欢迎指正
12.26更新:
bug反馈
upstream backend {
server 127.0.0.1:8081 weight=2;
server 127.0.0.1:8082 weight=1;
}
在Nginx配置文件中,对于upstream
块中的配置,通常是不允许有空格的。
所以当这里选择使用权重时,切记“weight=1”之间不能有空格,如上图所示,如果有空格的话,将会报下面的错