46

Nginx 配置内网访问树莓派4 ASP.NET Core 3.0 网站

 4 years ago
source link: https://www.tuicool.com/articles/jANjmey
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

导语

前几天发了两篇《 在树莓派4上安装 .NET Core 3.0 运行时及 SDK 》以及《 “自启动”树莓派上的 .NET Core 3.0 环境 》。其实仍有个坑:我们的网站只能localhost访问,虽然dotnet环境变量可以“自启动”了,但网站本身并且不能随系统自启动。今天我们来看看如何把逼装得更完整一些。

能跑就行:Kestrel Hosting

如果你的要求只是临时内网访问,可以只用 Kestrel 来承载 Web 服务器,只需要给 dotnet 命令一个 --urls 参数即可设置允许访问的主机名和端口号。我不希望限制主机名,所以这里我用了 *。

dotnet Empower.dll --urls "http://*:8080"

现在,你的内网机器就能访问树莓派上的网站了:

vMjMrmQ.png!web

但是这种方式有一定的缺点。比如你的代码写爆了,只要一个exception,dotnet 进程就会结束,你必须手工重启才能继续使用网站。而且 Kestrel 的功能远没有正常的Web服务器强大。因此,在更真实的环境里,我们还是要通过正常的Web服务器(如Nginx)做反向代理,并能自动重启dotnet进程。

使用 Nginx + systemd

首先,安装并启动ngix

sudo apt-get install nginx

sudo /etc/init.d/nginx start

打开配置文件

sudo nano /etc/nginx/sites-available/default

替换为以下内容

server {

listen        80 default_server;

server_name   _;

location / {

proxy_pass         http://localhost:5000;

proxy_http_version 1.1;

proxy_set_header   Upgrade $http_upgrade;

proxy_set_header   Connection keep-alive;

proxy_set_header   Host $host;

proxy_cache_bypass $http_upgrade;

proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_set_header   X-Forwarded-Proto $scheme;

}

}

其中 server_name 设置为 _; 的意思也是不限制主机名访问。 proxy_pass 对应的是 Kestrel 的默认终端地址。

应用设置

sudo nginx -t

sudo nginx -s reload

现在,启动你的 ASP.NET Core 网站,应该能在内网用80端口访问了。

dotnet Empower.dll

ZJNNF3m.png!web

现在,我们还有最后一步,就是让 dotnet 进程一爆就自动重启,这可以借助 systemd 服务实现。

sudo nano /etc/systemd/system/kestrel-empowerapp.service

内容如下

[Unit]

Description=ASP.NET Core 3.0 App - Empower

[Service]

WorkingDirectory=/home/pi/dotnet-playground/empower/portable-fdd

ExecStart=/home/pi/dotnet-arm32/dotnet /home/pi/dotnet-playground/empower/portable-fdd/Empower.dll

Restart=always

# Restart service after 10 seconds if the dotnet service crashes:

RestartSec=10

KillSignal=SIGINT

SyslogIdentifier=dotnet-empower

User=pi

Environment=ASPNETCORE_ENVIRONMENT=Production

Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]

WantedBy=multi-user.target

注意,systemd 要求我们使用绝对路径。

注册,并启动服务:

sudo systemctl enable kestrel-empowerapp.service

sudo systemctl start kestrel-empowerapp.service

sudo systemctl status kestrel-empowerapp.service

UnqUNzZ.jpg!web

现在,试试重启你的树莓派,网站会自动启动,局域网80端口也能访问,代码爆了也能自动重启服务!

关于更详细的配置,可以点击【阅读原文】参考微软官方文档。

b2Q7ryq.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK