简体   繁体   中英

How to dynamically change API URL's in react app which ran in a Docker container without rebuilding?

What is the best way to manage API URL's in an application (created with create-react-app) and ran in a Docker container?

Actually, I want to build a docker image and be able to run it on different environments (production and staging for example) without building a new one.

My current solution is to start a container with some environment variable like "docker run -e ENV=dev".

Add a logic to read env from query params. If query params are not passed use the default. That way, you can easily switch between envs on the fly. If you want to remember your users choice, then store it in the storage and you can read from storage when query param is not passed.

I don't consider myself a React dev, but I have come across and solved the same problem with Vue and docker.

After a little research specifically for React, it looks like you can use the public folder to share a mounted file/directory with the running container. Vue has a similar folder. The files in that directory are accessible from the app root URL (/some-file.blah).

Your app's directory structure might look like:

./app
./app/src
./app/src/public/
./app/src/public/config.json
./app/src/... (the rest of your app)

I assume that config.json would then be available at /config.json after a build. You could either then include that file in your HTML template's script tags or load it on demand using AJAX depending on what stage of the page lifecycle it's needed.

Having very little experience with React myself, I assume someone more familiar can provide clarification (or better edits ) to help out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM