skip to Main Content

I have a Uvicorn/FastAPI server that I am attempting to run through a Docker container. The server works fine outside of the Docker container, but when running it through Docker I get a connection refused error when trying to access it using the full hostname. Through Docker it works if I access it through localhost.

Here is my main.py file:

import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import routers.chat_router as chat_controller
import uvicorn

app = FastAPI(debug=True)

app.include_router(chat_controller.router)

origins = [
    "http://localhost:3000",
    "https://localhost:3000",
    "https://my.hostname.domain.com:3000"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == "__main__":
    host = "0.0.0.0"
    uvicorn.run("main:app", host=host, port=8000, log_level="debug",
                ssl_keyfile="privateKey2.key", ssl_certfile="certificate2.crt")

This is my Dockerfile:

FROM python:3.10

# set a directory for the app
WORKDIR /usr/src/app

# copy all the files to the container
COPY . .

# install dependencies
RUN pip install --no-cache-dir -r requirements.txt

RUN pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

# define the port number the container should expose
EXPOSE 8000

# run the command
CMD ["python", "main.py"]

Why is Uvicorn/FastAPI refusing the connection when it is through Docker? What am I doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    The problem was caused because I was using Docker through WSL. I needed to set up a port forwarding between my host machine and the WSL ports using netsh:

    netsh interface portproxy add v4tov4 listenport=8000 listenaddress=0.0.0.0 connectport=8000 connectaddress=172.18.28.x

    (change 172.18.28.x to whatever the address of your WSL IP address is)

    Source: https://github.com/microsoft/WSL/issues/4150


  2. When you are running the docker container use

    docker run <image-name> -p 8000:8000
    

    This maps your docker 8000 port to your host 8000 port
    Then you can go to your browser and go to

    http://0.0.0.0:8000/docs
    

    To get your server

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search