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

配置Nginx与Gunicorn后,如何访问Flask应用及解决404问题?

问题描述

我已完成Nginx与Gunicorn的配置,此前通过python run.py访问Flask应用的API(地址为http://127.0.0.1:5000/users)。尝试使用http://<ip_address>/访问时,出现「404 Not Found nginx/1.22.1」错误。附上我的配置信息,想了解在Postman或浏览器中应输入什么地址来访问API:

Gunicorn配置文件(my-server.service)

[Unit]
Description=Flask Web Application Server using Gunicorn
After=network.target

[Service]
User=naveen.p@ah.zymrinc.com
Group=www-data
WorkingDirectory=/home/naveen/Documents/GitHub/flask-demo
Environment="PATH=/home/naveen/Documents/GitHub/flask-demo/myenv/bin"
ExecStart=/home/naveen/Documents/GitHub/flask-demo/myenv/bin/gunicorn --workers 3 --bind unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock run:app
Restart=always

[Install]
WantedBy=multi-user.target

Nginx站点配置文件(sites-available/my-server)

server {
    listen 80;

    location / {
        proxy_set_header Host $http_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-Proto $scheme;
        proxy_pass http://unix:/home/naveen/Documents/GitHub/flask-demo/my-server.sock;
    }
}

Nginx主配置文件(nginx.conf)

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
解决方案

访问地址

直接使用http://<你的服务器IP>/users即可访问API,路径和你用Flask内置服务器时保持一致,仅需将127.0.0.1:5000替换为服务器的公网/内网IP。

404错误原因及排查

  1. 路由缺失导致根路径404:你的Flask应用仅配置了/users路由,没有根路径/的处理逻辑,所以访问http://<ip_address>/时返回404是正常现象,并非配置错误。
  2. 确认Gunicorn服务状态:执行systemctl status my-server.service检查服务是否正常启动,若未启动则执行systemctl start my-server.service并设置开机自启systemctl enable my-server.service。
  3. 启用Nginx站点配置:检查/etc/nginx/sites-enabled/目录下是否存在指向/etc/nginx/sites-available/my-server的软链接,若没有则执行:
    ln -s /etc/nginx/sites-available/my-server /etc/nginx/sites-enabled/
    
    之后重启Nginx服务:
    systemctl restart nginx
    
  4. 套接字文件权限检查:确保Nginx用户能访问my-server.sock,执行以下命令调整权限:
    chmod 777 /home/naveen/Documents/GitHub/flask-demo/my-server.sock
    
    或调整所属组:
    chown :www-data /home/naveen/Documents/GitHub/flask-demo/my-server.sock
    
    调整后重启Gunicorn和Nginx服务。

内容的提问来源于stack exchange,提问作者Naveen Pandia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:15:11