'FastAPI/uvicorn not working when specifying host
I'm running a FastAPI app in Python using uvicorn on a Windows machine. It works fine when I either
- Run the following code on my mac, or
- When I don't specify the port for uvicorn (remove the
hostparameter from the uvicorn.run call) - When I specify port '127.0.0.1', which is the host it uses when I don't specify a host at all.
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == '__main__':
uvicorn.run(app, port=8080, host='0.0.0.0')
When I go to 0.0.0.0:8080 on my browser, I get an error that says "This site can’t be reached".
I have checked my current active ports to make sure I'm not getting a collision using netstat -ao |find /i "listening" and 0.0.0.0:8080 is not in use.
My current file configuration looks like this:
working_directory
└── app
├── gunicorn_conf.py
└── main.py
My gunicorn_conf.py is super simple and just tries to set the host and port:
host = "0.0.0.0"
port = "8080"
How can I get this to work when I specify host '0.0.0.0'?
Solution 1:[1]
As I was writing the question above, I found the solution and thought I would share in case someone else runs into this. To get it to work put "http://localhost:8080" into the web browser instead of "http://0.0.0.0:8080" and it will work fine. This also works if you're hitting the endpoint via the python requests package, etc.
Solution 2:[2]
Run this in terminal uvicorn main:app --port 8086 --reload
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jed |
| Solution 2 | Manoj M |
