Access Environment Variables in a Dockerfile to Build a Front-End Container

InstructorJoel Lord

Share this video with your friends

Send Tweet

In the previous lesson, Containerize the Front End of an Application with a Multi-Step Docker Build, we managed to put all of our front-end in a container and we can now distribute this container to the rest of our team. This will work well with stand-alone websites but as soon as you need to connect to an API, this could become an issue.

You will need to specify the base URL of your server and this would need to be done as an environment variable. The problem here is that since our application lives in a browser, it can’t read the environment variables from the server.

In the last lesson, you’ve seen that all requests were made to http://localhost:3000. This means that this value was hard-coded somewhere in the front end source code. The first thing you will want to do is to find out where this was coded and make sure that it is only defined in one place.

The fix here will be to create a bash script that updates the hardcoded localhost:3000 URL to a BASE_URL environment variable and update the instances that are used within the frontend app to your environment variable. This script will be called in the projects Dockerfile and override the original entry point.