0

I have a env variable name: REACT_APP_BACKEND in my react app. I'm able to build my app and run it successfully in nginx in my macos.

When I try to run it inside docker and nginx, I pass list of environment variables with --env-file=.env command. However this env variable is undefined in the browser, even though when I entered the running docker instance I'm able to echo this variable successfully.

/ # echo $REACT_APP_BACKEND
http://localhost:3000
/ #

I don't know if I missing somethings in docker settings, nginx settings or my build command?

This is the nginx settings (nginx.conf):

server {
  listen       80;
  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}

This is docker config:

#... installing node and npm install#

RUN npm run build 

### STAGE 2: Production Environment ###
FROM nginx:1.12.0-alpine
COPY --from=build /usr/src/app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
1
  • This is exactly how it's meant to work. Your browser is on a different machine (potentially) and cannot access the node server's environment. Commented May 31, 2021 at 16:42

1 Answer 1

1

It turned out that problem is is from build command, When running npm run build, npm replaces all occurrences of environment variables with the values that it can find in .env or .env.production files in the same directory.

In my case, .env file was not in the same root.

Sign up to request clarification or add additional context in comments.

1 Comment

In my case I had ran the build command before creating the .env file

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.