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:
Why does this occur and how can I fix it?