我想在 docker 镜像构建期间为 React 设置环境变量。设置 docker compose 后,React 返回 undefined
作为以下结果:
console.log(process.env.REACT_APP_EMAILJS_USERID);
我确认正在运行的容器看到了环境变量:
» docker exec -it mszan-portfolio-prod /bin/sh
/app # echo $REACT_APP_EMAILJS_USERID
foo
REACT_APP_EMAILJS_USERID=foo docker-compose -f docker-compose.production.yml build
REACT_APP_EMAILJS_USERID=foo docker-compose -f docker-compose.production.yml up
docker-compose.production.yml
services:
react:
container_name: mszan-portfolio-prod
restart: always
build:
context: .
dockerfile: Dockerfile.production
args:
- REACT_APP_EMAILJS_USERID=${REACT_APP_EMAILJS_USERID}
command: serve -s out -l 3000
ports:
- 4050:3000
Dockerfile.production
FROM node:lts-alpine
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
ARG REACT_APP_EMAILJS_USERID
ENV REACT_APP_EMAILJS_USERID $REACT_APP_EMAILJS_USERID
COPY package.json /app/
RUN npm install -g serve
RUN npm install
COPY ./ /app/
RUN npm run build
├── Dockerfile.production
├── docker-compose.production.yml
├── node_modules
├── package.json
├── pages
├── public
├── src
└── yarn.lock
答案 0 :(得分:1)
您应该像这样更改构建命令:
docker-compose -f docker-compose.production.yml build --build-arg REACT_APP_EMAILJS_USERID=foo
然后您可以简单地使用以下命令运行您的服务:
docker-compose -f docker-compose.production.yml up