【问题标题】:Consul Template - "If Service Exists" condition?领事模板 - “如果服务存在”条件?
【发布时间】:2021-03-21 04:29:59
【问题描述】:

我刚刚继承了一个 Nginx 代理/应用服务器设置,它使用 Consul 和 Consul Template 进行服务发现和注册。 Nginx 代理有一个配置文件,其中包含这样的条目来注册下游应用服务器:

<snip>

upstream appservers {
  {{ range service "my-app-servers" }}
     server {{ .Address }}.{{ .Port }};
  {{ end }}
}

<snip>

我在后台运行consul-template 以捕获对my-app-servers 的任何更新,适当地更新nginx.conf 文件,然后重新加载nginx 配置。这一切都很好,我们能够根据需要从组合中添加和删除应用程序服务器。也就是说,如果我们有 no 个应用服务器可用的情况,我们最终会得到一个空的 upstream 块,这会导致 nginx 重新加载失败。

有没有办法在 consul-template 中有 "if service my-app-servers exists, then...""if not, then..." 逻辑?我希望能够让我的nginx.conf 文件有一个配置用于上游服务器存在的场景,以及另一个在上游服务器不存在时显示错误页面的应急设置。我仍然在加快 consul-template 的速度,还没有看到任何显示这种逻辑语法的示例。有什么帮助吗?

【问题讨论】:

    标签: nginx nginx-reverse-proxy consul consul-template


    【解决方案1】:

    您可以通过将service 查找的结果存储在变量中来实现此目的,然后使用仅在变量不为空时输出上游块的条件。

    {{- $upstream_services := service "my-app-servers" -}}
    {{- if $upstream_services -}}
    upstream appservers {
      {{- range $upstream_services }}
         server {{ .Address }}.{{ .Port }};
      {{- end }}
    }
    {{- end }}
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-22
      • 2016-11-29
      • 2019-08-23
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2023-04-05
      • 2020-02-05
      相关资源
      最近更新 更多