Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I know when Kestrel has started listening?

I need to notify systemd that my service has started up successfully, and a task it needs to run after startup requires that the server is already listening on the target Unix domain socket.

I am using IWebHost::Run to start the server, and that is a blocking call. Additionally, I am unable to find any obvious way to set a delegate or callback event for successful initialization.

Anyone?

like image 645
Rimmel Avatar asked Jun 20 '17 20:06

Rimmel


People also ask

How do I know if my kestrel is running Linux?

Register(() => { /* any code you put here will execute * after the host has started listening */ Console. WriteLine("Kestrel has started listening"); }); /* this is a blocking call. * the start event occurs from "in there" */ app. Run();

How do you start a kestrel?

To start the application from Kestrel webserver click project name menu item in run dropdown like below. ASPNETCoreVS2017Demo is my project name. This will start the app directly form Kestrel webserver. This will start the app with Kestrel webserver and server will start listening to port 5000 by default.

How does a kestrel server work?

Kestrel used as an edge server without a reverse proxy server doesn't support sharing the same IP and port among multiple processes. When Kestrel is configured to listen on a port, Kestrel handles all of the traffic for that port regardless of requests' Host headers.

Should I use Kestrel production?

The recommended way to use Kestrel in a production environment is to place it behind a reverse proxy. The reverse proxy can handle things that Kestrel isn't well suited for—like serving static files, SSL termination, and response compression. The setup is as shown in figure B. 1 on Windows or Linux.


2 Answers

You may use Microsoft.AspNetCore.Hosting.IApplicationLifetime:

/// <summary>
/// Triggered when the application host has fully started and is about to wait
/// for a graceful shutdown.
/// </summary>
CancellationToken ApplicationStarted { get; }

Look into this SO post for the configuration example.

like image 187
Set Avatar answered Sep 30 '22 07:09

Set


  • On .Net Core 1.x it is safe to just run IWebHost.Start() and assume that the server is initialized afterwards (instead of Run() that blocks the thread). Check the source.

    var host = new WebHostBuilder()
        .UseKestrel()
        (...)
        .Build();
    
    host.Start();
    
  • If you are using .NET Core 2.0 Preview 1 (or later), the source is different, the synchronous method is not available anymore so you should await IWebHost.StartAsync() and assume everything is ready afterwards.

like image 40
Gerardo Grignoli Avatar answered Sep 30 '22 06:09

Gerardo Grignoli