Pass Docker variable to React index.html file

1.2k Views Asked by At

I am already familiar on passing Docker environmental variables to a React app by prepending the variable in the docker-compose.yml file with "REACT_APP_" string.

However I would like to do something similar in the index.html entrypoint that loads the actual React application.

Context: Imagine you want to pass a Google API key for a Google API and you want to swap between development and production Docker containers through docker-compose rather than by editing index.html.

Is it even possible?

1

There are 1 best solutions below

2
brandon-barnett On

I wrote a blog post about a similar, related topic last month -- let me know if this helps: https://www.brandonbarnett.io/blog/2018/05/accessing-environment-variables-from-a-webpack-bundle-in-a-docker-container/

TL;DR: create a shell script that auto-generates a static JS config file in your web server container. Here's how:

config.js

#!/bin/bash
echo "window.appConfig = { API_URL: '${API_URL}'} " >> config.js
cat config.js
apachectl -D FOREGROUND

Dockerfile

COPY --from=build-env /src/config.sh .
RUN ["chmod", "+x", "./config.sh"]
CMD ["/usr/local/apache2/htdocs/config.sh"]

docker-compose.yaml

...
environment:
  - API_URL=http://localhost:8082
...

index.html

<!-- config.js has to come before your bundle -->
<script src="config.js"></script>  
<script src="dist/bundle.js"></script>