1. 程式人生 > >使用 Nginx 在 Ubuntu 16.04 上托管 ASP.NET Core

使用 Nginx 在 Ubuntu 16.04 上托管 ASP.NET Core

mage 常見 div 啟動 environ 轉發 create seconds ron

使用 Nginx 在 Ubuntu 16.04 上托管 ASP.NET Core


準備工作

服務器主機:騰訊雲主機 Ubuntu 16.04 64位
客戶端軟件:putty.exe; WinSCP 5.13.2

在 Ubuntu 中安裝 ASP.NET Core

微軟在 .NET Core指南 提供了在不同操作系統中安裝運行 ASP.NET Core 的幫助文檔,請選擇 linux-prerequisites 部分,並找到和自己服務器所安裝操作系統相同的內容進行安裝即可。

註冊Microsoft密鑰為被信任的

在Linux環境中運行ASP.NET Core網站,我們需要安裝.NET Core運行時(當然也可以自己實現.NET Core程序的宿主)。
在安裝 .NET 之前,需要註冊Microsoft密鑰,註冊產品存儲庫,並安裝所需的依賴項。這只需要在每臺機器上完成一次。
打開命令提示符並運行以下命令:

wget -q packages-microsoft-prod.deb https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb

.NET Core Runtime 和 .NET Core SDK 的區別:

  • .NET Core = 應用運行依賴的 .NET Core Runtime
  • .NET Core SDK = 使用 .NET Core 開發應用 .NET Core Runtime 和 SDK+CLI(Software Development Kit/Command Line Interface) 工具

安裝 .NET Core SDK

更新可用於安裝的產品,然後安裝 .NET SDK。
在命令提示符中,運行以下命令:

sudo apt-get install apt-transport-https
sudo apt-get update
sudo apt-get install dotnet-sdk-2.1.105

.NET Core SDK 可能會發布新的版本,將 dotnet-sdk-2.1.105 更新為對應的版本號即可。

檢查安裝情況

在終端輸入以下命令檢查安裝是否成功:

dotnet --version

ASP.NET Core 示例程序

創建程序目錄

在用戶的主目錄(/home/ubuntu/

)中創建新目錄 firstapp,然後進入該目錄:

mkdir firstapp
cd firstapp

創建示例程序

直接使用 .NET Core 的命令創建一個 ASP.NET Core 示例網站應用程序,在目錄 /home/ubuntu/firstapp 執行命令:

dotnet new mvc

命令運行結果:

The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.

Processing post-creation actions...
Running ‘dotnet restore‘ on /home/ubuntu/firstapp/firstapp.csproj...
  Restoring packages for /home/ubuntu/firstapp/firstapp.csproj...
  Generating MSBuild file /home/ubuntu/firstapp/obj/firstapp.csproj.nuget.g.props.
  Generating MSBuild file /home/ubuntu/firstapp/obj/firstapp.csproj.nuget.g.targets.
  Restore completed in 857.05 ms for /home/ubuntu/firstapp/firstapp.csproj.
  Restore completed in 24.33 ms for /home/ubuntu/firstapp/firstapp.csproj.

Restore succeeded.

還原整個項目的依賴庫

執行命令:

dotnet restore

命令運行結果:

Restore completed in 59.28 ms for /home/ubuntu/firstapp/firstapp.csproj.
Restore completed in 10.83 ms for /home/ubuntu/firstapp/firstapp.csproj.

更改 MVC 項目默認端口號

為防止沖突,先將 ASP.NET Core MVC 程序的默認端口號改為9000。更改端口號的辦法:打開項目的 program.cs 文件,添加以下有註釋的兩行

    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://*:9000")   //指定端口號
                .UseKestrel()  //使用 Kestrel 服務器
                .Build();
    }

發布項目

執行命令:

dotnet publish -c release

命令運行結果:

Microsoft (R) Build Engine version 15.7.177.53362 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 62.23 ms for /home/ubuntu/firstapp/firstapp.csproj.
  Restore completed in 11.54 ms for /home/ubuntu/firstapp/firstapp.csproj.
  firstapp -> /home/ubuntu/firstapp/bin/release/netcoreapp2.0/firstapp.dll
  firstapp -> /home/ubuntu/firstapp/bin/release/netcoreapp2.0/publish/

命令執行完畢後,項目被發布到 /home/ubuntu/firstapp/bin/release/netcoreapp2.0/publish/ 目錄下,這個路徑太長,訪問的時候比較不方便,所以可以創建一個項目運行的目錄:/var/www/firstapp/,並將剛才項目發布後的內容復制到該目錄中。
創建項目運行目錄,執行命令:

sudo mkdir /var/www/firstapp

將發布後的結果復制到運行目錄中,執行命令:

