I’m creating a Docker image on the dev environment, and later, I will deploy this image to the production environment.
I have a react application that is served by next.js inside of the image.
Docker image is hosted on the Google Cloud Run which contains the environment variables.
As I understand, I should build an image once and then deploy it to different environments instead of rebuilding for each.
How to populate environment variables in the react app when the deploy script will trigger next start
?
So far all the techniques I’ve tried can swap the environment variables only in the build phase.
I’ve tried setting variables to publicRuntimeConfig
and env
parameters in next.config.js
but it still changes variables only on the build time for the react component
2
Answers
Next.js documentation has a section about environment variables for the browser and the runtime. https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables#bundling-environment-variables-for-the-browser
Also, this thread on GitHub touches on the issue https://github.com/vercel/next.js/discussions/22243
I just went with rebuilding as part of the command on how to run the image in Dockerfile
CMD ["npm", "run", "build-and-start"]
. It conflicts with build once and use in different environments practice, but it should be fine in my use caseYou can build once and deploy to somewhere like cloud run and configure environment variable for the container when it’s running.
See below document to check how you can use environment variables with cloud run.
https://cloud.google.com/run/docs/configuring/services/environment-variables
basically, follows below steps. I confirmed I can set environment variables and it changed the behavior of the container.