带 nginx、fastAPI 的 HTTPS,docker

HTTPS with nginx, fastAPI, docker

我正在为我的 FARM 堆栈应用程序使用 nginx。我 运行 遇到一个问题,我的 API 不通过 HTTPS,它在 HTTP 上工作。我已经尝试删除服务器 80 块仍然遇到同样的问题。

这是错误

docker-fastapi    | [2021-04-10 01:02:36 +0000] [9] [WARNING] Invalid HTTP request received. proxy-app         | 2021/04/10 01:02:36 [error] 22#22: *15 peer closed connection in SSL handshake while SSL handshaking to upstream, client: 192.168.249.11, server: xxxx, request: "GET /api/ HTTP/1.1", upstream: "https://192.168.160.2:8080/api/", host: "xxx"

这是 nginx 配置文件

upstream docker_fastapi {
    server docker-fastapi:8080;
}

server {
    listen 80;

    location ~ /api/ {
        proxy_pass http://docker_fastapi;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
    }

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

server {
    listen 443 ssl default_server;
    server_name xxxx;
    client_max_body_size 12m;
    listen [::]:443 ssl http2;
    ssl_certificate /etc/ssl/nginx.crt;
    ssl_certificate_key /etc/ssl/nginx.key;
    server_tokens off;
    add_header X-Frame-Options sameorigin always;
    add_header X-Content-Type-Options nosniff;
    add_header Cache-Control "no-cache";
    add_header X-XSS-Protection "1; mode=block";
    add_header Set-Cookie "lcid=1043; Max-Age=60";

    ssl_protocols TLSv1.2;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location ~ /api/ {
        proxy_pass https://docker_fastapi;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Host $server_name;
        proxy_ssl_server_name on;
    }

    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

我几乎复制了这个 repo 来尝试让 HTTPS 工作 https://github.com/geekyjaat/fastapi-react

目前,您的代理将请求传递给位于 https://192.168.160.2:8080/api/ 的 API。但是,HTTPS 证书依赖于域名。当您使用 IP 地址时,您可以在日志中看到有关 Nginx 和上游之间的 SSL 连接的错误:

closed connection in SSL handshake while SSL handshaking to upstream

您可以在 HTTP 中 运行 您的 API。要将请求从 nginx 代理传递到您的 API,请更改服务器 443 块中的配置:

  proxy_pass https://docker_fastapi;

至:

  proxy_pass http://docker_fastapi;