18

I'm running a FastAPI app in Python using uvicorn on a Windows machine without a frontend (e.g. Next.js, etc.) so there should NOT be any iteraction between a local frontend and backend like there is in this question. Plus the answer(s) to that question would not have solved my issue/question. That question was also asked AFTER this one so THIS QUESTION IS NOT A DUPLICATE!

It works fine when I do any one of the following options:

  1. Run the following code on my mac, or
  2. When I don't specify the port for uvicorn (remove the host parameter from the uvicorn.run call)
  3. 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'?

Jed
  • 1,823
  • 4
  • 20
  • 52

3 Answers3

20

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.

Jed
  • 1,823
  • 4
  • 20
  • 52
8

Run this in terminal uvicorn main:app --port 8086 --reload

Manoj M
  • 189
  • 2
  • 4
1

0.0.0.0 isn't technically allowed as a destination address in IPv4, but can be used as a source address. Implementations vary, e.g. Linux treats it similar to localhost.

When testing your web server it is probably a better idea to send requests to 127.0.0.1 or localhost as you say.

Nameless One
  • 1,615
  • 2
  • 23
  • 39
  • If the downvoters clarify what they would like to be improved about my answer, then I'll gladly make improvements. My answer is the only answer to point out that sending traffic to 0.0.0.0 is a bad idea (although listening on 0.0.0.0 _can be_ a good idea). May answer also confirms working host name and IPs, when connecting from the same machine. Obviously when connecting from a different machine, you'd have to use the IP on the network or a hostname in DNS. – Nameless One Aug 29 '23 at 20:41