You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EC2部署Flask+Gunicorn+Nginx后POST请求报错,需配置Nginx?

Hey there! Let's break down what's causing that upstream prematurely closed connection error and walk through fixes that should get your Flask app working with Gunicorn and Nginx properly.

Key Observations First

Since your app works perfectly when running directly with python app.py, the issue isn't with your Flask code itself—it's almost certainly a mismatch in configuration between Gunicorn, Nginx, or how cross-origin requests are handled.

Step 1: Fix Cross-Origin Request Handling

Your POST request is cross-origin, and even though your Flask app works locally, Nginx might be dropping or mishandling the necessary preflight OPTIONS requests that browsers send before POSTs. You have two solid options here:

Option A: Add CORS Headers in Nginx

Edit your Nginx config file (either /etc/nginx/nginx.conf or your site-specific config in /etc/nginx/sites-available/) and add these lines inside the server block:

# Allow cross-origin requests (replace * with your actual frontend domain in production!)
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET, POST, OPTIONS;
add_header Access-Control-Allow-Headers Content-Type, Authorization;

# Handle preflight OPTIONS requests immediately to avoid connection issues
if ($request_method = OPTIONS) {
    return 204;
}

Note: If you're already using the flask-cors library in your app, skip the add_header lines to avoid header conflicts—just keep the OPTIONS handling block.

Option B: Ensure Flask-CORS is Configured Correctly

If you prefer handling CORS directly in Flask, double-check that flask-cors is installed and initialized properly in your app.py:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
# Allow your frontend domain specifically (better than * for security)
CORS(app, resources={r"/*": {"origins": "https://your-frontend-domain.com"}})
Step 2: Fix Timeout Mismatches Between Gunicorn and Nginx

This error often pops up when your POST requests (like /train or /save_data) take longer to process than Gunicorn's default timeout. Gunicorn will drop the connection mid-processing, which Nginx reports as "prematurely closed".

Update Gunicorn's Timeout

If you start Gunicorn manually, add the --timeout flag (adjust the value to match your app's processing time—300 seconds is a safe starting point):

gunicorn --workers=3 --timeout=300 --bind unix:/home/ec2-user/myproject/myproject.sock app:app

If you're using a systemd service for Gunicorn, edit your service file (e.g., /etc/systemd/system/gunicorn.service) to include the timeout:

ExecStart=/usr/bin/gunicorn --workers=3 --timeout=300 --bind unix:/home/ec2-user/myproject/myproject.sock app:app

Then restart Gunicorn to apply changes:

sudo systemctl daemon-reload
sudo systemctl restart gunicorn

Sync Nginx's Timeout Settings

Make sure Nginx's timeouts are at least as long as Gunicorn's to avoid it giving up while waiting for a response. Add these lines to your Nginx server or location block:

proxy_connect_timeout 300s;
proxy_send_timeout 300s;
proxy_read_timeout 300s;
send_timeout 300s;

Restart Nginx after making changes:

sudo systemctl restart nginx
Step 3: Check Unix Socket Permissions

Nginx might not have access to the Gunicorn socket file, which can cause connection drops. Fix the permissions with these commands:

# Give Nginx access to the socket
sudo chown ec2-user:nginx /home/ec2-user/myproject/myproject.sock
# Set appropriate permissions (770 is tighter than 777 for production)
sudo chmod 770 /home/ec2-user/myproject/myproject.sock

Alternatively, you can set the umask directly when starting Gunicorn to ensure the socket has correct permissions from the start:

gunicorn --workers=3 --timeout=300 --bind unix:/home/ec2-user/myproject/myproject.sock --umask=007 app:app
Step 4: Dig Into Gunicorn Logs for Clues

If the above steps don't fix it, check Gunicorn's logs—they'll often show why the connection was closed (like an unhandled exception in your app that only triggers under Gunicorn). If you're using systemd, run:

sudo journalctl -u gunicorn -f

This will stream real-time logs so you can see exactly what happens when you send a POST request.

Final Notes

Start with the CORS and timeout fixes—those are the most common culprits here. If you still run into issues, the Gunicorn logs will point you to the root cause.

内容的提问来源于stack exchange,提问作者Stacy Thompson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:24:08