处理 Cloud 运行 容器关闭

Handling a Cloud Run container shutdown

在编写云 运行 服务时,我们开发了一个容器来侦听 PORT 环境变量来处理传入的 HTTP 请求。容器的一个实例启动并处理请求,然后在结束原始请求后存活一段时间,以防有进一步的请求到达。如果没有进一步的请求,GCP 关闭 容器。我在这方面有一个问题。

容器内是否有钩子、信号或其他指示容器正在关闭?

在我的示例中,我的容器想要干净地结束。也许它想关闭连接或执行一些快速缓存刷新。

已找到 运行 云上收集的精彩问答常见问题解答 here。在该常见问题解答中,有一项内容如下:

What is the termination signal for Cloud Run services?

Currently, Cloud Run terminates containers while scaling to zero with unix signal 9 (SIGKILL). SIGKILL is not trappable (capturable) by applications. Therefore, your applications should be okay to be killed abruptly.

相关且重要的条目还显示:

When will my service scale to zero?

Cloud Run does not provide any guarantees on how long it will keep a service "warm". It depends on factors like capacity and Google’s implementation details.

Some users see their services staying warm up to an hour, or longer.


意见

我觉得有趣的是这个故事似乎是直接的SIGKILL。如果我们将 Docker 作为容器环境的基础,我们可以阅读 docker stop 这似乎是干净地停止容器的方法。在它自己的描述中说:

The main process inside the container will receive SIGTERM, and after a grace period, SIGKILL.

这似乎表明对于 正常 Docker 容器停止,进程 运行 容器将收到一个信号。

SIGTERM(unix 信号 15)现已发送到云 运行 服务,如果您在代码中处理该信号,您将有 10 秒的时间来处理关闭任何资源等。

here

Container instances can be shut down at any time. When a container instance needs to be shut down, new incoming requests are routed to other instances and requests currently being processed are given time to complete. The container instance then receives a SIGTERM signal indicating the start of a 10 second period before being shut down (with a SIGKILL signal). During this period, the container instance is allocated CPU and billed. If the container instance does not catch the SIGTERM signal, it is immediately shut down.

(代码图片取自 here