Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeromy-vandusen-obs/b9a15d68bf99a5e1478b1dc90d008691 to your computer and use it in GitHub Desktop.
Save jeromy-vandusen-obs/b9a15d68bf99a5e1478b1dc90d008691 to your computer and use it in GitHub Desktop.
Static Website With Runtime Environment Variables

Static Website With Runtime Environment Variables

Main page (index.html)

<script src="./environment.js"></script>

Environment variables (environment.js)

window._env_ = {
  BASE_URL = "http://localhost:3000"
}

Environment setting script (env.sh)

#!/bin/bash

rm /usr/share/nginx/html/environment.js
touch /usr/share/nginx/html/environment.js

{
  echo "window._env_ = {"
  echo "    BASE_URL: \"${BASE_URL}\""
  echo "};"
} >> /usr/share/nginx/html/profile.js

Docker build file (Dockerfile)

FROM nginx-alpine:latest

RUN rm -rf /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY ./build /usr/share/nginx/html
COPY ./env.sh /usr/share/nginx/html
RUN chmod +x /usr/share/nginx/html/env.sh

EXPOSE 80
CMD ["/bin/bash", "-c", "/usr/share/nginx/html/env.sh && nginx -g \"daemon off;\""]
@atrakic
Copy link

atrakic commented Sep 20, 2023

Note that you need to rebuild image on each env change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment