Uvicorn 不会用 CTRL+C 退出

发布于 2025-01-16 23:02:42 字数 597 浏览 6 评论 0原文

我有一个使用 uvicorn 的 Python FastAPI 应用程序。我把它打包在 docker 容器中。当我使用如下命令运行应用程序(在 Windows 10 计算机上的 Power Shell 中)时:docker run -p 8080:8080 my-image-name 我收到以下 uvicorn 启动文本

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)

:按 CTRL+C 终止应用程序,没有任何反应。我总是最终不得不关闭终端才能让它停止。

这是因为它在 docker 容器中运行吗?

我知道我可以在分离模式 (-d) 下运行容器,但有时我想在容器日志发生时查看它们。

如何终止 docker 映像和 uvicorn 进程并保持终端仍在运行?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

够运 2025-01-23 23:02:42

您需要使用 --tty--interactice 运行容器,以便转发您的键盘按下操作。

-t, --tty 分配伪 TTY
-i, --interactive 即使未连接,也保持 STDIN 打开

docker run -ti myapp

此外,您应该确保您的 入口点,如果有的话。

shell 形式可以防止使用任何 CMD 或运行命令行参数,但缺点是您的 ENTRYPOINT 将作为 /bin/sh -c 的子命令启动,该子命令不传递信号。这意味着可执行文件不会是容器的 PID 1 - 并且不会接收 Unix 信号 - 因此您的可执行文件不会从 docker stop 接收 SIGTERM 。

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

顺便说一句,关闭终端通常不会停止容器。在执行 docker ps 时,您应该仍然会看到它在运行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文