How to do gracefully shutdown on dotnet with docker? How to do gracefully shutdown on dotnet with docker? docker docker

How to do gracefully shutdown on dotnet with docker?


In .NET Core 2.0, you can use the AppDomain.CurrentDomain.ProcessExit event, which works fine on Linux in Docker. AssemblyLoadContext.Default.Unloading probably works as well, even before .NET Core 2.0.


System.Console has an event called CancelKeyPress. I believe this is fired when a sigint event is passed into dotnet.

System.Console.CancelKeyPress += (s,e) => { /* do something here */};


Using 2.0.0-preview2-006497 I did some testing, and now the AssemblyLoadContext.Default.Unloading is fired when Docker sends a SIGTERM/SIGINT to the container.

Example code looks like:

System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += ctx =>{    // code here...};

See also this issue for some details: https://github.com/aspnet/Hosting/issues/870