Docker Compose修改React镜像.env变量不生效问题求助
问题原因
React的REACT_APP_*系列环境变量是在构建阶段(执行npm run build时)就被硬编码到静态JS文件中的。你的Dockerfile在builder阶段已经完成了构建,此时.env里的URL1已经被嵌入到生成的静态资源中。后续通过Docker Compose设置的环境变量,无法修改已经打包好的静态文件内容,所以控制台仍输出旧值。
解决方案
根据你的需求场景,有两种可行方案:
方案一:构建镜像时传入目标环境变量(适合URL不频繁变更的场景)
修改Dockerfile,支持构建时传入自定义环境变量,替换默认的.env值:
# Fetching the latest node image on alpine linux FROM node:22 AS builder WORKDIR /app # 定义构建参数,可在构建时覆盖 ARG REACT_APP_SERVER_URL="URL1" # 将构建参数转为环境变量,供build过程使用 ENV REACT_APP_SERVER_URL=$REACT_APP_SERVER_URL # Installing dependencies COPY ./package.json ./ RUN npm install # Copying all the files in our project COPY . . # Building dist and run RUN npm run build # Fetching the latest nginx image FROM nginx # Copying built assets from builder COPY --from=builder /app/build /usr/share/nginx/html # Copying our nginx.conf COPY nginx.conf /etc/nginx/conf.d/default.conf
构建镜像时通过--build-arg传入新URL:
docker build --build-arg REACT_APP_SERVER_URL="New URL" -t my_web_image .
之后正常推送镜像、用Docker Compose部署即可,无需在compose文件中再设置该环境变量。
方案二:运行时动态替换环境变量(适合需要频繁修改URL的场景)
通过容器启动脚本,在Nginx启动前将环境变量替换到静态文件中:
修改React代码或.env:将原环境变量值替换为占位符,比如在
.env中设置:REACT_APP_SERVER_URL="__REACT_APP_SERVER_URL__"或者在React组件中直接使用占位符:
const serverUrl = process.env.REACT_APP_SERVER_URL; console.log('url', serverUrl);创建启动脚本:新建
start.sh文件,内容如下:#!/bin/sh # 替换静态JS和HTML文件中的占位符为环境变量值 sed -i "s|__REACT_APP_SERVER_URL__|${REACT_APP_SERVER_URL}|g" /usr/share/nginx/html/static/js/*.js sed -i "s|__REACT_APP_SERVER_URL__|${REACT_APP_SERVER_URL}|g" /usr/share/nginx/html/index.html # 启动Nginx nginx -g 'daemon off;'修改Dockerfile:添加脚本并设置为启动命令:
# Fetching the latest node image on alpine linux FROM node:22 AS builder WORKDIR /app COPY ./package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx COPY --from=builder /app/build /usr/share/nginx/html COPY nginx.conf /etc/nginx/conf.d/default.conf # 复制启动脚本 COPY start.sh /start.sh # 赋予执行权限 RUN chmod +x /start.sh # 设置启动命令 CMD ["/start.sh"]调整Docker Compose配置:确保端口映射正确(Nginx默认监听80端口,若未修改nginx.conf,需改为
8082:80),并保留环境变量设置:react: image: my_web_image container_name: web depends_on: - server platform: linux/amd64 environment: - REACT_APP_SERVER_URL="New URL" ports: - "8082:80"
每次启动容器时,脚本会自动将静态文件中的占位符替换为当前设置的环境变量值。
内容的提问来源于stack exchange,提问作者famfamfam
相关产品推荐
相关产品推荐

