Consul templates, ports and consul connect

Say I have the following nginx config:

{{ range service "my-service" }}
  server {{ .Address }}:{{ .Port }};
{{ else }}server 127.0.0.1:65535; # force a 502
{{ end }}

Port seems to return whatever port is registered for the service with Consul - but what if I want to connect to the port associated with the Consul Connect sidecar? In some cases, that is the only port associated with the service, and Port in those contexts returns 0.

Hi @nateberkopec :wave:

With Consul Connect you don’t need to query the service information, since all the connectivity that you need is managed by the sidecar proxy. So you can use the NOMAD_UPSTREAM_*_<service> environment variables, since the sidecar and your main task live in the same allocation.

So your template could just look like this:

server {{ env "NOMAD_UPSTREAM_ADDR_count_api" }}

Thanks @lgfa29 - that is indeed exactly what I ended up doing.

However, the answer to my (wrong) question turned out to be:

{{ range connect "my-service" }}
  server {{ .Address }}:{{ .Port }};
{{ else }}server 127.0.0.1:65535; # force a 502
{{ end }}

… but as you said, I actually want to connect to the local sidecar proxy, not directly to the sidecar on the service.

3 Likes

TIL about connect in Consul Templates :grinning_face_with_smiling_eyes:

Thanks for posting this follow-up!

1 Like

TIL learnt about else condition to range construct! :raised_hands:

1 Like