###### tags: `Ubuntu`,`Asp.net Core`, `Nginx` # Ubuntu 20.04 + Nginx + ASP.Net core 5 1. 先設定一個群組跟使用者, 用來執行web app ``` javascript=1 sudo groupadd mvc sudo useradd -g mvc mvc ``` 2. 在Nginx資料夾下建立 web app 在這取名 ==api== 資料夾 , 並調整使用者帳號跟權限 ``` javascript=1 sudo mkdir /var/www/api sudo chown -R mvc:mvc /var/www/api sudo chmod -R 755 /var/www/api/ ``` 3. 先回到 C# core 5 的專案內開啟 Startup.cs 找到下面這兩行把它刪除 (因為不使用 https 所以先把它刪除) (visual studio) ``` csharp=1 app.UseHsts(); app.UseHttpsRedirection(); ``` 4. 建置Web App (visual studio) ``` csharp=1 dotnet publish -c Release -r ubuntu.20.04-x64 ``` 5. 把建置出來的檔案 放到 Ubuntu 建立的資料夾裡面 ==bin/Debug/net5.0/以下的所有檔案== 6. 新增一個 Nginx 的 site available 設定 ``` javascript=1 sudo nano /etc/nginx/sites-available/api ``` 內容 ``` javascript=1 server { listen 80 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; } } ``` ==proxy_pass 這裡的 port 要看 Web App 運行時的 port 而定== 7. 把剛才建立的 site available 設定檔,連結到 site enabled 裡面 ``` javascript=1 sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled/ ``` 8. 檢查 Ngixn 的設定檔 ``` javascript=1 sudo nginx -t ``` 9. 如果沒有問題的話就重啟 Nginx 的服務 ``` javascript=1 sudo systemctl restart nginx ``` 10. 如果有設定防火牆,記得 allow ==你所設定的== port ``` javascript=1 sudo ufw allow 80 ``` 11. 測試 到 /var/www/api 資料夾,先手動執行 Web App 測試一下 ``` javascript=1 dotnet EquipmentGroup.dll ``` 12. 因不可能每次都手動運行 Web App, 所以要做一個自動執行的服務, 先暫停剛剛的測試然後建立一個 mvc.service的副物 ``` javascript=1 sudo nano /etc/systemd/system/mvc.service ``` 內容 ``` javascript=1 [Unit] Description=mvc web app [Service] WorkingDirectory=/var/www/api ExecStart=/usr/bin/dotnet /var/www/mvc/net5.0/EquipmentGroup.dll # 這裡的路徑和名稱,請自己調整 Restart=always # Restart service after 10 seconds if the dotnet service crashes: RestartSec=10 SyslogIdentifier=dotnet-mvc User=mvc # 指定執行的使用者為建立的 mvc Environment=ASPNETCORE_ENVIRONMENT=Production Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false [Install] WantedBy=multi-user.target ``` ㄋ 13. 啟用 mvc.service ``` javascript=1 sudo systemctl enable mvc ``` 14. 執行 mvc.service ``` javascript=1 sudo systemctl start mvc ``` 15. 查看 mvc.service 狀態 ``` javascript=1 sudo systemctl status mvc ``` ### ==Finish== - [參考連結](https://blog.cashwu.com/blog/ubuntu-asp-net-core-mvc-publish-nginx/)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up