aspnetcore 2.0 kestrel unix socket behind nginx

ぃ、小莉子 提交于 2020-04-30 08:11:18

问题


I am current using aspnet core behind nginx through http requests in Ubuntu 16.

And I'd like to switch to unix 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 http works, but, chaning to socket I got a 502 error.

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


回答1:


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!




回答2:


@Apolineo correctly identified that the Unix socket's permissions need to be opened up to allow other users to connect to the socket.

However, a better solution than manually setting the permissions is to do it programmatically from Main immediately after the socket is created.

Example solution in this answer.



来源:https://stackoverflow.com/questions/49905724/aspnetcore-2-0-kestrel-unix-socket-behind-nginx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!