Search code examples
dockerfastapibad-gatewayhttp-status-code-502codespaces

Using a docker file on github codespaces results in 502 bad gateway


I have a fastapi python script that works on codespaces when I use the following command:

uvicorn main:fast_API_app --reload

The following code appears and my api's work fine:

INFO:     Will watch for changes in these directories: ['/workspaces/WebAPI']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [3229] using WatchFiles
INFO:     Started server process [3241]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

resulting in

Running it in github codespaces works fine

However, when I turn this into a docker container, running it results in a 502 Bad Gateway

terminal:

docker container run <username>/<container name>:v0.0.1
INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

Whether i select port 8000 to be public or private in github codespaces makes no difference.

Below is my Dockerfile which is used to build the image.

# For more information, please refer to https://aka.ms/vscode-docker-python
FROM python:3.10-slim

EXPOSE 8000

# Keeps Python from generating .pyc files in the container
ENV PYTHONDONTWRITEBYTECODE=1

# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1

# Install pip requirements
COPY requirements.txt .
RUN python -m pip install -r requirements.txt

WORKDIR /app
COPY . /app

# Creates a non-root user with an explicit UID and adds permission to access the /app folder
# For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers
RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app
USER appuser

# During debugging, this entry point will be overridden. For more information, please refer to https://aka.ms/vscode-docker-python-debug
CMD ["uvicorn", "main:fast_API_app", "--host", "0.0.0.0", "--port","8000"]

It results in the following error:

image of the error

It does not show an error code.

What I already tried (but potentially also did wrong):

  • I tried exposing different ports
  • tried running gunicorn instead of uvicorn
  • Searched on Stackoverflow.com for docker codespaces and bad gateway
  • Toggling the port forward to public / private
  • Changing the Port Protocol to https
  • rebuilding the container several times

Solution

  • Thank you @Hedde

    some renaming and changing it to:

    CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:8000", "--access-logfile", "-", "--error-logfile", "-", "main:app"]
    

    did the trick