【问题标题】:How to host ASP.NET Core 2.0 (Kestrel) with Unix domain socket behind a nginx proxy?如何在 nginx 代理后面使用 Unix 域套接字托管 ASP.NET Core 2.0 (Kestrel)?
【发布时间】:2018-04-18 17:31:54
【问题描述】:

我目前在 Ubuntu 16 中通过 HTTP 请求在 nginx 后面使用 ASP.NET Core 2.0。

我想切换到 Unix 域套接字。

在我的 Program.cs 我有:

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();

并且,在 Nginx

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

使用默认的 TCP 套接字运行它可以工作,但是切换到 Unix 域套接字,我得到了 502 错误。

我需要 nginx 的任何特定模块吗?我做错了什么?

【问题讨论】:

    标签: nginx .net-core kestrel-http-server


    【解决方案1】:

    Aspnetcore 运行时会创建 api.socket,但 Nginx 必须有写权限。

    所以,如果你不知道 nginx 使用什么用户,请执行:

    ps aux | grep nginx
    

    你会在终端得到这样的东西:

    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
    

    然后你设置权限:

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

    而且,就是这样!

    【讨论】:

      【解决方案2】:

      @Apolineo 正确识别出需要打开 Unix 套接字的权限以允许其他用户连接到该套接字。

      但是,比手动设置权限更好的解决方案是在创建套接字后立即从 Main 以编程方式进行。

      this answer 中的示例解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-19
        • 1970-01-01
        • 2019-04-01
        • 2018-03-02
        • 2019-10-10
        • 2017-05-24
        相关资源
        最近更新 更多