etcd + confd 實(shí)現(xiàn) nginx upstream 自動注冊

confd是一個輕量級的配置管理工具,源碼地址:https://github.com/kelseyhightower/confd,它可以將配置信息存儲在etcd、consul、dynamodb、redis以及zookeeper等。confd定期會從這些存儲節(jié)點(diǎn)pull最新的配置,然后重新加載服務(wù),完成配置文件的更新。

一、confd 安裝配置

  1. 安裝
mkdir -p /root/go/src/github.com/kelseyhightower
git clone https://github.com/kelseyhightower/confd.git /root/go/src/github.com/kelseyhightower/confd
cd /root/go/src/github.com/kelseyhightower/confd
make
mv bin/confd /usr/local/bin
  1. confd 語法配置


    目錄結(jié)構(gòu)如下,confd 默認(rèn)配置文件目錄為 /etc/confd
  • 配置文件
# cat conf.d/www.imlcs.com.toml

[template]
src = "www.imlcs.com.tmpl"
dest = "/etc/nginx/conf.d/www.imlcs.com.conf"
keys = [
    "/nginx/www",
    "/domain/www",
]
check_cmd = "nginx -t"
reload_cmd = "nginx -s reload"
  • 參數(shù)說明:

src:模板文件名
dest:生成目標(biāo)文件的文件名及位置
keys:監(jiān)控的keys,是一個數(shù)組,用到哪個key加入里面就行
check_cmd:檢查命令,可以不用加
relaod_cmd:重新加載進(jìn)程的命令

  • 模板文件
# cat templates/www.imlcs.com.tmpl
upstream {{"/domain/www"}} { # 獲取單個 key 的值
    {{range getvs "/nginx/www/*"}} # 循環(huán)獲取當(dāng)前目錄下的所有 key 的值
    server {{.}}; 
    {{end}}
}
server {
    listen 80;
    server_name {{getv "/domain/www"}};
    proxy_pass http://www;
}

二、測試

  • confd 啟動命令
confd --watch -backend etcd -node http://127.0.0.1:2379
  • 向 etcd 中寫入數(shù)據(jù)
etcdctl  set /nginx/www/node1 192.168.1.11:80
etcdctl  set /nginx/www/node2 192.168.1.12:80
etcdctl  set /nginx/www/node3 192.168.1.13:80
etcdctl  set /domain/www www.imlcs.com
  • 生成文件的內(nèi)容
# cat /etc/nginx/conf.d/www.imlcs.com.conf
upstream /domain/www {

    server 192.168.1.11:80;

    server 192.168.1.12:80;

    server 192.168.1.13:80;

}
server {
    listen 80;
    server_name www.imlcs.com;
    proxy_pass http://www;
}
  • supvervisor 管理 confd 進(jìn)程
# cat /etc/supervisord.d/confd.conf
[program:confd]
command=/usr/local/bin/confd --watch -backend etcd -node http://127.0.0.1:2379
autostart=true
startsecs=5
autorestart=true
startretries=3
user=root
redirect_stderr = true
stdout_logfile_maxbytes=20MB
stdout_logfile_backups=20
stopasgroup=true
killasgroup=true
exitcodes=0,2
stopsignal=KILL
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容