简体   繁体   English

"为什么启动并运行 Web 服务返回 500 Internal Server Error?"

[英]Why up and running web service returns 500 Internal Server Error?

I'm learning back-end and decided to write a simple web service using FastAPI.我正在学习后端,并决定使用 FastAPI 编写一个简单的 Web 服务。 The idea is, the front-end does the request to the webserver, then the webserver communicates with Postgresql DB to retrieve the data, and then the webserver returns that data to the front-end.这个想法是,前端向网络服务器发出请求,然后网络服务器与 Postgresql DB 通信以检索数据,然后网络服务器将该数据返回给前端。 I'm using FastAPI for creating a web service, Nginx to expose that service to the internet, Postgresql for storing the data.我使用 FastAPI 创建 Web 服务,使用 Nginx 将该服务公开到 Internet,使用 Postgresql 存储数据。
Here is my code for that service:这是我对该服务的代码:

from fastapi import FastAPI, HTTPException
import psycopg2
import time

app = FastAPI()

while True:
    try:
        # Connect to your postgres DB
        conn = psycopg2.connect(host='hostIP', database='postgres',user='postgres',password='passwd')

        # Open a cursor to perform database operations
        cursor = conn.cursor()
        print('DB connection was successfull!')
        break
    except Exception as error:
        print('Connection to DB failed')
        print("Error: ", error)
        time.sleep(2)

@app.get("/")
async def root():
    cursor.execute("""SELECT * FROM characters""")
    flags = cursor.fetchall()
    return {'data': flags}

hostIP = is IP address of my ubuntu server (for security purpose I'm not showing actual IP here) which is installed on VirtualBox VM. hostIP = 是安装在 VirtualBox VM 上的我的 ubuntu 服务器的 IP 地址(出于安全目的,我没有在此处显示实际 IP)。 So my web service and database both are deployed on this VM.所以我的网络服务和数据库都部署在这个虚拟机上。
Then I created a gunicorn.service to run fastAPI service:然后我创建了一个 gunicorn.service 来运行 fastAPI 服务:

[Unit] Description=Gunicorn Web Server as Unit Service Systemd After=network.target [单位] 描述=Gunicorn Web 服务器作为单位服务 Systemd After=network.target

[Service] [服务]
User=ubuntuserver用户=ubuntuserver
Group=ubuntuserver组=ubuntuserver
WorkingDirectory=/home/ubuntuserver/test工作目录=/home/ubuntuserver/test
Environment="PATH=/home/ubuntuserver/test/venv/bin"环境="PATH=/home/ubuntuserver/test/venv/bin"
ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config /home/ubuntuserver/test/main.py main:app ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config /home/ubuntuserver/test/main.py main:app

[Install] [安装]
WantedBy=multi-user.target WantedBy=多用户.target

For nginx, I configured default.conf file like below:对于 nginx,我配置default.conf文件,如下所示:

server {
  listen 80;
  server_name hostIP;
  location / {
    proxy_pass http://localhost:8000;
  }
}

So I expect to type in on another computer's browser, hostIP:80 and get database information or at least some success message etc. but instead I get Internal Server Error .所以我希望在另一台计算机的浏览器上输入 hostIP:80并获取数据库信息或至少一些成功消息等,但我得到的是Internal Server Error
On server-side, I ran below command to check the services:在服务器端,我运行以下命令来检查服务:

systemctl status postgresql 
systemctl status gunicorn.service  
systemctl status nginx  

And they all appear to be normally activated.而且它们似乎都被正常激活了。

Below I checked all ports in use by services:下面我检查了服务使用的所有端口:
港口

Am I missing something ?我错过了什么吗?

EDIT编辑
After using suggestion by Thomas and running below command:在使用 Thomas 的建议并运行以下命令后:

sudo journalctl -f -u nginx -u gunicorn  

I got folowing output:我得到以下输出:

Feb 06 12:08:31 ubuntuserver gunicorn[3975]: [2022-02-06 12:08:31 +0000] [3975] [ERROR] Error handling request / 2 月 6 日 12:08:31 ubuntuserver gunicorn[3975]: [2022-02-06 12:08:31 +0000] [3975] [ERROR] 错误处理请求 /
Feb 06 12:08:31 ubuntuserver gunicorn[3975]: Traceback (most recent call last): 2 月 6 日 12:08:31 ubuntuserver gunicorn [3975]:回溯(最近一次通话最后):
Feb 06 12:08:31 ubuntuserver gunicorn[3975]: File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 136, in handle 2 月 6 日 12:08:31 ubuntuserver gunicorn[3975]:文件“/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py”,第 136 行,在句柄中
Feb 06 12:08:31 ubuntuserver gunicorn[3975]: self.handle_request(listener, req, client, addr) 2 月 6 日 12:08:31 ubuntuserver gunicorn[3975]: self.handle_request(listener, req, client, addr)
Feb 06 12:08:31 ubuntuserver gunicorn[3975]:File "/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py", line 179, in handle_request 2 月 6 日 12:08:31 ubuntuserver gunicorn [3975]:文件“/home/ubuntuserver/test/venv/lib/python3.8/site-packages/gunicorn/workers/sync.py”,第 179 行,在 handle_request
Feb 06 12:08:31 ubuntuserver gunicorn[3975]: respiter = self.wsgi(environ, resp.start_response) 2 月 6 日 12:08:31 ubuntuserver gunicorn[3975]: respiter = self.wsgi(environ, resp.start_response)
Feb 06 12:08:31 ubuntuserver gunicorn[3975]: TypeError: _ call_ () missing 1 required positional argument: 'send' 2 月 6 日 12:08:31 ubuntuserver gunicorn [3975]:TypeError:_ call_ () 缺少 1 个必需的位置参数:“发送”

Finally, resolved the issue, so FastAPI uses ASGI<\/a> which is asynchronous, and gunicorn, where I run my FastAPI application, uses WSGI<\/a> which is synchronous.最后,解决了这个问题,所以 FastAPI 使用异步的ASGI<\/a> ,而我运行我的 FastAPI 应用程序的 gunicorn 使用同步的WSGI<\/a> 。 When executing gunicorn command you should add uvicorn's workers.执行 gunicorn 命令时,您应该添加 uvicorn 的工人。 In my case, I've edited my gunicorn.service file:就我而言,我编辑了我的 gunicorn.service 文件:

[Unit] Description=Gunicorn Web Server as Unit Service Systemd After=network.target

[Service]
User=ubuntuserver
Group=ubuntuserver
WorkingDirectory=/home/ubuntuserver/test
Environment="PATH=/home/ubuntuserver/test/venv/bin"
ExecStart=/home/ubuntuserver/test/venv/bin/gunicorn --config /home/ubuntuserver/test/main.py main:app -w 4 -k uvicorn.workers.UvicornWorker

[Install]
WantedBy=multi-user.target

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM