🌐 이 글의 한국어 원문이 있습니다.한국어 원문 보기 →

· 12 min read

FastAPI WebSockets with Uvicorn and Nginx (Including Reverse Proxy)

Because WebSockets allow two-way communication, they have a wide range of uses. FastAPI in particular makes it easy to go from authentication, using the session token you get at login, all the way to implementing features, so there's a lot you can do with it. But most examples only cover the local environment, and it's hard to find posts that cover the issues you run into when deploying to an actual web service.

So I'm writing up the issues I ran into while testing WebSockets with FastAPI.

@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: int):
    await manager.connect(websocket)
    try:
        while True:
            data = await websocket.receive_text()
            await manager.send_personal_message(f"You wrote: {data}", websocket)
            await manager.broadcast(f"Client #{client_id} says: {data}")
    except WebSocketDisconnect:
        manager.disconnect(websocket)
        await manager.broadcast(f"Client #{client_id} left the chat")

This is a function that implements chat over WebSockets. It lets you implement a 'chat' among multiple connected users. (For the full code, see the FastAPI Websockets Tutorial.)

I ran FastAPI with Uvicorn.

uvicorn main:app --reload

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

The tutorial example lets you implement chat in a 'web browser' using HTML. But if you build on WebSockets, you can communicate not only between browsers but also with applications and processes.

# websocket_test_script.py

import asyncio

host = 'localhost:8000'
websocket_url = f"ws://{host}/ws/111111"

async def connect():
    async with websockets.connect(websocket_url) as websocket:
        await websocket.send("Hello, server!")
        response = await websocket.recv()
        print(f"Received message from server: {response}")

asyncio.run(connect())

If you open the browser chat window from the example and run the script above locally, 'Hello, server!' shows up in the browser.

The problem started when I deployed this example as-is to a 'web server.'

uvicorn main:app   --host 0.0.0.0 --port 8000

(0.0.0.0 is the setting for allowing 'access from anywhere.' Uvicorn only supports two settings: 'allow internal access' and 'allow access from anywhere.')

Communicating with the web server over HTTP isn't a problem. The problem is when you communicate with SSL applied. First, I tried configuring the certificate on Uvicorn itself and running the server with SSL.

uvicorn main:app  --ssl-keyfile=/path/to/localhost.key --ssl-certfile=/path/to/localhost.crt  --host 0.0.0.0 --port 8000

When you do this, SSL is applied to the API. But for WebSockets, a certificate error occurs during the WebSocket handshake.

...
  File "/usr/lib/python3.10/ssl.py", line 975, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1007)

The way to solve this is to communicate through Nginx.

Remove the SSL key settings from Uvicorn and let it accept connections over HTTP as before. Then have Nginx pass requests on to that 'port.' Nginx takes care of SSL.

server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/key/cert.pem;
    ssl_certificate_key /etc/nginx/key/privatekey.pem;

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

But this is where the problem begins. Once requests go through Nginx, the API works fine. But strangely, whenever I make a WebSocket request, I keep getting a 404 Not Found error.

INFO:     10.0.0.2:0 - "POST /login HTTP/1.0" 200 OK
INFO:     10.0.0.2:0 - "GET /ws/111111 HTTP/1.0" 404 Not Found

/login is a request handled by FastAPI. It works fine through Nginx. But when requesting /ws/111111 for the WebSocket, it says the 'path' itself doesn't exist.

What on earth is going on here….!

