一、部署前环境准备
1.1 系统基础配置
选择CentOS 8或更高版本作为部署环境,建议使用最小化安装镜像以减少不必要的服务占用。通过cat /etc/redhat-release确认系统版本,使用yum update -y完成基础更新。内存建议不低于4GB,磁盘空间预留至少20GB用于应用部署和数据存储。
1.2 安装.NET Core运行环境
通过微软官方仓库安装.NET Core SDK:
# 导入微软GPG密钥sudo rpm -Uvh https://packages.microsoft.com/config/centos/8/packages-microsoft-prod.rpm# 安装SDK(以.NET 6为例)sudo dnf install dotnet-sdk-6.0 -y# 验证安装dotnet --version
对于生产环境,建议同时安装ASP.NET Core运行时:
sudo dnf install aspnetcore-runtime-6.0 -y
1.3 数据库准备
推荐使用PostgreSQL作为后台数据库,安装步骤如下:
# 添加PostgreSQL仓库sudo dnf install https://download.postgresql.org/pub/repos/yum/reporpms/EL-8-x86_64/pgdg-redhat-repo-latest.noarch.rpm -y# 安装PostgreSQL 14sudo dnf install postgresql14-server -y# 初始化数据库sudo /usr/pgsql-14/bin/postgresql-14-setup initdb# 启动服务sudo systemctl enable postgresql-14sudo systemctl start postgresql-14
创建数据库用户和专用数据库:
CREATE USER customer_service WITH PASSWORD 'SecurePass123!';CREATE DATABASE customer_service_db OWNER customer_service;ALTER DATABASE customer_service_db SET timezone TO 'Asia/Shanghai';
二、应用部署实施
2.1 代码结构准备
建议采用分层架构设计:
/CustomerServiceSystem├── Controllers/ # API控制器├── Services/ # 业务逻辑├── Models/ # 数据模型├── Data/ # 数据库访问├── appsettings.json # 配置文件└── Program.cs # 启动入口
关键配置示例(appsettings.Production.json):
{"ConnectionStrings": {"DefaultConnection": "Host=localhost;Database=customer_service_db;Username=customer_service;Password=SecurePass123!"},"Kestrel": {"Endpoints": {"Http": {"Url": "http://*:5000"}}}}
2.2 发布与部署
使用dotnet publish生成发布包:
dotnet publish -c Release -o ./publish --self-contained false
将publish目录下的文件通过scp或rsync传输至服务器:
scp -r ./publish user@centos-server:/var/www/customerservice
2.3 服务管理配置
创建Systemd服务文件/etc/systemd/system/customerservice.service:
[Unit]Description=.NET Core Customer Service AppAfter=network.target[Service]WorkingDirectory=/var/www/customerserviceExecStart=/usr/bin/dotnet /var/www/customerservice/CustomerServiceSystem.dllRestart=alwaysRestartSec=10SyslogIdentifier=customerserviceUser=nginxEnvironment=ASPNETCORE_ENVIRONMENT=Production[Install]WantedBy=multi-user.target
启用并启动服务:
sudo systemctl daemon-reloadsudo systemctl enable customerservicesudo systemctl start customerservice
三、反向代理与安全配置
3.1 Nginx反向代理设置
安装Nginx并配置代理:
sudo dnf install nginx -y
编辑/etc/nginx/conf.d/customerservice.conf:
server {listen 80;server_name customerservice.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 $host;proxy_cache_bypass $http_upgrade;}# 安全头配置add_header X-Frame-Options "SAMEORIGIN";add_header X-Content-Type-Options "nosniff";}
重启Nginx服务:
sudo systemctl restart nginx
3.2 防火墙配置
开放必要端口:
sudo firewall-cmd --permanent --add-port=80/tcpsudo firewall-cmd --permanent --add-port=443/tcpsudo firewall-cmd --reload
四、性能优化与监控
4.1 数据库连接池优化
在Startup.cs中配置:
services.AddDbContextPool<ApplicationDbContext>(options =>options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection"),sqlOptions => sqlOptions.EnableRetryOnFailure(maxRetryCount: 5,maxRetryDelay: TimeSpan.FromSeconds(30),errorNumbersToAdd: null)));
4.2 响应缓存中间件
安装缓存包并配置:
dotnet add package Microsoft.AspNetCore.ResponseCaching
在Program.cs中添加:
builder.Services.AddResponseCaching();app.UseResponseCaching();
4.3 监控方案
推荐使用Prometheus+Grafana监控栈:
# 安装Prometheus Node Exportersudo dnf install prometheus-node-exporter -ysudo systemctl enable prometheus-node-exportersudo systemctl start prometheus-node-exporter
配置.NET Core应用指标:
app.UseMetricServer();app.UseHttpMetrics();
五、常见问题处理
5.1 数据库连接失败
检查三要素:
- 确认PostgreSQL服务状态:
systemctl status postgresql-14 - 验证pg_hba.conf配置(/var/lib/pgsql/14/data/pg_hba.conf)
- 测试连接:
psql -h localhost -U customer_service -d customer_service_db
5.2 502 Bad Gateway错误
检查步骤:
- 确认应用日志:
journalctl -u customerservice -f - 验证Kestrel监听端口:
ss -tulnp | grep 5000 - 检查Nginx错误日志:
tail -f /var/log/nginx/error.log
5.3 性能瓶颈排查
使用以下工具进行诊断:
# 进程资源监控top -p $(pgrep -d',' dotnet)# 网络连接分析netstat -anp | grep dotnet# 慢查询日志分析(PostgreSQL)sudo vi /var/lib/pgsql/14/data/postgresql.conf# 设置log_min_duration_statement = 1000
通过以上系统化的部署方案,开发者可以在30分钟内完成从环境准备到系统上线的完整流程。实际部署时建议先在测试环境验证所有步骤,特别注意配置文件的环境区分(Development/Staging/Production)。对于高并发场景,建议结合负载均衡器和Redis缓存进一步提升系统性能。