Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI + Docker: Connection refused

everyone!

I am having problem deploying a FastAPI app using Docker containers. I have tested deploying it without Docker, just using FastAPI, and all works just fine. But when I use Docker, I am not able to access the API, getting only the "Connection refused" message.

Here it is the Dockerfile I am using:

FROM python:3.7-slim

WORKDIR /app/
COPY . /app/

RUN apt-get update && apt-get install -y --no-install-recommends apt-utils
RUN apt-get -y install curl
RUN apt-get install libgomp1

RUN pip install -r requirements.txt

EXPOSE 8000

CMD ["uvicorn", "main:app", "--host=0.0.0.0", "--reload"]

Note: the API I have to build is ML-focused, so I needed to declare some packages as above so LightGBM can be used.

After constructing the Dockerfile, I have runned the following Docker commands:

docker build -t ml_app:latest .

docker run -p 8000:8000 --name test_cont ml_app:latest

When I check running containers using docker ps, I find that the container is working fine, as the image shows: docker ps

Additionally, docker logs just return the default message of FastAPI:

INFO:     Will watch for changes in these directories: ['/app']
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.

I am trying to access the API using the URL that FastAPI indicates when I run the container (http://localhost:8000). I have sent requests against this URL using the browser, line commands with curl and Postman.

There are the things I have tried to fix this issue:

  1. Change the ports.
  2. With and without the command EXPOSE.
  3. Running a Python script instead of using uvicorn explicitly.
  4. Exposing a port different (and equal) to those declared in uvicorn argument.

So, does anyone gets what I am doing wrong? Or what I should do to access the API deployed in the container?

Thank you all!

like image 536
Matheus Rosso Avatar asked Jul 01 '26 12:07

Matheus Rosso


1 Answers

After running docker container , try http://localhost:80 instead of http://0.0.0.0:8000 (what's shown on docker logs).

like image 75
mallana Avatar answered Jul 04 '26 01:07

mallana



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!