简体   繁体   English

如何使用 create-react-app 在 docker-compose.yml 中传递环境变量

[英]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.我有 nginx 和客户端图像,由 docker-compose.yml 文件加载。 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.出于某种原因,应用程序运行时环境变量 (REACT_APP_MAXIMUM_CAMERAS_COUNT) 不可见(我未定义),我不知道为什么。

Here is my create-react-app Dockerfile:这是我的 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: 这是我的 docker-compose.yml 文件:
 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). **注意**,由于 docker-compose 从私有注册表中提取图像(没有任何构建),它不能使用带有“args”的“构建”块(已经尝试过使用 args 并且可以正常工作)。
Any workaround to solve this? 任何解决方法来解决这个问题?

The docker-compose file you have seems to do the right thing.您拥有的 docker-compose 文件似乎做对了。 Try to get a shell inside the running container and type export .尝试在正在运行的容器中获取一个 shell 并输入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.github上有一个冗长的讨论,即使它可能不是最佳的,我每次启动服务时都会“重新构建然后运行”。 It is not optimal, but it works for what I need.它不是最佳的,但它适用于我需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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