服務(wù)器維護(hù)CentOS 7環(huán)境下使用Nginx托管.Net Core應(yīng)用程序
2020-06-07 13:44 作者:admin
如何做好
服務(wù)器維護(hù)?北京艾銻無限科技與你談?wù)処T人員必須知道的
服務(wù)器維護(hù)信息
服務(wù)器維護(hù)小知識(shí)一、安裝.Net Core
參考官方文檔:
https://www.microsoft.com/net/core#linuxcentos
服務(wù)器維護(hù)小知識(shí)服務(wù)器維護(hù)小知識(shí)1、添加dotnet產(chǎn)品Feed
在安裝.NET Core之前,您需要注冊Microsoft產(chǎn)品Feed。這只需要做一次。首先,注冊Microsoft簽名密鑰,然后添加Microsoft產(chǎn)品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'
服務(wù)器維護(hù)小知識(shí)2、安裝.NET Core SDK
sudo yum update
sudo yum install libunwind libicu
sudo yum install dotnet-sdk-2.0.0
之后運(yùn)行命令
dotnet --info
可以查看安裝是否成功。至此,.Net Core的安裝就完成了。
當(dāng)然,也可以使用解壓安裝。到
https://www.microsoft.com/net/download/linux 下載
CentOS7對(duì)應(yīng)的sdk壓縮包,之后解壓到自定義的安裝路徑。
sudo mkdir -p /opt/dotnet && sudo tar zxf dotnet.tar.gz -C /opt/dotnet
# 可以設(shè)置一下環(huán)境變量,也可以采用下面的方式建立軟鏈接,因?yàn)?/usr/local/bin 默認(rèn)包含于$PATH中
sudo ln -s /opt/dotnet/dotnet /usr/local/bin
# 之后運(yùn)行查看安裝結(jié)果
dotnet --info
服務(wù)器維護(hù)小知識(shí)二、編譯運(yùn)行項(xiàng)目
1、新建一個(gè)mvc項(xiàng)目
dotnet new mvc -o ntmvc
查看ntmvc文件夾 ,可以發(fā)現(xiàn),一個(gè)mvc項(xiàng)目的模板已經(jīng)建好了,如下:
2、修改 Startup.cs 文件
可以使用vscode直接修改遠(yuǎn)程計(jì)算機(jī)或者是虛擬機(jī)中的文件,具體參考
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、生成項(xiàng)目
首先切換到項(xiàng)目目錄ntmvc,之后運(yùn)行下面的命令
dotnet publish -c Release
服務(wù)器維護(hù)小知識(shí) 運(yùn)行命令之后,項(xiàng)目目錄中會(huì)多出一個(gè)
bin文件夾
服務(wù)器維護(hù)小知識(shí) 在bin文件夾中會(huì)包含Release文件夾,在Release文件夾中的netcoreapp2.0文件夾中,會(huì)包含可以發(fā)布的內(nèi)容,即
publish文件夾。
服務(wù)器維護(hù)小知識(shí)注:publish文件夾之外的內(nèi)容,同我們運(yùn)行 dotnet run 命令時(shí)所生成的文件是相同的,只不過Debug文件夾換成了自己命名的Release文件夾而已。換句話說,運(yùn)行dotnet publish -c Release 比運(yùn)行 dotnet run 多了一個(gè)publish文件夾,而這個(gè)文件夾正是所要發(fā)布的內(nèi)容
服務(wù)器維護(hù)小知識(shí)4、運(yùn)行項(xiàng)目
切換到publish文件夾,運(yùn)行命令
dotnet nmvc.dll
如下圖所示:
服務(wù)器維護(hù)小知識(shí) 5、項(xiàng)目的開機(jī)自動(dòng)運(yùn)行
接下來設(shè)置項(xiàng)目的開機(jī)自動(dòng)啟動(dòng),在
/etc/systemd/system/ 中新建一個(gè)服務(wù)文件
vim /etc/systemd/system/kestrel-ntmvc.service
內(nèi)容如下:
[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
之后保存,運(yùn)行以下命令:
systemctl enable kestrel-ntmvc.service
systemctl start kestrel-ntmvc.service
systemctl status kestrel-ntmvc.service
注意:如果檢查到錯(cuò)誤,需要修改 kestrel-ntmvc.service 文件,修改正確之后,需要運(yùn)行以下命令重新啟動(dòng):
systemctl daemon-reload
systemctl restart kestrel-ntmvc.service
到此為止,一個(gè)簡單的項(xiàng)目就可以正常訪問了。接下來,對(duì)項(xiàng)目進(jìn)行改造,引入nginx的使用。
服務(wù)器維護(hù)小知識(shí)三、編譯安裝nginx
1、安裝依賴項(xiàng)
yum -y install gcc gcc-c++ pcre pcre-devel openssl openssl-devel zlib zlib-devel
2、下載安裝包
最新的下載地址請到官網(wǎng)獲取。
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
如上所述,這樣可以不用再設(shè)置環(huán)境變量。
服務(wù)器維護(hù)小知識(shí)四、證書相關(guān)
為了增強(qiáng)項(xiàng)目的安全性,有時(shí)需要將http訪問轉(zhuǎn)為https訪問。通過對(duì)nginx中ssl模塊進(jìn)行設(shè)置,可以實(shí)現(xiàn)這一點(diǎn)。
通常,這需要向CA申請安全證書(常用免費(fèi)證書:
https://letsencrypt.org/ )。
由于這里僅作測試用,因此使用自己生成的證書。
1、證書的生成
在root目錄下建立certs文件夾,切換到該文件夾,依次運(yùn)行以下命令:
# 建立服務(wù)器私鑰(過程需要輸入密碼,請記住這個(gè)密碼)生成RSA密鑰
openssl genrsa -des3 -out testcert.key 1024
# 生成一個(gè)證書請求 需要依次輸入國家,地區(qū),組織,email,common name等,common name可以寫你的名字或者域名。如果為了https申請,必須和域名吻合,否則會(huì)引發(fā)瀏覽器警報(bào)。
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、證書的位置
將證書復(fù)制到 /etc/ssl/certs/ 目錄
cp testcert.crt /etc/ssl/certs/
cp testcert_nopwd.key /etc/ssl/certs/testcert.key
如下圖:
3、迪菲-赫爾曼密鑰交換
一般來說,之后修改nginx.conf配置文件就可以了。為了進(jìn)一步增強(qiáng)安全性,可以進(jìn)行迪菲-赫爾曼密鑰交換,在 /etc/ssl/certs/ 目錄中
openssl dhparam -out dhparam.pem 4096生成文件
服務(wù)器維護(hù)小知識(shí)五、nginx配置文件相關(guān)
1、自定義 proxy.conf 文件
在 /usr/local/nginx/cong/ 目錄下新建 proxy.conf 文件,后面會(huì)在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文件,著重點(diǎn)已經(jīng)使用了不同的顏色進(jìn)行標(biāo)注。
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;
}
}
}
服務(wù)器維護(hù)小知識(shí)六、nginx 開機(jī)自動(dòng)啟動(dòng)
# 設(shè)置nginx自啟動(dòng),在/lib/systemd/system/ 目錄下創(chuàng)建一個(gè)服務(wù)文件
vim /lib/systemd/system/nginx.service
注意,這里的路徑是 /lib/systemd/system/ ,而非上面ntmvc項(xiàng)目自啟動(dòng)服務(wù)文件所在的 /etc/systemd/system/ 這一點(diǎn)值得注意。
內(nèi)容如下:
[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
文件編輯完成之后,運(yùn)行以下命令啟動(dòng)服務(wù):
systemctl enable nginx.service
# 啟動(dòng)nginx服務(wù)
systemctl start nginx.service
# 查看狀態(tài)
systemctl status nginx.service
這里之所以有一個(gè)警告,是因?yàn)槲覀兪褂玫淖C書是自己生成的,而不是正式的證書。
通常,對(duì)配置文件修改后需要重啟服務(wù),執(zhí)行以下命令:
# 如果修改了文件,這個(gè)是必須的
systemctl daemon-reload
# 重新啟動(dòng)服務(wù)
systemctl restart nginx.service
服務(wù)器維護(hù)小知識(shí)七、防火墻相關(guān)
以下的三個(gè)端口是必須要開的 ,其他的視情況而定。
#端口
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
重新加載并顯示端口
服務(wù)器維護(hù)小知識(shí)八、訪問相關(guān)
以上的配置完成之后,如果環(huán)境使用的是真實(shí)的物理機(jī),或者是橋接的虛擬機(jī),直接訪問ip地址就可以了。
如果是NAT連接的虛擬機(jī),需要進(jìn)行端口映射。本實(shí)驗(yàn)使用的VirtualBox 搭建的虛擬機(jī),以此為例,按下圖進(jìn)行設(shè)置即可。
如果是直接在虛擬機(jī)中進(jìn)行瀏覽,瀏覽127.0.0.1 或者localhost 即可。
服務(wù)器維護(hù)小知識(shí)如果是從主機(jī)進(jìn)行訪問,可在主機(jī)的瀏覽器中輸入https://192.168.56.1:1518,即可映射到虛擬機(jī)的443端口,這樣就可以通過https進(jìn)行訪問虛擬機(jī)中的ntmvc項(xiàng)目。
服務(wù)器維護(hù)小知識(shí)由于在nginx.conf中配置了
add_header Strict-Transport-Security max-age=15768000; 即只能允許https訪問, 因此輸入http://192.168.56.1:1518 會(huì)提示錯(cuò)誤。
服務(wù)器維護(hù)小知識(shí)正常的訪問結(jié)果如下圖所示(谷歌瀏覽器),之所以會(huì)出現(xiàn)這樣的提示,是因?yàn)樗玫淖C書是自己生成的。
繼續(xù)訪問即可訪問ntmvc中的頁面,如下圖:
IT運(yùn)維 我們選擇
北京艾銻無限
以上文章由北京艾銻無限科技發(fā)展有限公司整理