Uvicorn won't quit with CTRL+C
Asked Answered
N

1

6

I have a Python FastAPI app that is using uvicorn. I have it packaged in docker container. When I run the app (in Power Shell on my Windows 10 machine) with a command like this: docker run -p 8080:8080 my-image-name I get the following uvicorn startup text:

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

When I press CTRL+C to kill the app, nothing happens. I always end up having to close the terminal to get it to stop.

Is this due to the fact that it's running in a docker container?

I know I can run the container in detached mode (-d), but sometimes I want to watch the container logs as they happen.

How can I kill the docker image and uvicorn process AND keep the terminal still running?

Neomineomycin answered 25/3, 2022 at 17:18 Comment(0)
F
9

You need to run the container with --tty and --interactice so that your keyboard presses are forwarded.

-t, --tty Allocate a pseudo-TTY
-i, --interactive Keep STDIN open even if not attached

docker run -ti myapp

Additionally, you should make sure that you don't use shell syntax for your entrypoint, if you have one.

The shell form prevents any CMD or run command line arguments from being used, but has the disadvantage that your ENTRYPOINT will be started as a subcommand of /bin/sh -c, which does not pass signals. This means that the executable will not be the container’s PID 1 - and will not receive Unix signals - so your executable will not receive a SIGTERM from docker stop .

ENTRYPOINT ["uvicorn"]
CMD ["app.py"]

On a side note, closing the terminal, doesn't stop the container, normally. You should still see it running when doing docker ps.

Fleeting answered 25/3, 2022 at 17:25 Comment(1)
This looked promising but for me even with -it for podman run and JSON-array form for my ENTRYPOINT, uvicorn does not exit with Ctrl+C.Montero

© 2022 - 2024 — McMap. All rights reserved.