Azure Web App Windows容器优雅关机前被终止如何设置等待时长
Azure App Service Windows容器优雅关机时长配置方案
代码修正(先解决示例代码的语法错误)
你提供的代码存在一处语法笔误,修正后可正常注册系统关机事件监听:
using System; using System.Runtime.InteropServices; using System.Threading; namespace delayed_shutdown { class Program { public enum CtrlTypes { CTRL_C_EVENT = 0, CTRL_BREAK_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT = 5, CTRL_SHUTDOWON_EVENT } [DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool Add); public delegate bool HandlerRoutine(CtrlTypes CtrlType); public static volatile HandlerRoutine handlerRoutine = new HandlerRoutine(ConsoleCtrlCheck); public static volatile ManualResetEvent exitEvent = new ManualResetEvent(false); public static bool ConsoleCtrlCheck(CtrlTypes ctrlType) { switch (ctrlType) { case CtrlTypes.CTRL_C_EVENT: Console.WriteLine("CTRL_C received"); exitEvent.Set(); return true; case CtrlTypes.CTRL_CLOSE_EVENT: Console.WriteLine("CTRL_CLOSE received"); exitEvent.Set(); return true; case CtrlTypes.CTRL_BREAK_EVENT: Console.WriteLine("CTRL_BREAK received"); exitEvent.Set(); return true; case CtrlTypes.CTRL_LOGOFF_EVENT: Console.WriteLine("CTRL_LOGOFF received"); exitEvent.Set(); return true; case CtrlTypes.CTRL_SHUTDOWON_EVENT: Console.WriteLine("CTRL_SHUTDOWN received"); exitEvent.Set(); return true; default: return false; } } static int Main(string[] args) { if (!SetConsoleCtrlHandler(handlerRoutine, true)) { Console.WriteLine("Error setting up control handler... :("); return -1; } Console.WriteLine("Waiting for control event..."); exitEvent.WaitOne(); var i = 60; Console.WriteLine($"Exiting in {i} seconds..."); while (i > 0) { Console.WriteLine($"{i}"); Thread.Sleep(TimeSpan.FromSeconds(1)); i--; } Console.WriteLine("Goodbye"); return 0; } } }
配置延长容器停止等待时长
Azure App Service Windows容器默认停止超时仅为1秒,可通过添加应用配置项自定义超时时间:
- 进入对应Web App的Azure门户管理页,打开「配置」-「应用程序设置」
- 新增配置项:
- 键:
WEBSITE_CONTAINER_START_STOP_TIMEOUT_SECONDS - 值:你需要的最大等待秒数,建议比你的业务逻辑执行最大时长多预留10%的余量,比如你的关机逻辑需要60秒执行完成,可设为
70
- 键:
- 保存配置后等待Web App重启生效
如果你使用Hyper-V隔离模式的Windows容器,该配置的最大生效值为120秒,超过部分会被自动截断;进程隔离模式下最大支持1800秒(30分钟)。
命令行配置方式(az cli)
可直接通过Azure命令行工具批量配置:
az webapp config appsettings set --name <你的WebApp名称> --resource-group <你的资源组名称> --settings WEBSITE_CONTAINER_START_STOP_TIMEOUT_SECONDS=70
验证逻辑
配置生效后,Azure App Service在触发容器停止操作时,会先给容器发送对应关闭事件,等待你设置的超时时间到期后,才会强制终止容器,你的优雅关机逻辑可以在等待窗口内正常执行完成。
内容的提问来源于stack exchange,提问作者Rasmus-E
相关产品推荐
相关产品推荐

