Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am to run python FastAPI locally, but when trying to run through container, not getting any response on browser. No error as well

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
like image 482
Vishal Avatar asked Nov 01 '25 21:11

Vishal


2 Answers

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

like image 137
Raghad Avatar answered Nov 03 '25 09:11

Raghad


Simpler: you can redirect local port 8000 to docker port 8000

docker run -p 8000:8000 ...

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 docker IP

docker run --expose 8000 ...

or in Dockerfile you can use EXPOSE 8000

Next you have to find Container ID

docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED         STATUS         PORTS      NAMES
0e7c6c543246   furas/fastapi   "uvicorn app.main:ap…"   3 seconds ago   Up 2 seconds   8000/tcp   stupefied_nash

or

docker ps -q
0e7c6c543246

And use (part of) CONTAINER ID to get container IP address

docker inspect 0e7c | grep IPAddress
            "SecondaryIPAddresses": null,
            "IPAddress": "172.17.0.2",
                    "IPAddress": "172.17.0.2",

or

docker inspect --format '{{ .NetworkSettings.IPAddress }}' 0e7c
172.17.0.2

And now you can access it using

  • http://172.17.0.2:8000

EDIT:

In one line (on Bash)

docker inspect --format '{{ .NetworkSettings.IPAddress }}' $(docker ps -q)
172.17.0.2
like image 28
furas Avatar answered Nov 03 '25 11:11

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!