简体   繁体   中英

React process.env can't read environment variables in docker-compose.yml

My React project use environment variables and there the variables in docker-compose.yml. but they couldn't be read from the project.

docker-compose.yml

version: '3.4'
services:
  frontend:
    build: 
      context: .
      target: app
    environment:
      - API_PROTOCOL=http
      - API_HOST=localhost
      - API_PORT=10000
    volumes:
      - app-volume:/share
    command: cp -R ./build /share
...
/* Ngnix Setting */
...
volumes:
  app-volume:

api.js

export const API_PROTOCOL = process.env.API_PROTOCOL || 'http';
export const API_HOST = process.env.API_HOST || 'localhost';
export const API_PORT = process.env.API_PORT || '8080';
export const getAPIUrl = () => {
  return `${API_PROTOCOL}://${API_HOST}:${API_PORT}`
};

And I printed using console.log(getAPIUrl());.

but it shows up default values like below.

Output

http://localhost:8080

You must create custom environment variables beginning with REACT_APP_ . Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name. Changing any environment variables will require you to restart the development server if it is running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM