說明
生產(chǎn)環(huán)境中平時會對NGINX配置文件做修改垄惧,添加或刪除后端主機菜秦。如果只有一兩臺手動修改很輕松挽牢,如果有幾十臺摆舟,一臺臺修改是一個很麻煩的事情。也許有人會說可以用ansible或salt之類的管理噪服,當(dāng)然這樣可以實現(xiàn),而且這類工具也是做這些事情的胜茧。但是如果想集成到運維平臺粘优,只用這些還不足夠。下面就可以通過etcd(單機)和confd來實現(xiàn)nginx的配置管理
安裝
- etcd
yum install etcd
- confd
confd只是一個二進制文件呻顽,下載下來即可
wget https://github.com/kelseyhightower/confd/releases/download/v0.16.0/confd-0.16.0-linux-amd64
mv confd-0.16.0-linux-amd64 /usr/bin/confd
chmod +x /usr/bin/confd
配置
- confd配置
-
創(chuàng)建confd配置目錄
mkdir /etc/confd/{conf.d, templates}
- conf.d: 資源模板文件雹顺,必須以toml為后綴
- templates: 配置文件模板,必須以tmpl為后綴
-
創(chuàng)建資源模板文件
# vi /etc/confd/conf.d/app01.conf.toml [template] src = "app01.conf.tmpl" dest = "/etc/nginx/conf.d/app01.conf" keys = [ "/nginx/app01" ] check_cmd = "/usr/sbin/nginx -t" reload_cmd = "/usr/sbin/nginx -s reload"
- src: nginx配置文件模板
- dest: 生成的nginx配置文件廊遍,如果在運維平臺在嬉愧,這里可以指定一個臨時路徑,然后通過運維平臺分發(fā)到所有nginx節(jié)點
- check_cmd: 檢測nginx配置文件命令
- creload_cmd: 重新加載配置文件命令
-
創(chuàng)建nginx配置文件模板
# vim /etc/confd/templates/app01.conf.tmpl upstream www_{{ getv "/nginx/app01/server_name" }} { {{ range getvs "/nginx/app01/upstream/*" }} server {{.}}; {{end}} } server { server_name {{getv "/nginx/app01/server_name"}}; listen 80; location / { proxy_pass http://www_{{ getv "/nginx/app01/server_name" }}; } }
- getv: confd從etcd中獲取key對應(yīng)的value
- range getvs:從etcd中獲取某個目錄下所有key對應(yīng)的value喉前,然后遍歷
- {{ . }}: 占位符没酣,range中遍歷的值
- 配置etcd
-
根據(jù)confd中nginx的模板文件在etcd中生成對應(yīng)的key value
etcdctl set /nginx/app01/server_name www.app01.com etcdctl set /nginx/app01/upstream/server1 192.168.100.10 etcdctl set /nginx/app01/upstream/server2 192.168.100.11
-
查看etcd中的結(jié)構(gòu)
# etcdctl ls /nginx/app01 /nginx/app01/upstream /nginx/app01/server_name # etcdctl get /nginx/app01/server_name www.app01.com # etcdctl ls /nginx/app01/upstream /nginx/app01/upstream/server2 /nginx/app01/upstream/server1
- 啟動etcd和confd
service etcd start
confd -watch -backend etcd -node http://127.0.0.1:2379
服務(wù)啟動后查看生成的配置文件:
upstream www_www.app01.com {
server 192.168.100.10;
server 192.168.100.11;
}
server {
server_name www.app01.com;
listen 80;
location / {
proxy_pass http://www_www.app01.com;
}
}
擴展思路(運維平臺結(jié)合)
- 如果有多個配置文件管理,可以在web界面編輯卵迂,然后保存文件到confd的模板目錄
- 操作etcd鍵值裕便,可以通過etcd api操作,并將值保存到數(shù)據(jù)庫见咒,以供回滾
- 生成的配置文件保存到臨時目錄(生產(chǎn)環(huán)境運維平臺肯定和nginx服務(wù)器是分開的)偿衰,然后通過ansible或salt調(diào)用服務(wù)器列表分發(fā)到有nginx標(biāo)簽的服務(wù)器