skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 case


  2. You 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.

    • Go to the Cloud Run section in the Google Cloud Console.
    • Click Create Service or select an existing service and click Edit and deploy new revision.
    • In the service configuration page, expand the Container tab.
    • Click Add Variable under the Environment variables section.
    • Enter the variable name (e.g., FOO) and its value (e.g., bar).
    • Click Create or Deploy to apply the changes.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search