How to use environment variables in nginx.conf

preface

During the development and deployment process, we will publish the project application to different environments, and different environments will load different resources through different parameter configurations.

For example, our application uses K8S to manage and deploy application containers and configMap to configure resources for different environments. For SpringBoot background applications, we can set the resources loaded by background YAML configuration file to the form of variables, which can be configured through K8S configMap. For Nginx reverse proxy configuration, configMap can configure the environment variables of Nginx service. How to make nginx.conf load the corresponding configuration according to the environment variables becomes an urgent problem to be solved.

Nginx. conf introduces environment variables into the nginx.conf file.

solution

How to introduce OS variables in nginx configuration? Nginx currently does not include built-in environment variables in its configuration. Some solutions include the perl_set directive for ngx_HTTP_perl_module, which is an additional module of Nginx.

Here’s another easy way to solve this problem. We can use environment variables to generate external configuration files for nginx, and then nginx.conf to configure the environment variable parameters by importing external files.

1) Build an external configuration file to generate the script otherServer.sh

The environment variables of the nginx image container have been configured using configMap. When the container service is started, this script is executed to generate the external configuration file upgrade.conf to be loaded

echo "upstream otherserver {" > /usr/local/nginx/conf/upstream.conf
echo " server $OTHER_SERVER1;" >> /usr/local/nginx/conf/upstream.conf
echo " server $OTHER_SERVER2;" >> /usr/local/nginx/conf/upstream.conf
echo "}" >> /usr/local/nginx/conf/upstream.conf
Copy the code
  1. Nginx.conf imports configuration parameters from external files
include ./upstream.conf server { listen 1002; server_name otherserver; client_max_body_size 100m; server_tokens off; add_header X-Frame_Options SAMEORIGIN; location / { proxy_pass https://otherserver; }}Copy the code
  1. Edit dockerfile
# Partial configuration
ADD ./nginx.conf /usr/local/nginx/conf/
ADD ./run.sh /root
ADD ./otherserver.sh /root

EXPOSE 80
ENTRYPOINT ["sh"."/root/run.sh"]
Copy the code

In the command, run.sh is the service startup script, and the dmzServer. sh execution statement is added. After dockerfile is configured, build the image.

Sh /root/dmzserver.shCopy the code
other

If the SSL module was not added at compile time, the service could not be started.

Solution:

./configure --prefix=/usr/local/nginx --with-http_stub_status_module\
  -- with-http_ssl_module --error-log-path=/var/log/nginx/error.log --http=log=path=/var/log/nginx/access.og \
  && make && make install
Copy the code