Home > Software engineering >  Docker exit code 0 issue
Docker exit code 0 issue

Time:05-13

Here is my logs after trying to dockerizing a fastapi script:

$ docker-compose logs -f
Attaching to docker-name
docker-name exited with code 0

Here is my docker compose file:

version: '3'  

services:
  observatory-service:
    build: ./observatory  
    volumes:
      - ./observatory:/usr/src/app 
    ports:
      - 8000:8000  

docker file:

FROM python:3.9

COPY requirements.txt /usr/src/app/
RUN pip install -r /usr/src/app/requirements.txt

COPY . /usr/src/app

CMD ["python", "/usr/src/app/api.py"]

api.py:

from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def read_root():
    return { "Lux app": "Welcome to Lux app" }

@app.post("/extract_text")
def ali():
    return {"Hello": "World"}

I am sure it goes through api.py but it exits out of it without error. I am running this on Windows docker.

CodePudding user response:

The problem is that you're directly calling the fastAPI server script with python and not wrapped with a ASGI web server such as Uvicorn. This is explained in the debugging page of fastAPI.

I tested with latest versions of fastapi/uvicorn and it works just fine. I suggest you make these two changes:

1 - Add this line to your requirements.txt file:

uvicorn

2- Then add the first line and the two last lines to the end of your api.py file:

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return { "Lux app": "Welcome to Lux app" }

@app.post("/extract_text")
def ali():
    return {"Hello": "World"}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Result of GET /

{"Lux app":"Welcome to Lux app"}

Finally, another alternative would be following the docker guide provided by fastAPI which solves this easily by calling your fastapi module directly with uvicorn. This will achieve the same as above.

Example of Dockerfile:

FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
  • Related