Search code examples
nginx.net-corekestrel-http-server

How to host ASP.NET Core 2.0 (Kestrel) with Unix domain socket behind a nginx proxy?


I am current using ASP.NET Core 2.0 behind nginx through HTTP requests in Ubuntu 16.

And I'd like to switch to Unix domain socket.

In my Program.cs I have:

var host = default(IWebHost);
var builder = new WebHostBuilder()
    .UseKestrel(opt =>
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && settings.Config.ListenUnixSocket)
        {
            opt.ListenUnixSocket("/tmp/api.sock");
        }
    })
    .Configure(app =>
    {
        app.Map("/health", b => b.Run(async context =>
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            await context.Response.WriteAsync("Ok");
        }));
    });

if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || !settings.Config.ListenUnixSocket)
{
    host = builder.UseUrls("http://0.0.0.0:5501").Build();
}
else
{
    host = builder.Build();
}

host.Run();

And, at Nginx:

location /health {
  #proxy_pass http://127.0.0.1:5501;
  proxy_pass http://unix:/tmp/api.sock:/;
}

Running it using the default TCP socket works, but switching to Unix domain sockets, I got a 502 error.

Do I need any specific module at nginx? What I am doing wrong?


Solution

  • Aspnetcore will create api.socket when its running but Nginx must have permission to write.

    So, if you don't know what user nginx uses, execute:

    ps aux | grep nginx
    

    You'll get something this in the terminal:

    root      5005  0.0  0.2 125116  1460 ?        Ss   20:12   0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
    www-data  5006  0.0  0.6 125440  3260 ?        S    20:12   0:00 nginx: worker process
    root      5173  0.0  0.1  14516   920 pts/0    S+   20:17   0:00 grep --color=auto nginx
    

    Then you set the permission:

    sudo chown www-data:www-data /tmp/api.sock
    

    And, that's it!