The problem was Nginx.

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

		# Settings for the WebSocket protocol
    location /ws/ {
        proxy_pass http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

WebSockets use HTTP's Upgrade header to switch from the existing protocol to the WebSocket protocol. You don't need any configuration for this when running with Uvicorn alone, but when you use Nginx, you have to configure the Upgrade header separately.

There's one more issue here. What if there's yet another 'proxy' in between? Should you apply the headers on the front proxy, or on the web server?

The answer is 'both.' The WebSocket only connects properly when you configure the headers on both sides for requests coming to the WebSocket path (/ws here).

Below is Uvicorn's 'verbose log' when the connection succeeds.

TRACE:    10.0.0.1:43956 - HTTP connection made
TRACE:    10.0.0.1:43956 - Upgrading to WebSocket
DEBUG:    = connection is CONNECTING
TRACE:    10.0.0.1:43956 - WebSocket conn
DEBUG:    < upgrade: websocketection made
DEBUG:    < GET /ws/111111 HTTP/1.1
DEBUG:    < host: 10.0.0.2:8000
DEBUG:    < connection: Upgrade
DEBUG:    < sec-websocket-key: **************==
DEBUG:    < sec-websocket-version: 13
DEBUG:    < sec-websocket-extensions: permessage-deflate; client_max_window_bits
DEBUG:    < user-agent: Python/3.10 websockets/12.0
TRACE:    10.0.0.1:43956 - ASGI [4] Started scope={'type': 'websocket', 'asgi': {'version': '3.0', 'spec_version': '2.3'}, 'http_version': '1.1', 'scheme': 'ws', 'server': ('10.0.0.2', 8000), 'client': ('10.0.0.1', 43956), 'root_path': '', 'path': '/ws/111111', 'raw_path': b'/ws/111111', 'query_string': b'', 'headers': '<...>', 'subprotocols': []}
TRACE:    10.0.0.1:43956 - ASGI [4] Receive {'type': 'websocket.connect'}
TRACE:    10.0.0.1:43956 - ASGI [4] Send {'type': 'websocket.accept', 'subprotocol': None, 'headers': '<...>'}
INFO:     ('10.0.0.1', 43956) - "WebSocket /ws/111111" [accepted]
DEBUG:    > HTTP/1.1 101 Switching Protocols
DEBUG:    > Upgrade: websocket
DEBUG:    > Connection: Upgrade
DEBUG:    > Sec-WebSocket-Accept: **************=
DEBUG:    > Sec-WebSocket-Extensions: permessage-deflate
DEBUG:    > date: Wed, 03 Apr 2024 09:28:02 GMT
DEBUG:    > server: uvicorn
INFO:     connection open
DEBUG:    = connection is OPEN
DEBUG:    < TEXT 'Hello, server!' [14 bytes]
TRACE:    10.0.0.1:43956 - ASGI [4] Receive {'type': 'websocket.receive', 'text': '<14 chars>'}
TRACE:    10.0.0.1:43956 - ASGI [4] Send {'type': 'websocket.send', 'text': '<25 chars>'}
DEBUG:    > TEXT 'You wrote: Hello, server!' [25 bytes]
TRACE:    10.0.0.1:43956 - ASGI [4] Send {'type': 'websocket.send', 'text': '<35 chars>'}
DEBUG:    > TEXT 'Client #111111 says: Hello, server!' [35 bytes]
DEBUG:    < CLOSE 1000 (OK) [2 bytes]
DEBUG:    = connection is CLOSING
DEBUG:    > CLOSE 1000 (OK) [2 bytes]
DEBUG:    x half-closing TCP connection
TRACE:    10.0.0.1:43956 - WebSocket connection lost
DEBUG:    = connection is CLOSED
TRACE:    10.0.0.1:43956 - ASGI [4] Receive {'type': 'websocket.disconnect', 'code': 1000}
TRACE:    10.0.0.1:43956 - ASGI [4] Completed
INFO:     connection closed

It nicely shows Uvicorn upgrading the protocol from HTTP to WebSocket, then opening and closing the connection.

I'm looking forward to everything I can build with FastAPI and WebSockets.

References

https://fastapi.tiangolo.com/advanced/websockets/fastapi.tiangolo.com https://ko.wikipedia.org/wiki/%EC%9B%B9%EC%86%8C%EC%BC%93ko.wikipedia.org https://github.com/tiangolo/fastapi/issues/5274github.com

Related posts

Home