0

I have ReactJs app with .env file like this:

REACT_APP_SERVER_URL="URL1"

Then I using Dockerfile to build to Image:

# Fetching the latest node image on apline linux
FROM node:22 AS builder
# Setting up the work directory
WORKDIR /app
# Installing dependencies
COPY ./package.json ./
RUN npm install
# Copying all the files in our project
COPY . .
# Building dist and run
RUN npm run build

# # Fetching the latest nginx image
FROM nginx
# Copying built assets from builder
COPY --from=builder /app/build /usr/share/nginx/html
# Copying our nginx.conf
COPY nginx.conf /etc/nginx/conf.d/default.conf

After that, I pushed this Image to my reposity. Then I am using this Docker Composer file:

db:
    image: postgres
    container_name: db
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgress
      POSTGRES_DB: my_db
      PGPORT: 5433
    volumes:
      - ./pgdata:/var/lib/postgresql/data
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    expose:
      - "5433"
    ports:
      - "5433:5433"
    restart: always

  server:
    image: my_server_image
    container_name: server
    platform: linux/amd64
    depends_on:
      - db
    ports:
      - "8081:8081"
    environment:
      DB_HOST: db

  react:
    image: my_web_image
    container_name: web
    depends_on:
      - server
    platform: linux/amd64
    environment:
      - REACT_APP_SERVER_URL="New URL" <-----HERE
    ports:
      - "8082:8082"

But when run docker compose up, then run my web app, I still see the REACT_APP_SERVER_URL show "URL1", can someone help?

console.log('url', process.env.REACT_APP_SERVER_URL)
 -> URL1
7
  • 1
    Front-end apps only use environment variables during the build phase. All their assets are statically compiled Commented Jul 25, 2024 at 6:54
  • Hi @Phil, did you mean I can not do that? I am new on Docker, thanks Commented Jul 25, 2024 at 6:57
  • Assuming your React app's build system is create-react-app (FYI that's a dead project, time to try something else like Vite), you'll want to create separate a .env.production file and use that in your production build. See create-react-app.dev/docs/adding-custom-environment-variables/… Commented Jul 25, 2024 at 6:57
  • Duplicate: How to set build .env variables when running create-react-app build script?. Commented Jul 25, 2024 at 6:59
  • @Phil thanks you, I read this topic before, my problem is I want to change the ENV variable programmatically without build the Image again. because I have to run this docker in 2 server (without know their IP after build Image), and I dont want to update .env file directly before build Commented Jul 25, 2024 at 7:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.