How to manage nginx template

I hava some config in nginx,but I don’t know how to manage these

first i use like

        template {
            data        = "{{ key \"slb/nginx/test.conf\" }}"
            destination = "local/conf.d/test.conf"
        }

but can’t discern

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


then i use like 

    template {
        data        = <<EOF
upstream backend
{
{{ range service "test" }}  server {{ .Address }}:{{ .Port }};
{{ else }}server 127.0.0.1:65535; # force a 502
{{ end }}
}
EOF
but this will cause the nomad file to be very long

I struggled with nginx templates as well. What I’m currently doing is starting with an nginx conf file that uses levant templating to add the dynamic configuration. The result of that is written into the docker image.

If you want the templating to occur inside the container then another approach is to use the gettext tool envsubst to write out the config file and then boot nginx.

1 Like

Hi @lialzm :wave:

There are a few ways that you can go about doing this.

@foozmeat gave a nice tip of using Levant to render your configuration file into your jobspec.

If you don’t want to use another tool, you can also use the HCL2 file function to load an external file into your jobspec at submission time. It would look like this:

# nginx.nomad
job "nginx" {
  datacenters = ["dc1"]

  group "nginx" {
    network {
      port "http" {
        to = 8080
      }
    }

    task "nginx" {
      driver = "docker"

      config {
        image = "nginx:1.21"
        ports = ["http"]
        volumes = [
          "local:/etc/nginx/conf.d",
        ]
      }

      template {
        data        = file("./app.conf")
        destination = "local/app.conf"
      }
    }
  }

  group "demo" {
    count = 3

    network {
      port "http" {}
    }

    service {
      name = "demo-webapp"
      port = "http"
    }

    task "server" {
      env {
        PORT    = "${NOMAD_PORT_http}"
        NODE_IP = "${NOMAD_IP_http}"
      }

      driver = "docker"

      config {
        image = "hashicorp/demo-webapp-lb-guide"
        ports = ["http"]
      }
    }
  }
}
# app.conf
upstream backend {
{{ range service "demo-webapp" }}
  server {{ .Address }}:{{ .Port }};
{{ else }}server 127.0.0.1:65535; # force a 502
{{ end }}
}

server {
   listen 8080;

   location / {
      proxy_pass http://backend;
   }
}

The important thing to keep in mind here, is that you will need to have both files when submitting the job. The Nomad CLI will render the app.conf file inside nginx.nomad and submit the resulting jobspec to the Nomad API.

1 Like