Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Docker Port Forwarding for FastAPI REST API

I have a simple FastAPI project called toyrest that runs a trivial API. The code looks like this.

from fastapi import FastAPI

__version__ = "1.0.0"

app = FastAPI()


@app.get("/")
def root():
    return "hello"

I’ve built the usual Python package infrastructure around it. I can install the package. If I run uvicorn toyrest:app the server launches on port 8000 and everything works.

Now I’m trying to get this to run in a Docker image. I have the following Dockerfile.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# syntax=docker/dockerfile:1

FROM python:3

# Create a user.
RUN useradd --user-group --system --create-home --no-log-init user
USER user
ENV PATH=/home/user/.local/bin:$PATH

# Install the API.
WORKDIR /home/user
COPY --chown=user:user . ./toyrest
RUN python -m pip install --upgrade pip && \
    pip install -r toyrest/requirements.txt
RUN pip install toyrest/ && \
    rm -rf /home/user/toyrest


CMD ["uvicorn", "toyrest:app"]

I build the Docker image and run it, forwarding port 8000 to the running container.

docker run -p 8000:8000 toyrest:1.0.0
INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

When I try to connect to http://127.0.0.1:8000/ I get no response.

Presumably I am doing the port forwarding incorrectly. I’ve tried various permutations of the port forwarding argument (e.g. -p 8000, -p 127.0.0.1:8000:8000) to no avail.

This is such a basic Docker command that I can’t see how I’m getting it wrong, but somehow I am. What am I doing wrong?

>Solution :

try to add this line to yourCMD in ̀dockerfile`:

CMD ["uvicorn", "toyrest:app","--host", "0.0.0.0"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading