ETCD + CONFD + NGINX的配置

上一篇文章我们介绍了 ETCD 的容器化,搞这件事情的主要目的其实是要动态更新 Nginx 的配置

这一章我们就来配置 confd 和 Nginx,来达到动态更新 Nginx 配置的目的

一、安装配置confd

下载并安装:

1wget https://github.com/kelseyhightower/confd/releases/download/v0.16.0/confd-0.16.0-linux-amd64
2mv confd-0.16.0-linux-amd64 /usr/sbin/confd
3chmod +x /usr/sbin/confd

生成配置文件:

我们在 etcd 中存放的格式如下

1etcdctl set /nginx/app01/subdomain app1
2etcdctl set /nginx/app01/upstream/app01_1 "192.168.0.1:5601"
3
4/nginx/app01/subdomain "app01"
5/nginx/app01/upstream/app01_1 "192.168.0.1:5601"
6/nginx/app01/upstream/app01_2 "192.168.0.2:5601"

那么,我们先生成 confd 的配置文件:

 1mkdir -p /etc/confd/{conf.d,templates}
 2
 3cat <<EOF>>/etc/confd/conf.d/nginx.toml
 4[template]
 5src = "nginx.conf.tmpl"
 6dest = "/etc/nginx/conf.d/nginx-auto.conf"
 7keys = [
 8  "/nginx/app01/subdomain",
 9  "/nginx/app01/upstream",
10]
11check_cmd = "/usr/sbin/nginx -t"
12reload_cmd = "/usr/sbin/nginx -s reload"
13EOF
14
15cat <<EOT>>/etc/confd/templates/nginx.conf.tmpl
16upstream {{getv "/nginx/app01/subdomain"}} {
17{{range getvs "/nginx/app01/upstream/*"}}
18    server {{.}};
19{{end}}
20}
21
22server {
23    server_name  {{getv "/nginx/app01/subdomain"}}.example.com;
24    location / {
25        proxy_pass        http://{{getv "/nginx/app01/subdomain"}};
26        proxy_redirect    off;
27        proxy_set_header  Host             $host;
28        proxy_set_header  X-Real-IP        $remote_addr;
29        proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
30   }
31}
32EOT
33

confd 会根据 etcd 的值,结合 nginx.conf.tmpl ,生成 nginx-auto.conf,然后 nginx -t 验证通过后,执行 nginx -s rolad。

注意:nginx的配置中必须有 include /etc/nginx/conf.d/*.conf;

二、运行confd

1# 只处理一次
2confd -onetime -backend etcd -node http://etcd-svc.default:2379
3
4# 按时间轮询
5confd -interval=60 -backend etcd -node http://etcd-svc.default:2379 &   
6

这样就可以动态更新 Nginx 了。


Etcd单节点应用
PyPXE-一个牛逼的一站式PXE安装包