Linux 服务器上部署 .NET Core 应用程序,值得收藏!

Deploy .NET Core Applications on Linux Servers

在 Linux 服务器上部署 .NET Core 应用程序,标志着传统的以微软为中心的部署平台的重大转变。.NET Core 的跨平台特性允许开发人员享受 Linux 环境的性能、可靠性和安全性。本指南提供了在各种 Linux 发行版上部署 .NET Core 应用程序的全面概述,重点是使用 Nginx 或 Apache 作为反向代理以及使用 SSL 保护部署。

必备条件

  • A .NET Core application ready for deployment.
  • A Linux server (Ubuntu, CentOS, or any preferred distribution).
  • Basic knowledge of the Linux command line.

Step 1: 准备 Linux Server

首先,更新服务器的包索引。在服务器上安装 .NET Core 运行时或 SDK。

For Debian / Ubuntu

sudo apt update
sudo apt install dotnet-runtime-6.0

For Red Hat / CentOS / Rocky Linux

sudo dnf update
sudo dnf install dotnet-runtime-6.0

Step 2: 发布 .NET 应用程序

要发布用于生产的.NET 应用程序,.NET CLI 提供了一个简单而强大的命令。

dotnet publish -c Release -o ./publish

Step 3: 上传 .NET 程序到 Linux Server

将已发布的应用程序从本地目录传输到远程 Linux 服务器

scp -r ./publish username@your_production_server:/path/to/destination

scp命令的使用参考文章:通过14个示例掌握 Linux 中使用 SCP 命令安全复制文件

Step 4: 运行 .NET 应用程序

切换到应用程序目录,并使用以下命令运行应用程序。

dotnet MyApplication.dll

该命令在其默认端口上启动应用程序,对于 Kestrel 服务器通常为 5000。

您还可以将 .NET 应用程序配置为系统服务运行,参考文章: 如何在 Linux 为 .NET Core 应用程序创建 Systemd 服务

Step 5: 设置反向代理

反向代理位于应用程序前面,处理传入的 HTTP 请求并将其转发到应用程序。这种设置提高了安全性,允许负载平衡,并有效地提供静态内容。

使用 Nginx 反向代理

(1) 安装 Nginx

sudo apt install nginx

(2) 创建 /etc/etc/nginx/sites-available/myapp 配置文件,包含以下内容:

server {
    listen 80;
    server_name 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;
    }
}

(3) 把配置文件链接到 sites-enabled 目录

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/

(4) 测试配置文件,然后重启 Nginx 服务

sudo nginx -t
sudo systemctl restart nginx

使用 Apache 反向代理

(1) 安装 Apache

sudo apt install apache2

(2) 启用 proxy 和 proxy_http 模块

sudo a2enmod proxy proxy_http

(3) 创建 /etc/apache2/sites-available/myapp.conf 配置文件,包含以下内容:

<VirtualHost *:80>
    ServerName example.com

    ProxyPreserveHost On
    ProxyPass / http://localhost:5000/
    ProxyPassReverse / http://localhost:5000/
</VirtualHost>

(4) 启用站点配置,然后重启 Apache 服务

sudo a2ensite myapp.conf
sudo systemctl restart apache2

Step 6: 安装 Let’s Encrypt SSL 证书

使用 SSL 保护应用程序对于保护敏感数据至关重要。Let’s Encrypt 提供免费的 SSL 证书。Certbot 是一个流行的工具,用于获取和更新 Let’s Encrypt 证书。

For Nginx

(1) 安装 Certbot 和 Nginx 插件

sudo apt-get install certbot python3-certbot-nginx

(2) 获取并安装证书

sudo certbot --nginx -d example.com

For Apache

(1) 安装 Certbot 和 Apache 插件

sudo apt-get install certbot python3-certbot-apache

(2) 获取并安装证书

sudo certbot --apache -d example.com

我的开源项目

酷瓜云课堂-开源知识付费解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值