I am able to run python FastAPI locally(connecting to local host http://127.0.0.1:8000/), but when I am trying to run through container, not getting any response on browser. No error message either.
content of main.py
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
content of Dockerfile
FROM python:3.9.5
WORKDIR /code
COPY ./docker_req.txt /code/docker_req.txt
RUN pip install --no-cache-dir --upgrade -r /code/docker_req.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--reload", "--host", "0.0.0.0"]
output on cmd when running container:-
docker run --name my-app1 python-fastapi:1.5
INFO: Will watch for changes in these directories: ['/code']
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started reloader process [1] using statreload
INFO: Started server process [7]
INFO: Waiting for application startup.
INFO: Application startup complete.
docker_req.txt —
fastapi==0.73.0
pydantic==1.9.0
uvicorn==0.17.4
3
Answers
I solved this problem by creating yaml file and running it via docker-compose
In yaml file, I also tried without ports and it still worked whereas the below docker run command not working
Can anyone pls explain why its not working from "docker run" command but working from yaml file?
Simpler: you can redirect local port
8000
to docker port8000
and now you can access it using one of
http://0.0.0.0:8000
http://localhost:8000
http://127.0.0.1:8000
Longer: you can expose port
8000
and run it using dockerIP
or in
Dockerfile
you can useEXPOSE 8000
Next you have to find
Container ID
or
And use (part of)
CONTAINER ID
to get container IP addressor
And now you can access it using
http://172.17.0.2:8000
EDIT:
In one line (on Bash)
Insert
-d
before docker run to run your container in Detached mode. try to run:docker run -d --name my-app5 -p 8000:8000 python-fastapi:1.5