Search code examples
reactjsdocker-composedockerfileenvironment-variablesproduction

React not reading environment variable value in production from docker-compose.yml but reading it on local machine


I tried to pass my variable from docker-compose.yml to docker container but my container doesn't see the value of this variable. I have tried many cases but all to no avail. here are my attempts.

First try:

FROM node:alpine3.17 as build
LABEL type="production"
WORKDIR /react-app
COPY package.json ./
COPY package-lock.json ./
RUN npm install
COPY . ./


ARG REACT_APP_BACKEND_URL
ENV REACT_APP_BACKEND_URL=$REACT_APP_BACKEND_URL
RUN npm run build

# production environment
FROM nginx:stable-alpine
COPY --from=build /react-app/build /usr/share/nginx/html
EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

Second try:

FROM node:alpine3.17 as build
LABEL type="dev"
WORKDIR /react-app
COPY package.json ./
COPY package-lock.json ./

# The RUN command is only executed while the build image
RUN npm install
COPY . ./

ARG REACT_APP_BACKEND_URL
ENV REACT_APP_BACKEND_URL=$REACT_APP_BACKEND_URL

RUN npm run build
RUN npm install -g serve
EXPOSE 3000
# The CMD command is only executed while the image is running
CMD serve -s build

And I built the container from Dockerfiles, then I pushed it to docker-hub with various version and after that I run docker-compose.yml from the remote server.

My docker-compose.yml

version: '3'
services:
  stolovaya51-react-static-server:
    container_name: stolovaya51-react-production:0.0.1 (for example)
    build: 
      args:
        - REACT_APP_BACKEND_URL=REACT_APP_BACKEND_URL
    ports:
      - "80:80"
      - "3000:3000"

By the way, when I run this code on my local machine, I see the value of the environment variable, but when I try to run this code on the server, I only see the variable name, but the value = "". I don't know the reason, what's the matter?


Solution

  • I have found the answear for my question! Firstly, i have combined two repository with frontend and backend into one project. Then, i have redesigned my project structure and gathere together two parts of my application. For now i have this structure:

     root_project_folder:
        ./frontend
        ...some src
        ./frontend/docker/Dockerfile
        ./backend
        ...somer src
        ./backend/docker/Dockerfile
        docker-compose.yml
    

    And now, my frontend applies all args from docker-compose.yml from the root folder