如何在 nginx 代理后面使用 Unix 域套接字托管 ASP.NET Core 2.0 (Kestrel)? [英] How to host ASP.NET Core 2.0 (Kestrel) with Unix domain socket behind a nginx proxy?
问题描述
我目前在 Ubuntu 16 中通过 HTTP 请求在 nginx 后面使用 ASP.NET Core 2.0.
I am current using ASP.NET Core 2.0 behind nginx through HTTP requests in Ubuntu 16.
我想切换到 Unix 域套接字.
And I'd like to switch to Unix domain socket.
在我的 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 错误.
Running it using the default TCP socket works, but switching to Unix domain sockets, I got a 502 error.
我需要在 nginx 上使用任何特定模块吗?我做错了什么?
Do I need any specific module at nginx? What I am doing wrong?
推荐答案
Aspnetcore 运行时会创建 api.socket 但 Nginx 必须有写入权限.
Aspnetcore will create api.socket when its running but Nginx must have permission to write.
所以,如果你不知道 nginx 使用的是什么用户,请执行:
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
然后你设置权限:
sudo chown www-data:www-data /tmp/api.sock
而且,就是这样!
这篇关于如何在 nginx 代理后面使用 Unix 域套接字托管 ASP.NET Core 2.0 (Kestrel)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!