Search code examples
dockeruvicorn

How to run Docker app in background instead of output to terminal


I'm running a FastAPI with unicorn in the shell. But when I run it inside docker it still output the output to the shell instead of Docker like this:

INFO:     Started server process [1]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)

How do I make the app output its output to the contain's shell and run the container the in background as a normal Docker container?

Here is the code:

from typing import Optional
import uvicorn
from fastapi import FastAPI
    

app = FastAPI()
    

@app.get("/")
def read_root():
    return {"Hello": "World"}
    
    
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}
    
    
if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")

Here is the Dockerfile:

FROM python:3.9.3-buster
WORKDIR /opt
ADD . .
RUN pip install "poetry==1.1.5"
RUN python -m venv /venv
RUN poetry export -f requirements.txt | /venv/bin/pip install -r /dev/stdin
RUN chmod u+x main.py
CMD ["/venv/bin/python", "main.py", "--port", "5000"]

I run and build the Docker image like this:

docker build -t example00 .
docker run -p 5000:5000 example00

Anyone has any suggestions?


Solution

  • From docker run --help:

    Options:
      -d, --detach                         Run container in background and print container ID
    
    

    So, you can go for docker run -d -p 5000:5000 example00. To check if your container started properly, you can use the container ID returned by -d flag and run:

    docker logs -f <container-ID>
    

    and expect to see your logs (-f flag means Follow log output):

        INFO:     Started server process [1]
        INFO:     Waiting for application startup.
        INFO:     Application startup complete.
        INFO:     Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)
    

    In this case, your CTRL+C will not stop the FastAPI server, it will only cancel the docker logs -f command. If you want to stop the running container, use docker stop <container-ID> instead.