0

I need to run a FastAPI in Docker on the remote machine and make it accessible for curl requests from any machine. Container builds and uvicorn starts, but when I try to do a curl request I get connection errors. I've already specified host 0.0.0.0 in the parameters, but experimenting with different ports I've noticed that port param seems to be ignored on uvicorn start. Probably that happens to the host param as well. I don't face this issue when running in the same way locally, at least I get Uvicorn running on http://0.0.0.0:some_port (Press CTRL+C to quit) in local logs.

Dockerfile

ARG PYTHON_VERSION=3.11-slim-buster
FROM python:${PYTHON_VERSION} as python

WORKDIR /app
ADD . .
RUN pip install -r requirements.txt
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8501"]

docker-compose.yml

version: '3.5'

services:
  container-name:
    container_name: container-name
    build:
      context: .
      dockerfile: Dockerfile
    env_file:
      - ./env/demo.env      
    ports:
      - "8501:8501" 

docker compose down && docker-compose build --no-cache && docker compose up

...
container-name  | INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
...

What could be a problem and what can I try to resolve it?

1 Answer 1

0

Your setup looks like it should work. But let's start with a simple project that works and then we can generalise to your specific case.

Assuming that project looks something like this:

├── docker-compose.yml
├── Dockerfile
├── main.py
└── requirements.txt

I made some small tweaks to your Dockerfile:

  • copy requirements.txt across separately so that don't install dependencies when rest of code changes; and
  • run uvicorn directly rather that via python (really just a matter of preference).
ARG PYTHON_VERSION=3.11-slim-buster
FROM python:${PYTHON_VERSION} as python

WORKDIR /app

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app","--host", "0.0.0.0","--port", "8501"]

Minimal requirements.txt and main.py:

uvicorn==0.27.0
fastapi==0.109.2
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World!"}

Then running as you did (but inserting some - which appear to be missing in your command):

docker-compose down && docker-compose build && docker-compose up

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.