下载

1
2
3
4
curl -Ls -o confd https://github.com/kelseyhightower/confd/releases/download/v0.16.0/confd-0.16.0-linux-amd64
chmod +x confd
sudo mv confd /usr/local/bin
/usr/local/bin/confd -version

部署

consul

1
2
3
4
5
6
7
8
9
# 集群
# 注册数据
#etcdctl --endpoints=$endpoints put /services/web/cust1/2 '{"IP": "10.0.0.2"}'
#etcdctl --endpoints=$endpoints put /services/web/cust2/2 '{"IP": "10.0.0.4"}'
#etcdctl --endpoints=$endpoints put /services/web/cust2/1 '{"IP": "10.0.0.3"}'
#etcdctl --endpoints=$endpoints put /services/web/cust1/1 '{"IP": "10.0.0.1"}'
curl --request PUT --data '{"Address": "192.168.33.101","Port": 9999 }' http://127.0.0.1:8500/v1/kv/nginx/upstream1/backend1
curl --request PUT --data '{"Address": "192.168.33.102","Port": 9999 }' http://127.0.0.1:8500/v1/kv/nginx/upstream1/backend2
curl --request PUT --data '{"Address": "192.168.33.103","Port": 9999 }' http://127.0.0.1:8500/v1/kv/nginx/upstream1/backend3

confd

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
sudo mkdir -p /etc/confd/conf.d/
sudo mkdir -p /etc/confd/templates/
confd -onetime -backend consul -node 127.0.0.1:8500 -log-level=DEBUG
#/usr/local/bin/confd -interval 5 -node '192.168.2.202:2379' -confdir /etc/confd &

sudo bash -c "cat > /etc/confd/conf.d/yourapp-nginx.toml" <<EOF
[template]
prefix = "/nginx"
src = "nginx.conf.template"
dest = "/tmp/yourapp.conf"
owner = "nginx"
mode = "0644"
keys = [
  "/upstream1",
]
check_cmd = "ls -l {{.src}}"
reload_cmd = "cat /tmp/yourapp.conf"
EOF

sudo bash -c "cat > /etc/confd/templates/nginx.conf.template" <<EOF
upstream backend{
    {{range gets "/upstream1/*"}}server {{\$data := json .Value}}{{\$data.Address}}:{{\$data.Port}} max_fails=3 fail_timeout=20 weight=1;
    {{else}}server 127.0.0.1:65535; # force a 502{{end}}
}
server {
    listen 80 default_server;
    server_name app.example.com;
    set \$upstream_endpoint http://backend;
    location / {
        proxy_pass \$upstream_endpoint;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
    }
}
EOF

# 查看生成
# cat /tmp/yourapp.conf
upstream backend{
    server 192.168.33.101:9999 max_fails=3 fail_timeout=20 weight=1;
    server 192.168.33.102:9999 max_fails=3 fail_timeout=20 weight=1;
    server 192.168.33.103:9999 max_fails=3 fail_timeout=20 weight=1;
    
}
server {
    listen 80 default_server;
    server_name app.example.com;
    set $upstream_endpoint http://backend;
    location / {
        proxy_pass $upstream_endpoint;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

systemd

参考