If you're looking for a more straightforward approach to "template substitution at runtime," here's an idea that may suit your needs.
Instead of reinventing the wheel, consider using the envsubst
utility from the gettext
package within the base nginx
image on Docker Hub. This tool can perform variable substitutions within files by leveraging environment variables. By creating a simple shell script as an entrypoint, we can automate this process at runtime.
To get started, let's craft the entrypoint.sh
script:
#!/bin/sh
if [ -n "$BASEURL" ]; then
envsubst '$BASEURL' < /my.js.template > /my.js
exec nginx -g "daemon off;"
else
echo "Ensure that \$BASEURL is defined as an environment variable."
fi
This script will search for a file at /my.js.template
, which might resemble something like:
var url = "$BASEURL" + window.location.pathname + "bridge/";
Now, it's time to bundle everything into a new Docker image based on the original nginx
. Your Dockerfile
should look similar to this:
FROM nginx
COPY entrypoint.sh /entrypoint.sh
COPY my.js.template /my.js.template
ENTRYPOINT ["/entrypoint.sh"]
Assuming that /my.js
is the file you wish to modify with the URL based on the environment, launch this image like so:
docker run -d -e BASEURL=wss://myhost mynewnginximage
By providing the BASEURL
environment variable, the template will be updated and written to
/my.js</code before executing <code>nginx
as PID 1, just like the original base image does.
In practice, you would need to adjust the paths in the shell script to match your specific setup. However, in essence, you now have the flexibility to use the same image while altering the BASEURL
environment variable per deployment. With Docker Compose, you could define an empty environment variable like so:
environment:
BASEURL:
This configuration will prompt docker-compose
to draw on the local shell's setting for
BASEURL</code and pass it to the container when launching it with <code>docker-compose up
:
export BASEURL=ws://myhostfordev
docker-compose up
If any part of this explanation seems unclear, please don't hesitate to reach out for further clarification. For more advanced templating options beyond envsubst
, tools such as confd by Kelsey Hightower offer additional functionality along with the ability to incorporate environment variables into templates.