1

I have a simple API with the following tree structure:

.
├── api
│   ├── fast.py
│   └── __init__.py
├── Dockerfile
├── Makefile
└── requirements.txt

The contents of fast.py are as follows:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn

app = FastAPI()

@app.get("/")
def index():
    return {"greeting": "Hello world!!!!!!!!!!!!!!"}

@app.get("/predict")
def predict():
    # create a datetime object from the user provided datetime
    return {'cool': True}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

The contents of the Dockerfile are as follows:

FROM python:3.8.6-buster

COPY api /api
COPY requirements.txt /requirements.txt

RUN pip install -r requirements.txt

CMD uvicorn api.fast:app --host 0.0.0.0 --port $PORT

When I start the API on my localhost in my Windows machine using wsl, it works fine, and I can access my API:

# uvicorn api.fast:app --reload                                             
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [20733] using statreload
INFO:     Started server process [20770]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     127.0.0.1:40446 - "GET / HTTP/1.1" 200 OK

However, when I try to access it from within a Docker container, I have issues. First I build the image as follows:

docker build --tag=docker_api_example .

then I run a container as follows:

docker run -it -e PORT=8000 -p 8000:8000 docker_api_example sh

The container opens up and I run the same uvicorn command again:

# uvicorn api.fast:app --reload

The process appears to start with no issues:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [8] using statreload
INFO:     Started server process [10]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

However, when I navigate to http://127.0.0.1:8000 on my browser I get an error:

enter image description here

Why does this occur and how can I fix it?

halfer
  • 19,824
  • 17
  • 99
  • 186
user32882
  • 5,094
  • 5
  • 43
  • 82
  • Is the port mapping of 8000 correct – Altaf Jun 08 '21 at 08:55
  • 1
    There is a difference between running on `127.0.0.1` and `0.0.0.0` and from your description it's not clear what you are actually doing (Your `CMD` has `--host 0.0.0.0` and then the logs show `127.0.0.1`). There's a nice explanation [here](https://stackoverflow.com/a/59182290/1561148) by [David Maze](https://stackoverflow.com/users/10008173/david-maze). – tgogos Jun 08 '21 at 09:20
  • In your `docker run` command, you're running `sh` instead of the (correct) `uvicorn --host 0.0.0.0` Try taking the `sh` off the end of that command. – David Maze Jun 08 '21 at 11:41

0 Answers0