Asp.net core Kubernetes job set to failed status on exception

12/18/2019

I have a Kubernetes job running a BackgroundService in Asp.net Core.

After doing some processing the BackgroundService initiates a shutdown by calling StopApplication.

Is there a way to shutdown the application and set the Kubernetes job to failed status when there is an exception in a BackgroundService?

-- user2596613
asp.net-core
kubernetes

1 Answer

12/18/2019

"Is there a way to shutdown the application and set the Kubernetes job to failed status ... ?"

Yes, by anticipating that your application will exit with non-zero exit code when encountering an exception. That's the way how Kubernetes Job's final status is determined.

In other words, if container's process finishes with non-zero code, it causes Pod to terminate and eventually the Job status becomes 'Failed'.

In case of stopping ASP.NET Core Application programmatically, with 'StopApplication()' method, it exits with '0' exit code (example usage here).

Possible solution:

You program needs to handle an exception, even like graceful shutdown = StopApplication(), by explicitly setting an exit code to non-zero one beforehand ([1,250]).

Pseudo code:

        catch (Exception ex)
        {
            _logger.LogError(ex, "Worker process caught exception");

            Environment.ExitCode = 1;
        }
        finally
        {
            applicationLifetime.StopApplication();
        }

based on example here.

-- Nepomucen
Source: StackOverflow