简体   繁体   中英

How to pass environment variables in docker-compose.yml with create-react-app

I have nginx and client images, loaded by docker-compose.yml file. For some reason, the environment variables (REACT_APP_MAXIMUM_CAMERAS_COUNT) are not visible when the application is running (I get undefined), and I can't figure out why.

Here is my create-react-app Dockerfile:

FROM node:alpine as builder

WORKDIR /app
COPY ./package.json ./
RUN npm i
COPY . .
RUN npm run build

FROM nginx
EXPOSE 3000
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /app/build /usr/share/nginx/html

And here is my docker-compose.yml file:
 version: '3' services: nginx: image: <ip_address>:5000/orassayag/osr_streamer_nginx:v1.0 restart: always ports: - '3050:80' client: image: <ip_address>:5000/orassayag/osr_streamer_client:v1.0 environment: - REACT_APP_MAXIMUM_CAMERAS_COUNT=10

**Note** that since the docker-compose pulls the images from a private registry (without any build), it can't use the "build" blocks with "args" (already tried with args and it works).
Any workaround to solve this?

The docker-compose file you have seems to do the right thing. Try to get a shell inside the running container and type export .

docker exec -it code_client_1 sh
/usr/app # export
export HOME='/root'
export HOSTNAME='f4b3fc891ce3'
export NODE_VERSION='10.15.0'
export PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
export PORT='80'
export PWD='/usr/app'
export REACT_APP_MAXIMUM_CAMERAS_COUNT='10'
export SHLVL='1'
export TERM='xterm'
export YARN_VERSION='1.12.3'
/usr/app #

There I can see the environment variable works. Your problem might be that your website is build without the environment being set, so it will not actually read your environment variables at runtime.

There is a lengthy discussion here on github and even though it might not be optimal, I have myself 'rebuild and then run' each time I start the service. It is not optimal, but it works for what I need.

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