服務器維護CentOS 7環(huán)境下使用Nginx托管.Net Core應用程序
2020-06-07 13:44 作者:admin
如何做好
服務器維護?北京艾銻無限科技與你談談IT人員必須知道的
服務器維護信息
服務器維護小知識一、安裝.Net Core
參考官方文檔:
https://www.microsoft.com/net/core#linuxcentos
服務器維護小知識服務器維護小知識1、添加dotnet產品Feed
在安裝.NET Core之前,您需要注冊Microsoft產品Feed。這只需要做一次。首先,注冊Microsoft簽名密鑰,然后添加Microsoft產品Feed
sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
sudo sh -c 'echo -e "[packages-microsoft-com-prod]\nname=packages-microsoft-com-prod \nbaseurl=https://packages.microsoft.com/yumrepos/microsoft-rhel7.3-prod\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/dotnetdev.repo'
服務器維護小知識2、安裝.NET Core SDK
sudo yum update
sudo yum install libunwind libicu
sudo yum install dotnet-sdk-2.0.0
之后運行命令
dotnet --info
可以查看安裝是否成功。至此,.Net Core的安裝就完成了。
當然,也可以使用解壓安裝。到
https://www.microsoft.com/net/download/linux 下載
CentOS7對應的sdk壓縮包,之后解壓到自定義的安裝路徑。
sudo mkdir -p /opt/dotnet && sudo tar zxf dotnet.tar.gz -C /opt/dotnet
# 可以設置一下環(huán)境變量,也可以采用下面的方式建立軟鏈接,因為 /usr/local/bin 默認包含于$PATH中
sudo ln -s /opt/dotnet/dotnet /usr/local/bin
# 之后運行查看安裝結果
dotnet --info
服務器維護小知識二、編譯運行項目
1、新建一個mvc項目
dotnet new mvc -o ntmvc
查看ntmvc文件夾 ,可以發(fā)現,一個mvc項目的模板已經建好了,如下:
2、修改 Startup.cs 文件
可以使用vscode直接修改遠程計算機或者是虛擬機中的文件,具體參考
http://www.linuxidc.com/Linux/2017-10/147241.htm
由于后面要用到nginx搭建反向代理,在此處修改一下Startup.cs文件中的代碼,添加引用
using Microsoft.AspNetCore.HttpOverrides;
之后再在 Startup.cs 文件的
Configure 方法中添加一段代碼(具體參見下面完整的Startup.cs文件):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
//添加引用
using Microsoft.AspNetCore.HttpOverrides;
namespace ntmvc
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//添加下面的代碼
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
}
}
}
3、生成項目
首先切換到項目目錄ntmvc,之后運行下面的命令
dotnet publish -c Release
服務器維護小知識 運行命令之后,項目目錄中會多出一個
bin文件夾
服務器維護小知識 在bin文件夾中會包含Release文件夾,在Release文件夾中的netcoreapp2.0文件夾中,會包含可以發(fā)布的內容,即
publish文件夾。
服務器維護小知識注:publish文件夾之外的內容,同我們運行 dotnet run 命令時所生成的文件是相同的,只不過Debug文件夾換成了自己命名的Release文件夾而已。換句話說,運行dotnet publish -c Release 比運行 dotnet run 多了一個publish文件夾,而這個文件夾正是所要發(fā)布的內容
服務器維護小知識4、運行項目
切換到publish文件夾,運行命令
dotnet nmvc.dll
如下圖所示:
服務器維護小知識 5、項目的開機自動運行
接下來設置項目的開機自動啟動,在
/etc/systemd/system/ 中新建一個服務文件
vim /etc/systemd/system/kestrel-ntmvc.service
內容如下:
[Unit]
Description=Example .NET Web MVC Application running on Centos7
[Service]
WorkingDirectory=/root/ntmvc
ExecStart=/usr/bin/dotnet /root/ntmvc/bin/Release/netcoreapp2.0/publish/ntmvc.dll
Restart=always
RestartSec=10 # Restart service after 10 seconds if dotnet service crashes
SyslogIdentifier=dotnet-example
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
[Install]
WantedBy=multi-user.target
之后保存,運行以下命令:
systemctl enable kestrel-ntmvc.service
systemctl start kestrel-ntmvc.service
systemctl status kestrel-ntmvc.service
注意:如果檢查到錯誤,需要修改 kestrel-ntmvc.service 文件,修改正確之后,需要運行以下命令重新啟動:
systemctl daemon-reload
systemctl restart kestrel-ntmvc.service
到此為止,一個簡單的項目就可以正常訪問了。接下來,對項目進行改造,引入nginx的使用。
服務器維護小知識三、編譯安裝nginx
1、安裝依賴項
yum -y install gcc gcc-c++ pcre pcre-devel openssl openssl-devel zlib zlib-devel
2、下載安裝包
最新的下載地址請到官網獲取。
wget http://nginx.org/download/nginx-1.13.5.tar.gz
3、解壓
mkdir nginxfiles
tar -zxvf nginx-1.13.5.tar.gz -C nginxfiles
4、切換目錄
cd nginxfiles/
cd nginx-1.13.5/
5、編譯安裝
執(zhí)行以下命令
# 配置:這里需要安裝額外的模塊
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-stream --with-mail=dynamic
# 編譯
make
# 安裝
make install
6、創(chuàng)建軟鏈接
ln -s /usr/local/nginx/sbin/nginx /usr/local/bin
如上所述,這樣可以不用再設置環(huán)境變量。
服務器維護小知識四、證書相關
為了增強項目的安全性,有時需要將http訪問轉為https訪問。通過對nginx中ssl模塊進行設置,可以實現這一點。
通常,這需要向CA申請安全證書(常用免費證書:
https://letsencrypt.org/ )。
由于這里僅作測試用,因此使用自己生成的證書。
1、證書的生成
在root目錄下建立certs文件夾,切換到該文件夾,依次運行以下命令:
# 建立服務器私鑰(過程需要輸入密碼,請記住這個密碼)生成RSA密鑰
openssl genrsa -des3 -out testcert.key 1024
# 生成一個證書請求 需要依次輸入國家,地區(qū),組織,email,common name等,common name可以寫你的名字或者域名。如果為了https申請,必須和域名吻合,否則會引發(fā)瀏覽器警報。
openssl req -new -key testcert.key -out testcert.csr
# 生成不需要密碼的key
openssl rsa -in testcert.key -out testcert_nopwd.key
# 生成crt文件
openssl x509 -req -days 365 -in testcert.csr -signkey testcert_nopwd.key -out testcert.crt
2、證書的位置
將證書復制到 /etc/ssl/certs/ 目錄
cp testcert.crt /etc/ssl/certs/
cp testcert_nopwd.key /etc/ssl/certs/testcert.key
如下圖:
3、迪菲-赫爾曼密鑰交換
一般來說,之后修改nginx.conf配置文件就可以了。為了進一步增強安全性,可以進行迪菲-赫爾曼密鑰交換,在 /etc/ssl/certs/ 目錄中
openssl dhparam -out dhparam.pem 4096生成文件
服務器維護小知識五、nginx配置文件相關
1、自定義 proxy.conf 文件
在 /usr/local/nginx/cong/ 目錄下新建 proxy.conf 文件,后面會在nginx.conf中引用此文件。
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;
2、修改 nginx.conf 文件
修改 /usr/local/nginx/cong/ 目錄下的nginx.conf文件,著重點已經使用了不同的顏色進行標注。
worker_processes 1;
events {
worker_connections 1024;
}
http {
include proxy.conf;
include mime.types;
default_type application/octet-stream;
limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
server_tokens off;
sendfile on;
#tcp_nopush on;
keepalive_timeout 29;
client_body_timeout 10;
client_header_timeout 10;
send_timeout 10;
upstream ntmvc{
server localhost:5000;
}
server {
listen 80;
add_header Strict-Transport-Security max-age=15768000;
return 301 https://$host$request_uri;
}
# HTTPS server
#
server {
listen *:443 ssl;
server_name localhost;
ssl_certificate /etc/ssl/certs/testcert.crt;
ssl_certificate_key /etc/ssl/certs/testcert.key;
ssl_protocols TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_dhparam /etc/ssl/certs/dhparam.pem;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_ecdh_curve secp384r1;
ssl_session_cache shared:SSL:10m;
ssl_session_tickets off;
ssl_stapling on; #ensure your cert is capable
ssl_stapling_verify on; #ensure your cert is capable
add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
#Redirects all traffic
location / {
proxy_pass http://ntmvc;
limit_req zone=one burst=10 nodelay;
limit_req_status 503;
}
}
}
服務器維護小知識六、nginx 開機自動啟動
# 設置nginx自啟動,在/lib/systemd/system/ 目錄下創(chuàng)建一個服務文件
vim /lib/systemd/system/nginx.service
注意,這里的路徑是 /lib/systemd/system/ ,而非上面ntmvc項目自啟動服務文件所在的 /etc/systemd/system/ 這一點值得注意。
內容如下:
[Unit]
Description=nginx - high performance web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
[Install]
WantedBy=multi-user.target
文件編輯完成之后,運行以下命令啟動服務:
systemctl enable nginx.service
# 啟動nginx服務
systemctl start nginx.service
# 查看狀態(tài)
systemctl status nginx.service
這里之所以有一個警告,是因為我們使用的證書是自己生成的,而不是正式的證書。
通常,對配置文件修改后需要重啟服務,執(zhí)行以下命令:
# 如果修改了文件,這個是必須的
systemctl daemon-reload
# 重新啟動服務
systemctl restart nginx.service
服務器維護小知識七、防火墻相關
以下的三個端口是必須要開的 ,其他的視情況而定。
#端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=5000/tcp --permanent
firewall-cmd --zone=public --add-port=443/tcp --permanent
#開端口后必須重新加載
firewall-cmd --reload
# 查看所有打開的端口:
firewall-cmd --list-ports
重新加載并顯示端口
服務器維護小知識八、訪問相關
以上的配置完成之后,如果環(huán)境使用的是真實的物理機,或者是橋接的虛擬機,直接訪問ip地址就可以了。
如果是NAT連接的虛擬機,需要進行端口映射。本實驗使用的VirtualBox 搭建的虛擬機,以此為例,按下圖進行設置即可。
如果是直接在虛擬機中進行瀏覽,瀏覽127.0.0.1 或者localhost 即可。
服務器維護小知識如果是從主機進行訪問,可在主機的瀏覽器中輸入https://192.168.56.1:1518,即可映射到虛擬機的443端口,這樣就可以通過https進行訪問虛擬機中的ntmvc項目。
服務器維護小知識由于在nginx.conf中配置了
add_header Strict-Transport-Security max-age=15768000; 即只能允許https訪問, 因此輸入http://192.168.56.1:1518 會提示錯誤。
服務器維護小知識正常的訪問結果如下圖所示(谷歌瀏覽器),之所以會出現這樣的提示,是因為所用的證書是自己生成的。
繼續(xù)訪問即可訪問ntmvc中的頁面,如下圖:
IT運維 我們選擇
北京艾銻無限
以上文章由北京艾銻無限科技發(fā)展有限公司整理