使用到的模块: https://github.com/weibocom/nginx-upsync-module

通过第三方注册中心(Etcd/Consul),NGINX/OpenResty从第三方拿后端信息,实现同步。该模块在修改后端注册中心时,无需重载(reload)NGINX/OpenResty

实践

1. 准备Consul

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
consul:
  image: consul
  container_name: nginx-consul
  net: host
  restart: always
  volumes:
    - ./data:/consul/data
  command:
    consul agent
           -server
           -ui
           -client=IP.Address
           -bind=IP.Address
           -advertise=IP.Address
           -data-dir=/consul/data
1
2
# 启动Consule
docker-compose up -d

2. NGINX/OpenResty

  1. 安装

    因为该模块不是标准模块,需要将相关产品的源码下载下来,通过--add-module重新编译,将模块整合进去,此处略…

  2. 配置

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    ...
    upstream test {
      upsync IP:PORT/v1/kv/upstreams/UPSTREAM_NAME/ upsync_timeout=10s upsync_interval=5000ms upsync_type=consul strong_dependency=off;
      upsync_dump_path servers_test.conf;
      include servers_test.conf;
      server 127.0.0.1:8090 backup;
    }
    ...
    # 查看当前后端的主机
    location = /upstream-show {
        allow IP.Address;
        deny all;
        upstream_show;
    }
    ...
    

    有一个小Bug,第一次启动时,要往servers_test.conf文件里面写入至少一台后端,不然会因为upstream内没有可用的server而导致主进程无法启动。

    1
    2
    
    # serers_test.conf
    server 127.0.0.1:9099;
    
  3. 注册后端服务

    1
    2
    
    # 格式
    curl -XPUT IP:PORT/v1/kv/upstreams/UPSTREAM_NAME/SERVER_ADDR:PORT
    
  4. 启动即可。通过ConsulAddress:8500管理地址可以删除KEY观察后端效果