FastAPI + NGINX + Docker连接被拒绝

rvpgvaaj  于 2023-03-07  发布在  Nginx
关注(0)|答案(1)|浏览(384)

我试图创建一个简单的停靠组合,将启动2个容器之一的应用程序,如下所示:

from fastapi import APIRouter

router = APIRouter()

@router.get("/")
async def root():
    return {"message": "This is a Test"}
from fastapi import FastAPI
import uvicorn as uvicorn

from routers import test

app = FastAPI()
app.include_router(test.router)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

另一个用于NGINX,配置为:

worker_processes 1;

events {
  worker_connections 1024;
}

http {
    server {
        listen       80;

        location / {
            proxy_pass http://0.0.0.0:8000;
        }
    }
}

我的docker-compose如下所示:

version: "3.7"
services:
    web:
        build: nginx
        ports:
          - "80:80"
        depends_on:
          - app
        container_name: tensor_nginx

    app:
        build: app
        ports:
          - "8000:8000"
        container_name: test

当我启动时,一切都很好,我可以通过www.example.com连接到FastAPI创建的Swagger,端点返回代码中定义的字符串。0.0.0.0:8000/docs and the endpoint returns the string defined in the code.
但是如果我尝试使用nginx端口连接,它会说连接失败。

[error] 30#30: *5 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.1, server: , request: "GET / HTTP/1.1", upstream: "http://0.0.0.0:8000/", host: "127.0.0.1"

我在配置中遗漏了什么?

xxe27gdn

xxe27gdn1#

nginx conf的proxy_pass http://0.0.0.0:8000;行没有意义(因为nginx部署在容器中,所以无法解析地址0.0.0.0),此处需要在终端设备或域名之前指定完整地址。在您的情况下,可以使用docker合成文件中的域名,例如proxy_pass http://app:8000或手动设置域主

app:
    build: app
    hostname: my-fastapi-app
    ports:
      - "8000:8000"

以及

proxy_pass http://my-fastapi-app:8000;

相关问题