简体   繁体   English

将自定义环境变量传递到 dockerized react-admin 应用程序中

[英]Passing custom environment variables into dockerized react-admin app

I'm using react-admin in a project which shall run in a Docker swarm.我在一个将在 Docker 群中运行的项目中使用react-admin

As we have multiple environments I defined an environment variable REACT_APP_API_ENDPOINT which points to our application's API with which react-admin shall interact.由于我们有多个环境,我定义了一个环境变量REACT_APP_API_ENDPOINT ,它指向我们的应用程序的 API,react-admin 将与之交互。

So far I have learned that this variable must be "baked into react-admin" on build time.到目前为止,我已经了解到这个变量必须在构建时“烘焙到 react-admin”。 So I added the following to my Dockerfile :所以我在我的Dockerfile添加了以下Dockerfile

ARG REACT_APP_API_ENDPOINT
ENV REACT_APP_API_ENDPOINT $REACT_APP_API_ENDPOINT

If this is true are my following assumptions correct?如果这是真的,我的以下假设是否正确?

  • I must set the value for REACT_APP_API_ENDPOINT when running the docker build command .运行REACT_APP_API_ENDPOINT docker build命令时,我必须设置REACT_APP_API_ENDPOINT的值。
  • I will need one Docker image per environment.每个环境我都需要一个 Docker 镜像。

Or is there a more feasible and dynamic way to pass that variable to react-admin?或者是否有更可行和动态的方式将该变量传递给 react-admin?

    1. 1.

dockerfile

ARG REACT_APP_API_ENDPOINT

docker build --build-arg REACT_APP_API_ENDPOINT=192.168.0.1

  1. You will need build container per environment您需要为每个环境构建容器

I finally got it working.我终于让它工作了。

Dockerfile文件

ARG REACT_APP_API_ENDPOINT
ENV REACT_APP_API_ENDPOINT $REACT_APP_API_ENDPOINT

Then, to build the container:然后,构建容器:
docker build -t myimage --build-arg REACT_APP_API_ENDPOINT=<URL> .

It looks a bit weird to me but I couldn't figure out any other way as React does need custom variables like REACT_APP_MY_VARIABLE at build time.我觉得这REACT_APP_MY_VARIABLE ,但我想不出任何其他方式,因为 React 在构建时确实需要自定义变量,如REACT_APP_MY_VARIABLE

At start i thought passing environment variables in a docker-compose file will work, but using RUN printenv inside Dockerfile (which prints systems environment variables), i found that the variables i was passing in, were not available when React was building production files.一开始我认为在 docker-compose 文件中传递环境变量会起作用,但是在 Dockerfile 中使用RUN printenv (打印系统环境变量),我发现我传入的变量在 React 构建生产文件时不可用。 The key here is to pass environment variables inside Dockerfile, when the image is created, before React build files are created.这里的关键是在创建镜像时,在创建 React 构建文件之前,在 Dockerfile 中传递环境变量。 Hence, a Dockerfile like this should work:因此,像这样的 Dockerfile 应该可以工作:

FROM node:13.12.0-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
#declaring react custom environment variable
ENV REACT_APP_API_HOST http://localhost:8080
COPY package.json ./
COPY package-lock.json ./
RUN npm ci --silent
COPY . ./
RUN npm run build

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

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