Eric
Eric

Reputation: 2390

How can I listen for signals from Docker in .Net Core Executable?

I have a console application written in .Net Core. I will be running this in a Docker container. I would like to gracefully stop the process when a docker stop command is given, rather than just letting the process get killed in the middle of doing something. Is there a way that I can listen for this signal from within the console application? Before containers, I would just have the console app listen for something to be typed in the console window. If there is a way to have docker send a message through standard input, I could work with that, I just do not know enough about Docker, yet, to know what is possible.

Upvotes: 3

Views: 602

Answers (2)

Eric
Eric

Reputation: 2390

My solution is going to end up being to not use a console application, after all. I learned that if I create a web project, I can tell when the container has requested a shutdown with the ApplicationStopping CancellationToken in the website's Startup. So, rather than having the container start up a long running console application, it will just host a website that has no web content. The website will just start up my long running process, and when the container sends a signal to the website that it is shutting down, my process can gracefully stop.

public void Configure(IApplicationBuilder app
                , IHostingEnvironment env
                , IApplicationLifetime applicationLifetime)
{
    applicationLifetime.ApplicationStarted.Register(ApplicationStarted);
    applicationLifetime.ApplicationStopping.Register(ApplicationStopping);
    applicationLifetime.ApplicationStopped.Register(ApplicationStopped);
}

Upvotes: 2

Boggin
Boggin

Reputation: 3416

You can pass a command to a running process in a Docker container using docker exec

Upvotes: 0

Related Questions