【问题标题】:How to pass environment variables to a front-end web application in nginx?如何将环境变量传递给 nginx 中的前端 Web 应用程序?
【发布时间】:2020-10-02 23:18:21
【问题描述】:

我正在使用 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
    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`

【问题讨论】:

    标签: docker docker-compose


    【解决方案1】:

    您正在使用 nginx Web 服务器容器来提供您的 html 和 JS 文件。 Web 服务器按原样将这些文件提供给浏览器。这与使用 npm start 不同,其中 Node 引擎动态地提供 HTML 和 JS 文件。

    当您的 JS 文件在客户端浏览器上运行时,没有名为 process.env 的变量。

    在 Create React 应用程序中查看 cmets 以了解以下问题可能会帮助您了解更多:

    https://github.com/facebook/create-react-app/issues/2353

    如果您没有更多的环境变量,最简单的解决方案是使用 window.location.hostname 并相应地准备或选择 API url。

    app-config.js

    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>
            );
        }
    }
    

    【讨论】:

    • 我没有使用 react,我使用 JavaScript vanilla
    • 好的。高层解释保持不变。
    • 如果它是一样的,但是如果我做“app-config.js”的配置更清楚一点,我可以从我的docker-compose发送我的配置变量吗?感谢您花时间回答我。
    • 实际上不是。甚至,我就在两天前遇到了这个问题。所以我决定使用托管 UI 的主机名,并根据它找出 api url。docker compose 使用环境变量创建图像。这些变量对 Nginx 是可见的。Nginx 不做任何处理,只是提供 html 和 js 文件,甚至不查看环境变量。这就是为什么 docker compose 变量不能被在浏览器中运行的 Java 脚本代码使用。
    • 我希望有更好的解决方案,但感谢您抽出宝贵时间
    猜你喜欢
    • 2018-07-13
    • 2016-07-31
    • 1970-01-01
    • 2019-06-18
    • 2011-01-30
    • 2018-11-08
    • 2021-07-20
    • 2018-02-04
    • 2021-02-19
    相关资源
    最近更新 更多