Templated Nginx configuration with Bash and Docker

Shoutout to @shakefu for his Nginx and Bash wizardry in figuring a lot of this stuff out.  I’d like to take credit for this, but he’s the one who got a lot of it working originally.

Sometimes it can be useful to template Nginx files to use environment variables to fine tune and adjust control for various aspects of Nginx.  A recent example of this idea that I recently worked on was a scenario where I setup an Nginx proxy with a very bare bones configuration.  As part of the project, I wanted a quick and easy way to update some of the major Nginx configurations like the port it uses to listen for traffic, the server name, upstream servers, etc.

It turns out that there is a quick and dirty way to template basic Nginx configurations using Bash, which ended up being really useful so I thought I would share it.  There are a few caveats to this method but it is definitely worth the effort if you have a simple setup or a setup that requires some changes periodically.  I stuck the configuration into a Dockerfile so that it can be easily be updated and ported around – by using the nginx:alpine image as the base image the total size all said and done is around 16MB.  If you’re not interested in the Docker bits, feel free to skip them.

The first part of using this method is to create a simple configuration file that will be used to substitute in some environment variables.  Here is a simple template that is useful for changing a few Nginx settings.  I called it nginx.tmpl, which will be important for how the template gets rendered later.

events {}

http {
  error_log stderr;
  access_log /dev/stdout;

  upstream upstream_servers {
    server ${UPSTREAM};
  }

  server {
    listen ${LISTEN_PORT};
    server_name ${SERVER_NAME};
    resolver ${RESOLVER};
    set ${ESC}upstream ${UPSTREAM};

    # Allow injecting extra configuration into the server block
    ${SERVER_EXTRA_CONF}

    location / {
       proxy_pass ${ESC}upstream;
    }
  }
}

The configuration is mostly straight forward.  We are basically just using this configuration file and inserting a few templated variables denoted by the ${VARIABLE} syntax, which are just environment variables that get inserted into the configuration when it gets bootstrapped.  There are a few “tricks” that you may need to use if your configuration starts to get more complicated.  The first is the use of the ${ESC} variable.  Nginx uses the ‘$’ for its variables, which also is used by the template.  The extra ${ESC} basically just gives us a way to escape that $ so that we can use Nginx variables as well as templated variables.

The other interesting thing that we discovered (props to shakefu for this magic) was that you can basically jam arbitrary server block level configurations into an environment variable.  We do this with the ${SERVER_EXTRA_CONF} in the above configuration and I will show an example of how to use that environment variable later.

Next, I created a simple Dockerfile that provides some default values for some of the various templated variables.  The Dockerfile aslso copies the templated configuration into the image, and does some Bash magic for rendering the template.

FROM nginx:alpine

ENV LISTEN_PORT=8080 \
  SERVER_NAME=_ \
  RESOLVER=8.8.8.8 \
  UPSTREAM=icanhazip.com:80 \
  UPSTREAM_PROTO=http \
  ESC='$'

COPY nginx.tmpl /etc/nginx/nginx.tmpl

CMD /bin/sh -c "envsubst < /etc/nginx/nginx.tmpl > /etc/nginx/nginx.conf && nginx -g 'daemon off;' || cat /etc/nginx/nginx.conf"

There are some things to note.  First, not all of the variables in the template need to be declared in the Dockerfile, which means that if the variable isn’t set it will be blank in the rendered template and just won’t do anything.  There are some variables that need defaults, so if you ever run across that scenario you can just add them to the Dockerfile and rebuild.

The other interesting thing is how the template gets rendered.  There is a tool built into the shell called envsubst that substitutes the values of environment variables into files.  In the Dockerfile, this tool gets executed as part of the default command, taking the template as the input and creating the final configuration.

/bin/sh -c "envsubst < /etc/nginx/nginx.tmpl > /etc/nginx/nginx.conf

Nginx gets started in a slightly silly way so that daemon mode can be disabled (we want Nginx running in the foreground) and if that fails, the rendered template gets read to help look for errors in the rendered configuration.

&& nginx -g 'daemon off;' || cat /etc/nginx/nginx.conf"

To quickly test the configuration, you can create a simple docker-compose.yml file with a few of the desired environment variables, like I have below.

version: '3'
services:
  nginx_proxy:
    build:
      context: .
      dockerfile: Dockerfile
    # Only test the configuration
    #command: /bin/sh -c "envsubst < /etc/nginx/nginx.tmpl > /etc/nginx/nginx.conf && cat /etc/nginx/nginx.conf"
    volumes:
      - "./nginx.tmpl:/etc/nginx/nginx.tmpl"
    ports:
      - 80:80
    environment:
    - SERVER_NAME=_
    - LISTEN_PORT=80
    - UPSTREAM=test1.com
    - UPSTREAM_PROTO=https
    # Override the resolver
    - RESOLVER=4.2.2.2
    # The following would add an escape if it isn't in the Dockerfile
    # - ESC=$$

Then you can bring up Nginx server.

docker-compose up

The configuration doesn’t get rendered until the container is run, so to test the configuration only, you could add in a command in the docker-compose file that renders the configuration and then another command that spits out the rendered configuration to make sure it looks right.

If you are interested in adding additional configuration you can use the ${SERVER_EXTRA_CONF} as eluded to above.  An example of this extra configuration can be assigned to the environment variable.  Below is an arbitrary snippet that allows for connections to do long polling to Nginx, which basically means that Nginx will try to hold the connection open for existing connections for longer.

error_page 420 = @longpoll;
if ($arg_wait = "true") { return 420; }
}
location @longpoll {
# Proxy requests to upstream
proxy_pass $upstream;
# Allow long lived connections
proxy_buffering off;
proxy_read_timeout 900s;
keepalive_timeout 160s;
keepalive_requests 100000;

The above snipped would be a perfectly valid environment variable as far as the container is concerned, it will just look a little bit weird to the eye.

nginx proxy environment variables

That’s all I’ve got for now.  This minimal templated Nginx configuration is handy for testing out simple web servers, especially for proxies and is also nice to port around using Docker.

Read More

Sperimenta il Meglio con l’App UnionsBet e il Casinò

Benvenuti nel mondo di UnionsBet, la piattaforma che sta rivoluzionando il modo in cui ci avviciniamo ai giochi online e alle scommesse. Con l’introduzione dell’app UnionsBet, gli utenti ora possono godere di un’esperienza di gioco senza interruzioni ovunque si trovino.

Perché Scegliere l’UnionsBet App?

Grazie all’app UnionsBet, gli utenti hanno accesso a una vasta gamma di funzionalità che migliorano il loro interesse verso le scommesse. Dall’analisi delle quote alla creazione di scommesse personalizzate, l’app offre tutto ciò di cui hai bisogno per avere successo. Inoltre, l’app è compatibile con la maggior parte dei dispositivi mobili, rendendola accessibile a tutti.

UnionsBet App

Scopri il Fascino del Casinò UnionsBet

Oltre alle scommesse, UnionsBet offre un’esperienza di casinò online eccezionale. Con una varietà di giochi disponibili, dagli slot ai tavoli da poker, c’è qualcosa per ogni appassionato di casinò. Il UnionsBet casinò è progettato per offrire non solo grandi opportunità di vincita ma anche un intrattenimento di alta qualità.

Funzionalità Avanzate e Sicurezza

UnionsBet pone un forte accento sulla sicurezza e sulla protezione dei dati dei suoi utenti. Utilizzando tecnologie all’avanguardia, garantisce che tutte le transazioni e i dati personali siano mantenuti al sicuro. Inoltre, offre supporto clienti 24/7 per risolvere qualsiasi problema possa sorgere durante l’utilizzo.

Unisci alla Rivoluzione del Gioco con UnionsBet

Non perdere l’opportunità di esplorare l’universo dei giochi e delle scommesse con UnionsBet. Che tu sia interessato a scommettere sui tuoi sport preferiti o a provare la fortuna al casinò, tutto è disponibile a portata di mano. Scarica oggi stesso l’app UnionsBet e unisciti a milioni di utenti soddisfatti in tutto il mondo.

Read More

Scopri il Mondo di Mostbet: Il Tuo Approdo per il Gioco Online – App, Casinò e Bonus

Introduzione a Mostbet

Benvenuti nel meraviglioso mondo di Mostbet, una piattaforma di gioco d’azzardo online che offre un’esperienza di casinò coinvolgente e vantaggiosa. Con un’ampia gamma di giochi e app utili, Mostbet è perfetto per gli appassionati di scommesse e casinò.

La Versatilità dell’App Mostbet

L’app Mostbet offre la comodità di giocare ovunque tu sia, con un’interfaccia intuitiva e facile da usare. Gli utenti possono scaricare l’applicazione sui loro dispositivi mobili per accedere rapidamente a giochi di casinò, promozioni e funzionalità di scommesse sportive.

Accesso Facile con il Mostbet Login

La procedura di Mostbet login è semplice e veloce, permettendo agli utenti di accedere immediatamente al loro account e iniziare a scommettere. La sicurezza è una priorità, quindi puoi essere certo che i tuoi dati siano protetti in ogni momento.

Bonus e Promozioni Esclusive

All’interno della piattaforma, i giocatori possono beneficiare di fantastici bonus Mostbet, che aumentano il loro potenziale di vincita. Che si tratti di giri gratuiti o di bonus sul deposito, c’è sempre qualcosa di speciale che ti aspetta.

Guida Completa al Mostbet Casino Online

Il Mostbet casino online è il luogo ideale per cimentarsi con una grande varietà di giochi, dai tavoli di carte alle slot machine. L’ampia scelta garantisce che tutti i giocatori trovino qualcosa che appassioni il loro interesse.

Perché Scegliere Mostbet?

Scegliere il Mostbet online casino significa optare per una piattaforma sempre aggiornata e ricca di contenuti nuovi e avvincenti. La tua esperienza di gioco sarà sempre al centro delle nostre priorità, e questo si riflette nella qualità del servizio e nell’ampiezza dell’offerta.

Mostbet App Banner

Conclusione

Non perdere l’opportunità di unirti alla comunità Mostbet e scoprire un mondo di emozioni e possibilità. Per ulteriori dettagli, visita il sito ufficiale di Mostbet per iniziare la tua avventura!

Guarda il Video per Saperne di Più

Read More

Unlock Exciting Rewards with Just Casino Bonus and Free Spins

In the ever-evolving world of online gambling, finding a platform that combines excitement, convenience, and ample rewards is crucial. Enter Just Casino, an online gaming hub that offers a myriad of enticing bonuses, including the coveted just casino bonus and just casino free spins. In this article, we delve into the features that make Just Casino a top choice for gaming enthusiasts.

The Alluring Just Casino Bonus

Just Casino Bonus Image

The just casino bonus is designed to enhance your gaming experience from the moment you sign up. New members are greeted with a generous welcome package, which usually includes a match bonus that boosts your initial deposit. This means more funds to explore and enjoy the vast array of games that Just Casino has to offer.

Experience the Thrill of Just Casino Free Spins

One of the standout features of Just Casino is the opportunity to enjoy Just casino free spins. Whether you’re a fan of classic slots or modern video slots, these spins provide a chance to win without risking your own money. Regular promotions ensure that both new and existing players can take advantage of these spins, amplifying the excitement of every spin.

Just Casino Online: Gaming at Your Fingertips

Thanks to its robust just casino online platform, players can access a comprehensive selection of games at their convenience. Whether you prefer slots, table games, or live dealer experiences, Just Casino delivers with seamless playability and state-of-the-art graphics, providing a fully immersive gaming experience.

Seamless Access with Just Casino App

The just casino app brings the full suite of games and promotions right to your mobile device. The app is designed with user-friendliness in mind, allowing players to enjoy their favorite games on the go, without sacrificing quality or performance. Available for both Android and iOS, the Just Casino app ensures that you never miss a bonus opportunity.

Secure and Convenient Just Casino Login

Security and ease of access are paramount at Just Casino. With a straightforward just casino login process, players can quickly and securely access their accounts. Advanced encryption technology protects your personal and financial information, so you can focus on what matters most: enjoying the games and winning big.

A Comprehensive Gaming Experience

Whether you’re a seasoned player or a newcomer, Just Casino offers something for everyone. From the impressive range of bonuses like the just casino bonus to the user-friendly app and secure login, the platform is dedicated to providing the ultimate gaming experience. Explore the just casino online universe today and unlock exciting rewards that amplify the thrill of gaming.

Read More

Explora Gran Casino Madrid Online: ¡Apuestas, Bonos y Más!

El Gran Casino Madrid se ha consolidado como uno de los destinos más populares para los entusiastas del juego en España. Gracias a su amplia oferta de juegos y servicios de primera calidad, este casino es conocido por su elegancia y sofisticación. Pero ¿sabías que también puedes disfrutar de todo lo que ofrece el Gran Casino Madrid sin necesidad de salir de casa? El Gran Casino Madrid Online te ofrece la posibilidad de vivir la experiencia del casino desde la comodidad de tu hogar.

Casino en Vivo Gran Casino Madrid

Opciones de Apuestas Disponibles

Al acceder al Gran Casino Madrid Online, te encontrarás con una amplia variedad de opciones de apuestas que se adaptan a todos los gustos y preferencias. Desde las clásicas mesas de ruleta y blackjack hasta las innovadoras tragaperras en línea, cada juego está diseñado para ofrecer una emoción única.

Bonos del Gran Casino Madrid

Uno de los atractivos más destacados del Gran Casino Madrid Online es su programa de bonos. Los nuevos jugadores pueden aprovechar bonificaciones de bienvenida que aumentan sus fondos iniciales, permitiéndoles explorar una mayor cantidad de juegos. Además, hay promociones regulares para usuarios recurrentes, lo que incrementa las oportunidades de ganar en grande.

Tipo de Bono Descripción
Bono de Bienvenida Duplicación del primer depósito hasta 100€.
Bono por Recarga Promociones semanales con beneficios para depósitos adicionales.
Programa de Lealtad Acumula puntos por cada apuesta y cámbialos por premios exclusivos.

Innovaciones Tecnológicas

El Gran Casino Madrid está a la vanguardia en tecnología de juegos. Su plataforma en línea utiliza las últimas innovaciones para garantizar una experiencia fluida y segura para todos los usuarios. Además, ofrecen un servicio al cliente 24/7 para resolver cualquier duda o inconveniente que pueda surgir durante el juego.

Entretenimiento en Vivo

Nada se compara con la adrenalina de un juego en vivo. El Gran Casino Madrid Online ofrece salas de juegos en vivo donde puedes interactuar con crupieres reales y otros jugadores. Esta experiencia está diseñada para los que buscan sentir la emoción del casino en tiempo real.

Conclusión

En resumen, el Gran Casino Madrid Online es la opción perfecta para aquellos que buscan una experiencia de apuestas completa y emocionante. Con su oferta de juegos, bonos atractivos y la comodidad de jugar desde cualquier lugar, es una propuesta que no puedes dejar pasar.

Read More