【问题标题】:Azure Web App Service + Docker Compose + NGINX Reverse Proxy -- 502 Error in DeploymentAzure Web App Service + Docker Compose + NGINX 反向代理——部署中的 502 错误
【发布时间】:2021-06-16 23:35:29
【问题描述】:

正如标题所述,我创建了一个全栈应用程序,它使用 FastAPI 作为后端,ReactJS 作为前端。我还有第三个容器用于我的 Nginx 反向代理。我拥有第三个容器的原因是,我可以使用我在 docker-compose.yaml 文件中创建的服务/容器名称从客户端浏览器调用我的后端。

然后我使用 compose 文件来构建和运行所有 3 个容器。当我在本地工作时,在我的浏览器上的 localhost 端点上一切正常。但是,当我尝试部署到 Azure Web App Service 时,我只能加载前端 (React) 主页。当我打开控制台时,我收到一条错误消息 502 (Bad Gateway)。

下面是我的 ReactJS 代码的 sn-p,它发出一个 post 请求以进行身份​​验证

import React, { useEffect, useContext } from 'react';
import { Redirect, Route } from 'react-router-dom';
import Cookies from 'js-cookie';
import { AuthContext } from './contexts/AuthContext';

const PrivateRoute = ({ component: Component, ...rest }) => {
  // Import the functions to set states
  const { isAuthenticated, setIsAuthenticated, setUsername } =
    useContext(AuthContext);

  // Read in the access token; if not available, make empty string
  const accessToken =
    Cookies.get('access_token') == null ? '' : Cookies.get('access_token');

  // Create the use effect function to generate the component
  useEffect(() => {
    fetch(`${window.location.protocol}//${window.location.hostname}/backend/auth/validate_token`, {
      method: 'POST',
      mode: 'cors',
      credentials: 'include',
      headers: {
        Accept: 'application/json',
      },
      body: JSON.stringify({
        token: accessToken,
      }),
    })
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        // Set the view based on the return
        if (response) {
          setIsAuthenticated(true);
          setUsername(response.username);
        } else {
          setIsAuthenticated(false);
        }
      });
  });

  return (
    <>
      <Route
        {...rest}
        render={() => {
          if (isAuthenticated) {
            return <Component {...rest} />;
          } else {
            return <Redirect to='/login' />;
          }
        }}
      />
    </>
  );
};

export { PrivateRoute };

下面是我的 docker compose 文件

version: "3"
services:
    reverse-proxy:
        container_name: reverse-proxy
        build:
            context: ./proxy
            dockerfile: Dockerfile
        image: ilecontainerregistry.azurecr.io/proxy:latest
        ports:
            - 80:80
            - 443:443
        depends_on:
            - frontend
            - backend
    frontend:
        container_name: frontend
        domainname: "usps-ile"
        # Remove the build command for configuration file in azure web app service
        build:
            context: ./frontend
            dockerfile: Dockerfile
        image: ilecontainerregistry.azurecr.io/frontend:latest
        ports:
            - 8080:80
        env_file:
            - ./frontend/.env
    backend:
        container_name: backend
        domainname: "usps-ile"
        # Remove the build command for configuration file in azure web app service
        build:
            context: ./backend
            dockerfile: Dockerfile
        image: ilecontainerregistry.azurecr.io/backend:latest
        ports:
            - 3000:3000
        env_file:
            - ./backend/app/.env

下面是我的 nginx 容器的 dockerfile

FROM nginx:latest

COPY nginx.conf /etc/nginx/

最后,这是我的 nginx.conf 文件

events {
    worker_connections 1024;
}

http {

    upstream backend{
        server backend:3000;
    }

    server {

        listen 80;
        listen 443;
        server_name _;

        location / {
            proxy_pass http://frontend:80/;
        }

        location /backend/ {
            proxy_pass http://backend/;
        }
    }
}

下面是来自 FastAPI 后端的 sn-p,用于 Python 中的身份验证后路由

@auth_router.post("auth/validate_token", tags=["Auth"])
async def validate_token(token: Token):
    '''
    This function is responsible for
    reading in the token in an object
    and validating if it is still valid
    '''

    try:

        # Get the access token from the request cookie
        authorization: str = token.token

        # Split the access token on the space "Bearer" "xxxxxxxxx-token"
        scheme, access_token = get_authorization_scheme_param(authorization)

        # Decode the token and check if it is valid
        decoded_token = jwt.decode(
            token=access_token,
            key=os.getenv("SECRET_KEY"),
            algorithms=[os.getenv("ALGORITHM")]
        )

        return decoded_token
    except Exception as e:
        return False

提前谢谢你!

【问题讨论】:

    标签: nginx deployment docker-compose azure-web-app-service reverse-proxy


    【解决方案1】:

    看起来我找到了一个适合我的解决方案,我最初将 FastAPI 的 PORT 暴露在 3000(我在开发过程中设置的),但是当我尝试使用 docker compose 部署它时,我遇到了一些问题容器通信。

    我默认为 fastapi 容器恢复到正常的 80 端口,并将我的 nginx conf 文件更改为如下所示,它就像一个魅力!希望我可以帮助其他陷入困境的人。

    events {
        worker_connections 1024;
    }
    
    http {
    
        server {
    
            listen 80;
            server_name _;
    
            location / {
                proxy_pass http://frontend:80/;
            }
    
            location /backend/ {
                proxy_pass http://backend:80/;
            }
        }
    }
    

    【讨论】:

    • 您是否更改了 Azure 应用服务中的其他任何内容?目前正在努力解决同样的问题,但是我仍然无法使用 nginx 重定向到我的后端。
    • 您是否确保您的撰写和容器中的端口正确映射到代理?在我的示例中,当后端暴露在端口 3000 上时,我最初在端口 80 上监听
    • 所以是的,我想通了。结果我忘了公开正确的端口......愚蠢的错误,但有时你只是对自己的代码视而不见。无论如何谢谢:-)
    • 我们以前都去过那里!很高兴听到你能弄清楚! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    • 2021-05-28
    • 2018-04-15
    • 1970-01-01
    相关资源
    最近更新 更多