27 June 2018

NGINX include statement

Este post es solo para demostrar la potencia de la sentencia include en NGINX. Con esta instruccion podremos evitar crear configuraciones gigantescas en un solo fichero de texto, pudiendo distribuir dichas configuraciones en ficheros especializados.

En el siguiente ejemplo vamos a iniciar un microservicio en el puerto 9090, posteriormente vamos a dar acceso a este servicio por el puerto 80 a travez de diferentes "context path" (/camel1 y /camel2) distribuidos en diferentes ficheros.

Iniciamos un servicio de prueba en el puerto 9090 ( para mas info visite helloworld-camel-spring-boot)
$ docker run -d -p 9090:8080 helloworld-camel-spring-boot:0.0.2 
Registramos la configuracion principal en NGINX importando los ficheros *.location (mappings) por cada "context path" al cual vamos a dar servicio.

camel.conf file
upstream camelcluster {
  keepalive 32; # keepalive connections
  server localhost:9090; #camel miroservice ip and port
}

server { # simple load balancing
    listen          80;
    server_name     localhost;
    access_log      /var/log/nginx/camel.server.access.log;
    error_log       /var/log/nginx/camel.server.error.log;

    include /etc/nginx/conf.d/*.location;
}
Primer mapping (camel1.location file)
location /camel1 {
      sendfile off;

      proxy_set_header   Host              $host;
      proxy_set_header   X-Real-IP         $remote_addr;
      proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Proto $scheme;
      proxy_set_header   Connection        ""; # Clear for keepalive

      proxy_connect_timeout      90;
      proxy_send_timeout         90;
      proxy_read_timeout         90;
      proxy_buffering            off;
      
      proxy_http_version 1.1;
      proxy_pass         http://camelcluster/camel/say/helloObject/ExampleNumberOne;
      
}
Segundo mapping (camel2.location file)
location /camel2 {
      sendfile off;

      proxy_set_header   Host              $host;
      proxy_set_header   X-Real-IP         $remote_addr;
      proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Proto $scheme;
      proxy_set_header   Connection        ""; # Clear for keepalive

      proxy_connect_timeout      90;
      proxy_send_timeout         90;
      proxy_read_timeout         90;
      proxy_buffering            off;
      
      proxy_http_version 1.1;
      proxy_pass         http://camelcluster/camel/say/helloObject/ExampleNumber2;
      
}
Reiniciamos NGINX.
$ sudo systemctl restart nginx
Comprobaremos que los mappings funcionan ejecutando curl commands como los siguientes:
$ curl http://localhost/camel1
{"text":"Hello ExampleNumberOne, I'm SpringCamelContext(camel-1) with spring id application!"}

$ curl http://localhost/camel2
{"text":"Hello ExampleNumber2, I'm SpringCamelContext(camel-1) with spring id application!"}

- Enjoy it -

No comments: