How to use environment variables in nginx configuration file

How to use environment variables in nginx configuration file

Preface

Nginx is an HTTP server designed for performance. Compared with Apache and lighttpd, it has the advantages of less memory usage and higher stability.

Since we need to deploy nginx docker now, we hope that the server_name in the nginx configuration file can be dynamically modified before starting the container.
However, the nginx configuration file does not support the use of environment variables. I found many solutions online and finally chose to use envsubst to rewrite the nginx configuration file.

How it works

Nginx consists of a kernel and modules. The kernel is very small and concise, and its work is also very simple. It only maps client requests to a location block (location is a directive in the Nginx configuration for URL matching) by looking up the configuration file. Each directive configured in this location will start different modules to complete the corresponding work.

Nginx modules are structurally divided into core modules, basic modules and third-party modules:

Core modules: HTTP module, EVENT module and MAIL module Basic modules: HTTP Access module, HTTP FastCGI module, HTTP Proxy module and HTTP Rewrite module,
Third-party modules: HTTP Upstream Request Hash module, Notice module, and HTTP Access Key module.

Learn envsubst

envsubst replaces the environment variables with the values ​​of the specified tags in the file.
For example, there is a file env.conf with the following content:

[test]
ip = ${ip}
port = ${port}
url = http://${ip}:${port}/index.html
phone = ${phone}

When executing export ip=192.168.1.5 , export port=8081 , export phone=13522223334 , the environment variables are written.
Then execute envsubst < env.conf > env.new.conf to generate the following env.new.conf

[test]
ip = 192.168.1.5
port = 8081
url = http://192.168.1.5:8081/index.html
phone = 13522223334

You can also specify to replace only some environment variables, source env.env && envsubst '$ip;$phone' < env.conf , which will only replace the two variables ip and phone.
The above only replaces part of the environment variables. In Linux testing, only single quotes can be used. Double quotes are invalid. I have tried delimiters , . ; | and these four are all OK. I guess there are more delimiters.

Apply nginx configuration file

docker-compose.yml file is as follows

version: "3"
 
services:
  nginx:
    image: nginx:1.20.1-alpine
    container_name: nginx
    ports:
      - 80:80
      -443:443
    environment:
      - NGINX_HOST=www.janbar.com
      - NGINX_PORT=80
    volumes:
      - /root/janbar.temp:/etc/nginx/conf.d/janbar.temp
    command: /bin/sh -c "envsubst < /etc/nginx/conf.d/janbar.temp > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
    network_mode: bridge
    restart: always

The contents of the /root/janbar.temp file are as follows

server {
    listen ${NGINX_PORT};
    listen [::]:${NGINX_PORT};
    server_name ${NGINX_HOST};

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

According to the above docker-compose.yml configuration file, the configuration file in the docker container is finally generated as follows cat /etc/nginx/conf.d/default.conf

server {
    listen 80;
    listen [::]:80;
    server_name www.janbar.com;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

Summarize

After the above operations, you can finally update the internal configuration file of the nginx docker container through environment variables. Mission accomplished!

The above is the details of using environment variables in the nginx configuration file. For more information about nginx environment variables, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to implement distributed current limiting using nginx
  • How to deploy static pages using Nginx
  • How to use Nginx proxy to surf the Internet
  • Detailed explanation of how to build a CDN server with Nginx (picture and text)
  • Nginx working mode and proxy configuration usage details

<<:  Notes on MySQL case sensitivity

>>:  Two types of tab applications in web design

Recommend

Win2008 Server Security Check Steps Guide (Daily Maintenance Instructions)

The document has been written for a while, but I ...

JavaScript BOM location object + navigator object + history object

Table of contents 1. Location Object 1. URL 2. Pr...

Introduction to ufw firewall in Linux

Let's take a look at ufw (Uncomplicated Firew...

Vue implements login verification code

This article example shares the specific code of ...

How to solve the slow speed of MySQL Like fuzzy query

Question: Although the index has been created, wh...

The implementation of event binding this in React points to three methods

1. Arrow Function 1. Take advantage of the fact t...

The pitfalls of deploying Angular projects in Nginx

Searching online for methods to deploy Angular pr...

Vue.js handles Icon icons through components

Icon icon processing solution The goal of this re...

Quickly master how to get started with Vuex state management in Vue3.0

Vuex is a state management pattern developed spec...

Summary of three rules for React state management

Table of contents Preface No.1 A focus No.2 Extra...

Detailed explanation of Linux file permissions and group modification commands

In Linux, everything is a file (directories are a...

Implementation steps of Mysql merge results and horizontal splicing fields

Preface Recently, I was working on a report funct...

Apache Log4j2 reports a nuclear-level vulnerability and a quick fix

Apache Log4j2 reported a nuclear-level vulnerabil...

Summary of MySQL5 green version installation under Windows (recommended)

1 Download MySQL Download address: http://downloa...

Detailed explanation of CSS multiple three-column adaptive layout implementation

Preface In order to follow the conventional WEB l...