Docker 如何在nginx中将环境变量传递给前端web应用程序?
我正在使用docker compose处理其他人制作的图像,我想使用环境变量动态分配它 docker-compose.ymlDocker 如何在nginx中将环境变量传递给前端web应用程序?,docker,docker-compose,Docker,Docker Compose,我正在使用docker compose处理其他人制作的图像,我想使用环境变量动态分配它 docker-compose.yml version: "3.7" services: appfronted2: image: trafex/alpine-nginx-php7 container_name: fronted2 ports: - "80:8080" volumes: - ./fronted2:/var/www/html en
version: "3.7"
services:
appfronted2:
image: trafex/alpine-nginx-php7
container_name: fronted2
ports:
- "80:8080"
volumes:
- ./fronted2:/var/www/html
environment:
- HOST_BACKEND=172.99.0.11
- PORT_BACKEND=4000
networks:
tesis:
ipv4_address: 172.99.0.13
这是我的javascript,我想在这里获取变量,但无法获取这些变量
api.js
const HOST = process.env.HOST_BACKEND || "127.0.0.1"
const PORT = process.env.PORT_BACKEND || "4000"
const URL_API = `http://${HOST}:${PORT}/api`
您正在使用nginxweb服务器容器来提供html和JS文件。web服务器将这些文件按原样提供给浏览器。这与使用npm start不同,在npm start中,节点引擎动态地提供HTML和JS文件 当JS文件在客户端浏览器上运行时,没有名为process.env的变量 在Create React应用程序中查看以下问题的评论可能有助于您了解更多信息: 如果没有更多的环境变量,最简单的解决方案是使用window.location.hostname并相应地准备或选择API url app-config.js 在组件中使用
我没有使用react,我使用JavaScript。高层解释保持不变。如果是相同的,但为了更清楚一点,如果我配置app-config.js,我可以从docker compose中将我的配置变量发送给它吗?。谢谢你花时间回答我。实际上不是。甚至,就在两天前,我还面临着这个问题。所以我决定使用UI所在的主机名,并根据它计算api url。。docker compose使用环境变量创建图像。Nginx可以看到这些变量。。Nginx不做任何处理,只提供html和js文件,甚至不查看环境变量。。这就是为什么在浏览器中运行的Java脚本代码不能使用docker compose变量的原因。我希望有更好的解决方案,但我感谢您抽出时间
let backendHost;
const hostname = window && window.location && window.location.hostname;
if(hostname === 'whatsgoodonmenu.com') {
backendHost = 'https://api.whatsgoodonmenu.com';
} else {
backendHost = 'http://localhost:8080';
}
export const API_ROOT = `${backendHost}`;
import React from "react"
import {API_ROOT} from './app-config'
export default class UserCount extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`${API_ROOT}/count`)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render(){
return(
<label>Total visits: {this.state.data}</label>
);
}
}