Fluke
Fluke

Reputation: 1

Can a static page read environment variable?

Currently I have a nginx server running in a container and want to display a static page when someone access https://example.com/showname/. The static page need to show the pod name get from the environment variable, is there a way to do this?

my env var name:deployment_env and below is static page code

<html>
    <head>
        <title>Test NGINX passed</title>
    </head>
    <body>
        <h1>deploy_env</h1>
        <h1><span id="deploy_env" style="display: block;"></span></h1>
        <script>
            var env = window.env;
            var deploy = document.querySelector('#deploy_env');
            deploy.textContent = env.deployment_env;
        </script>
    </body>
</html>

Upvotes: 0

Views: 340

Answers (1)

user11784
user11784

Reputation: 33

If you are using the official nginx docker image, there is an easy way since the image contains envsubst functionality for quite some time now.

  1. Here is the solution as you wished. It uses the envsubst feature to replace the environment variable in a file called env.js.template. It will be substituted and written into the html folder when nginx starts.

showname.html

<html>
    <head>
        <title>Test NGINX passed</title>
        <script src="/env.js"></script>
    </head>
    <body>
        <h1>deploy_env</h1>
        <h1><span id="deploy_env" style="display: block;"></span></h1>
        <script>
            var env = window.env;
            var deploy = document.querySelector('#deploy_env');
            deploy.textContent = env.deployment_env;
        </script>
    </body>
</html>

env.js.template

window.env = {
  "deployment_env": "${deployment_env}"
}

Dockerfile

FROM nginx:1

ENV NGINX_ENVSUBST_TEMPLATE_DIR=/usr/share/nginx/templates \
    NGINX_ENVSUBST_OUTPUT_DIR=/usr/share/nginx/html

COPY env.js.template /usr/share/nginx/templates/
COPY showname.html /usr/share/nginx/html/showname/index.html

docker-compose.yml

services:
  app:
    build: .
    environment:
      deployment_env: production
    ports:
      - 8000:80/tcp
  1. In your case, you could have it even simpler by leaving out javascript altogether and making the html page itself an nginx template:

showname.html.template

<html>
    <head>
        <title>Test NGINX passed</title>
    </head>
    <body>
        <h1>deploy_env</h1>
        <h1><span id="deploy_env" style="display: block;">${deployment_env}</span></h1>
    </body>
</html>

Dockerfile

FROM nginx:1

ENV NGINX_ENVSUBST_TEMPLATE_DIR=/usr/share/nginx/templates \
    NGINX_ENVSUBST_OUTPUT_DIR=/usr/share/nginx/html

COPY showname.html.template /usr/share/nginx/templates/showname/index.html.template

I admit that this functionality in the image was supposed to be used for configuration files only. If you want a cleaner solution, you might want to adjust the docker entrypoint to add a different envsubst usage.

Upvotes: 0

Related Questions