背景
手写Nginx的upsteam麻烦并且容易出错,想通过类似Kong的Restfull的api形式操作upsteam节点。
架构图
- etcd:分布式KV存储系统,一般用于共享配置和服务注册与发现。是CoreOS公司发起的一个开源项目。 ETCD存储格式类似于文件系统,以根"/"开始下面一级级目录,最后一个是Key,一个key对应一个Value。
- etcd集群:使用Raft协议保证每个节点数据一致,由多个节点对外提供服务。这里只用单台。
- confd:管理本地应用配置文件,使用etcd或consul存储的数据渲染模板,还支持redis、zookeeper等。
confd有一个watch功能,通过HTTP API定期监测对应的etcd中目录变化,获取最新的Value,然后渲染模板,更新配置文件。
实践
安装完confd和etcd之后,做如下操作:
创建配置目录
# mkdir -p /etc/confd/{conf.d,templates}
conf.d # 资源模板,下面文件必须以toml后缀
templates # 配置文件模板,下面文件必须以tmpl后缀
创建资源模板
# vi /etc/confd/conf.d/app01.conf.toml
[template]
src = "app01.conf.tmpl" # 默认在/etc/confd/templates目录下
dest = "/usr/local/nginx/conf/vhost/app01.conf" # 要更新的配置文件
keys = [
"/nginx", # 监测的key
]
reload_cmd ="/usr/local/nginx/sbin/nginx -s reload" # 最后执行的命令
创建Nginx配置文件模板
# vi /etc/confd/templates/app01.conf.tmpl
upstream www.{{getv "/nginx/www/server_name"}} {
{{range getvs "/nginx/www/upstream/*"}}
server ``.``;
`end`
}
server {
server_name www.{{getv "/nginx/www/server_name"}};
location / {
proxy_pass http://www.{{getv "/nginx/www/server_name"}};
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
测试
向etcd添加k/v:
# etcdctl -C http://192.168.1.99:2379 set domain.com
domain.com
# etcdctl -C http://192.168.1.99:2379 set /nginx/www/upstream/server01 "192.168.1.10:80"
192.168.1.10:80
# etcdctl -C http://192.168.1.99:2379 set /nginx/www/upstream/server02 "192.168.1.11:80"
192.168.1.11:80
启动 confd 监测 etcd 中的keys:
当你启动后,confd就会从etcd获取key的值并填充到Nginx配置文件模板,并更新到 /usr/local/nginx/conf/vhost/app01.conf,并nginx reload。
Etcd的Rest API操作
curl -X PUT http://192.168.1.99:2379/v2/keys/test/a_key -d value="789" # 增改key
curl -X DELETE http://192.168.1.99:2379/v2/keys/test/a_key # 删除key
curl http://192.168.1.99:2379/v2/keys/test/a_key # 查询key的值
curl -X PUT http://192.168.1.99:2379/v2/keys/dir -d dir=true # 创建目录
curl http://192.168.1.99:2379/v2/keys # 查看所有keys
curl -X PUT http://192.168.1.99:2379/v2/keys/ttlvar -d value="ttl_value" -d ttl=10 # 创建过期时间的key,单位秒
curl http://192.168.1.99:2379/version # 查看etcd版本
curl http://192.168.1.99:2379/v2/members # 列出所有集群成员
curl http://192.168.1.99:2379/v2/stats/leader # 查看leader
curl http://192.168.1.99:2379/v2/stats/self # 节点自身信息
curl http://192.168.1.99:2379/v2/stats/store # 查看集群运行状态