Using Docker environment variables at JavaScript runtime
September 04, 2023 by Anuraj
Docker Javascript
When creating a container for a single-page application with JavaScript frameworks like Angular, React, or Vue.js, we may have to inject certain configuration variables based the deployment environment. A common scenario is using API endpoint URL for the Javascript application which can vary depend on the environment. In Angular, we can use environment file for this purpose. But again the problem is we have to hard code the API URL in the environment file. In this post we will explore how we can do configure container environment variable in vanilla Javascript. This technique can be used in any Javascript framework or technology.
For hosting and running we are using Nginx Alpine. Here is the Dockerfile
We are not using nginx directly for serving the index.html page, instead we are using a shell script - docker-entrypoint.sh
. Here is the implementation of docker-entrypoint.sh
.
In the shell script, we are adding setting a Javascript variable - window.API_ENDPOINT
from the $API_ENDPOINT
environment variable using the cat
command. Then we are starting the nginx
web server with daemon mode off. And in the Dockerfile we are using this shell script as entry point - so that the env.js file will be populated and we will be running the nginx web server.
Inside scripts
folder we need to create an empty Javascript file with name env.js
.
Here is the index.html
file.
Please note we are including the env.js
file - which will set the API endpoint variable.
And here is the index.js
file
And when can build the image using the following command - docker build -t anuraj/staticweb:v1 .
- this command will build the image and we can run the container using following command - docker run -p 8080:80 -e API_ENDPOINT="https://api.example.com" anuraj/staticweb:v1
- Please note we are passing the API_ENDPOINT
as an environment variable. We can browse the application in http://localhost:8080. Here is the screenshot of the application running.
This way we can consume environment variables in Javascript - which can be used to provide server side configuration to frontend applications. Full source code available here - Docker samples
Happy Programming.
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub