捕获发送到容器实例的终止信号 (SIGTERM)

Cloud Run 在容器实例终止(由于缩减或删除了修订版本等事件)之前将 SIGTERM 信号发送到该容器实例。通过处理此信号,您现在可以正常终止应用并执行一些清理任务,而不是突然关停容器。

代码示例

Go

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// Create channel to listen for signals.
var signalChan chan (os.Signal) = make(chan os.Signal, 1)

func main() {
	// Determine port for HTTP service.
	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("defaulting to port %s", port)
	}

	srv := &http.Server{
		Addr:    ":" + port,
		Handler: http.HandlerFunc(handler),
	}

	// SIGINT handles Ctrl+C locally.
	// SIGTERM handles Cloud Run termination signal.
	signal.Notify(signalChan, syscall.SIGINT, syscall.SIGTERM)

	// Start HTTP server.
	go func() {
		log.Printf("listening on port %s", port)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatal(err)
		}
	}()

	// Receive output from signalChan.
	sig := <-signalChan
	log.Printf("%s signal caught", sig)

	// Timeout if waiting for connections to return idle.
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// Add extra handling here to clean up resources, such as flushing logs and
	// closing any database or Redis connections.

	// Gracefully shutdown the server by waiting on existing requests (except websockets).
	if err := srv.Shutdown(ctx); err != nil {
		log.Printf("server shutdown failed: %+v", err)
	}
	log.Print("server exited")
}

Java

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/** Register shutdown hook */
@PreDestroy
public void tearDown() {
  logger.info(IdpSqlApplication.class.getSimpleName() + ": received SIGTERM.");
  // Spring Boot closes JDBC connections.
  // https://docs.spring.io/spring-framework/docs/3.0.x/spring-framework-reference/html/jdbc.html

  // Flush async logs if needed
  // Current Logback config defaults to immediate flushing of all logs
}

Node.js

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

// Clean up resources on shutdown
process.on('SIGTERM', () => {
  logger.info(`${pkg.name}: received SIGTERM`);
  closeConnection();
  logger.end();
  logger.on('finish', () => {
    console.log(`${pkg.name}: logs flushed`);
    process.exit(0);
  });
});

Python

如需向 Cloud Run 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

def shutdown_handler(signal: int, frame: FrameType) -> None:
    """Gracefully shutdown app."""
    logger.info("Signal received, safely shutting down.")
    database.shutdown()
    middleware.logging_flush()
    print("Exiting process.", flush=True)
    sys.exit(0)


if __name__ == "__main__":
    # handles Ctrl-C locally
    signal.signal(signal.SIGINT, shutdown_handler)

    app.run(host="127.0.0.1", port=8080, debug=True)
else:
    # handles Cloud Run container termination
    signal.signal(signal.SIGTERM, shutdown_handler)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器