sudo scp -r /home/ubuntu/firstapp/bin/release/netcoreapp2.0/publish/* /var/www/firstapp

進入運行目錄,運行、測試項目:

 cd /var/www/firstapp
 dotnet firstapp.dll

程序運行結果:

Hosting environment: Production
Content root path: /var/www/firstapp
Now listening on: http://[::]:9000
Application started. Press Ctrl+C to shut down.

根據以上提示,通過地址 http://localhost:9000/http://127.0.0.1:9000 就可以訪問到網站。但是,這個只能在服務器網站內部訪問,通過外網並不能訪問的。

使用 Nginx 反向代理

反向代理是為動態 web 應用程序提供服務的常見設置。 反向代理終止 HTTP 請求,並將其轉發到 ASP.NET 核心應用程序。

安裝 Nginx

安裝命令:

sudo apt-get install nginx

因為是首次安裝 Nginx,通過運行以下命令顯式啟動:

sudo service nginx start

在瀏覽器地址欄中輸入類似於 http://192.168.XXX.XXX:9000 的IP地址或 http://域名:9000 就可以顯示 Nginx 的默認登陸頁了。

配置 Nginx

若要將 Nginx 配置為轉發請求向 ASP.NET Core 應用程序的反向代理,修改 /etc/nginx/sites-available/default。 在文本編輯器中打開它,並將內容替換為以下內容:

server {
    listen        80;
    server_name   example.com *.example.com;
    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 $http_host;
        proxy_cache_bypass $http_upgrade;
    }
}

Nginx 接受主機標頭使用的端口 80 上的公共流量, Nginx 將匹配的請求轉發到在 Kestrel http://localhost:9000
測試配置:

sudo nginx -t

顯示結果如下所示:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

重新加載配置:

sudo nginx -s reload

在瀏覽器中直接輸入你的服務器IP地址並訪問,就可以看到 ASP.NET Core MVC 應用程序運行的結果了。
技術分享圖片

監視應用程序

服務器已設置為轉發到發出的請求 http://<serveraddress>:80 Kestrel 在上運行 ASP.NET Core 應用到 http://127.0.0.1:9000。 但是,Nginx 未設置來管理 Kestrel 過程。 systemd可以用於創建服務文件以啟動和監視基礎的 web 應用。 systemd 是一個 init 系統,可以提供用於啟動、停止和管理進程的許多強大的功能。

創建服務文件

創建服務定義文件:

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

下面是應用程序的示例服務文件:

[Unit]
Description=firstapp .NET MVC App running on Ubuntu

[Service]
WorkingDirectory=/var/www/firstapp
ExecStart=/usr/bin/dotnet /var/www/firstapp.dll
Restart=always
RestartSec=10  # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

保存該文件並啟用該服務。

systemctl enable kestrel-firstapp.service

啟動服務並驗證它正在運行。

systemctl start kestrel-firstapp.service
systemctl status kestrel-firstapp.service

使用 WinSCP 管理服務器

騰訊雲主機提供了 Web 界的命令窗口,不過這個窗口不支持粘貼,所以在編輯需要輸入很多內容的配置文件時,比較不方便。雖然使用 putty.exe 可以進行復制粘貼,但使用 Linux 的 vi/vim 進行文本編輯估計也是很多不熟悉終端操作方式的人的惡夢。
WinSCP 是一個 Windows 環境下使用 SSH 的開源圖形化 SFTP 客戶端。同時支持 SCP 協議,它的主要功能就是在本地與遠程計算機間安全的復制文件,同時也可以在 WinSCP 上直接對 Ubuntu 中的文件進行編輯。

WinSCP 中的管理員限

在編輯 Ubuntu 中某些服務的配置文件、或是上傳文件到非用戶目錄時,需要使用 root 權限,比較簡單的做法是開啟 root 賬號,在需要使用管理員權限的地方使用 root 登錄進行操作

啟用 root 賬號

執行命令:

sudo passwd root

按提示輸入 root 賬號的密碼,如果不怕安全問題,可以使用和 ubuntu 賬號一樣的密碼,方便使用。

Password: //輸入密碼
Enter new UNIX password: //提示輸入新的root帳戶密碼
Retype new UNIX password:  //再輸入一次確認密碼

修改成功之後你就可以使用root賬號了.

WinSCP 使用 root 連接服務器

技術分享圖片

在 WinSCP 中編輯配置文件

技術分享圖片

配置文件的編輯窗口

技術分享圖片

管理服務器中的文件

使用 root 賬號登錄,左邊窗口定位到要上傳文件(如在 Visual Studio 中編輯並發布的項目),右邊窗口選到服務器中上傳的目錄,把文件從左邊拖到右邊就可以 。

使用 Nginx 在 Ubuntu 16.04 上托管 ASP.NET Core