我正在使用docker构建我的react应用程序,并在nginx中部署它。
我在docker-compose.yml中设置了一个环境变量。
version: '2'
services:
nginx:
container_name: ui
environment:
- HOST_IP_ADDRESS= xxx.xxx.xx.xx
build:
context: nginx/
ports:
- "80:80"在创建了码头容器之后,当我在容器中创建变量时,我可以看到hi。
但是,当我试图使用process.env.HOST_IP_ADDRESS阅读它时,它正在记录undefined。
我在某个博客中看到,env变量只能在生产环境中访问。因为,我正在构建应用程序并在nginx中部署它,我应该能够访问它,但由于某种原因,我无法阅读它。
我是不是做了什么根本不对的事。如果是的话,请告诉我一个解决办法。我不是反应专家,我只是管理别人的代码。
更新:
Dockerfile看起来如下:
FROM node:8 as ui-builder
WORKDIR /home/ui
COPY helloworld .
RUN npm install
RUN npm run build
FROM nginx
COPY --from=ui-builder /home/ui/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]React组件片段如下:
import React, { Component } from 'react';
class HelloWorld extends Component {
render() {
console.log(process.env.HOST_IP_ADDRESS);
return (
<div className="helloContainer">
<h1>Hello, world!</h1>
</div>
);
}
}
export default HelloWorld;发布于 2018-08-30 20:06:55
Env变量应该从REACT_APP_开始,否则NODE_ENV变量有点混乱,您的环境变量将无法工作:
environment:
- REACT_APP_DEBUG=TRUE否则,docker-compose.yml无效,您将看到一条错误消息:
services.client.environment contains an invalid type, it should be an object, or an array下面是一个工作示例:
docker-compose.yml
version: "3.3"
services:
client:
container_name: client
environment:
- REACT_APP_DEBUG=TRUE
build:
dockerfile: Dockerfile
context: ./web/clientDockerfile
FROM node:6.0.0
# Set env variable
ARG REACT_APP_DEBUG
ENV REACT_APP_DEBUG=$REACT_APP_DEBUG
# that will be empty
RUN echo "DEBUG": $REACT_APP_DEBUG运行:
->docker-compose run client node
->process.env.REACT_APP_DEBUG
'TRUE'https://stackoverflow.com/questions/52103155
复制相似问题