把 ASP.NET Core 服务(BigDogServer)部署到 Linux 并作为服务运行
这里写目录标题
- 引言
- 环境准备
- 步骤详解
- 1. 发布 BigDogServer 应用程序
- 2. 把应用程序复制到 Linux 服务器
- 3. 创建 Systemd 服务文件
- 4. 启动并启用服务
- 5. 验证服务状态
- 6. 验证服务响应
- 7. 查看服务日志
- 8. 查看 .NET 运行时版本
- 命令行方式
- 代码方式
- 自动化部署脚本
- 9. 卸载服务
- 9.1 停止服务
- 9.2 禁用服务
- 9.3 移除服务文件
- 9.4 重新加载 Systemd 管理器配置
- 9.5 删除应用程序文件(可选)
- 自动化部署脚本
- 总结
引言
在当今的软件开发领域,ASP.NET Core 以其跨平台、高性能等特性,成为开发 Web 应用和服务的热门选择。而 Linux 凭借其开源、稳定、安全等优势,在服务器领域占据着重要地位。本文将详细介绍如何把名为 BigDogServer 的通用主机服务项目发布到 Linux 服务器,并将其作为系统服务来运行。
环境准备
- 服务器环境:运行 Linux 系统的服务器,本文以 Ubuntu 为例,同时需要安装 .NET Core Runtime。
步骤详解
1. 发布 BigDogServer 应用程序
在开发环境中,打开命令行工具,通过 cd
命令进入到 BigDogServer 项目的根目录。接着,使用 dotnet publish
命令把项目发布到指定的文件夹。
dotnet publish -c Release -o /path/to/publish
这里的 /path/to/publish
是你希望将应用程序发布到的目标文件夹路径。-c Release
表示以发布模式进行编译,-o
则用于指定输出目录。
2. 把应用程序复制到 Linux 服务器
可以使用 scp
命令将本地发布好的文件夹复制到 Linux 服务器上。
scp -r /path/to/publish username@server:/path/on/server
其中,username
是你在 Linux 服务器上的用户名,server
是服务器的 IP 地址或者域名,/path/on/server
是服务器上的目标路径。-r
选项的作用是递归复制整个文件夹。
3. 创建 Systemd 服务文件
如果想要简单启动:
nohup dotnet BigDogServer.dll
在 Linux 服务器上,使用 nano
编辑器创建一个 Systemd 服务文件。
sudo nano /etc/systemd/system/BigDogServer.service
在打开的文件中,添加以下内容:
[Unit]
Description=BigDogServer ASP.NET Core Application
After=network.target
[Service]
WorkingDirectory=/path/on/server
ExecStart=/usr/bin/dotnet /path/on/server/BigDogServer.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-BigDogServer
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
需要把 /path/on/server
替换成你复制应用程序的实际路径,BigDogServer.dll
替换为你的应用程序的实际 DLL 文件名。
4. 启动并启用服务
保存并关闭服务文件之后,运行以下命令重新加载 Systemd 管理器配置:
sudo systemctl daemon-reload
然后启动服务:
sudo systemctl start BigDogServer.service
若要让服务在系统启动时自动启动,可运行以下命令:
sudo systemctl enable BigDogServer.service
5. 验证服务状态
使用以下命令检查服务的状态:
sudo systemctl status BigDogServer.service
如果服务正常运行,你会看到类似以下的输出:
● BigDogServer.service - BigDogServer ASP.NET Core Application
Loaded: loaded (/etc/systemd/system/BigDogServer.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2024-01-01 12:00:00 UTC; 1min ago
Main PID: 1234 (dotnet)
Tasks: 10 (limit: 4915)
CGroup: /system.slice/BigDogServer.service
└─1234 /usr/bin/dotnet /path/on/server/BigDogServer.dll
在这个输出中,Active: active (running)
表明服务正在正常运行。Main PID
显示了服务的主进程 ID,你可以使用这个 ID 来监控或管理服务进程。
6. 验证服务响应
除了检查服务的状态,还可以通过向服务发送请求来验证它是否能够正常响应。如果 BigDogServer 是一个 Web 服务,你可以使用 curl
命令来发送 HTTP 请求。
curl http://localhost:5000
这里假设服务监听的是 http://localhost:5000
。如果服务正常运行,你应该能够看到服务返回的响应内容。如果服务监听的是不同的端口或地址,需要相应地修改 curl
命令。
7. 查看服务日志
如果服务没有正常运行,或者你想了解服务的详细运行情况,可以查看服务的日志。使用以下命令查看 BigDogServer 服务的日志:
sudo journalctl -u BigDogServer.service
这个命令会显示服务的详细日志信息,包括启动信息、错误信息等。如果服务出现了问题,日志中通常会有相关的错误提示,帮助你定位和解决问题。
8. 查看 .NET 运行时版本
在部署和运行 ASP.NET Core 应用程序时,了解当前系统所使用的 .NET 运行时版本是很有必要的。以下为你介绍两种查看 .NET 运行时版本的方法:
命令行方式
在命令行中执行下面的命令:
dotnet --list-runtimes
这个命令会列出当前系统中安装的所有 .NET 运行时及其对应的版本。运行后,你会看到类似如下的输出:
Microsoft.AspNetCore.App 3.1.23 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 3.1.23 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
Microsoft.AspNetCore.App 6.0.10 [/usr/share/dotnet/shared/Microsoft.AspNetCore.App]
Microsoft.NETCore.App 6.0.10 [/usr/share/dotnet/shared/Microsoft.NETCore.App]
输出内容中会显示每个运行时的名称以及对应的版本号。
代码方式
如果你想在代码里查看 .NET 运行时版本,可以使用 C# 编写一个简单的控制台应用程序。以下是示例代码:
using System;
class Program
{
static void Main()
{
Console.WriteLine($"当前 .NET 运行时版本: {Environment.Version}");
}
}
将上述代码保存为一个 .cs
文件,例如 CheckRuntimeVersion.cs
,然后使用以下命令编译并运行:
dotnet new console -n CheckRuntimeVersion
cd CheckRuntimeVersion
dotnet run
运行程序后,控制台会输出当前使用的 .NET 运行时版本。
自动化部署脚本
为了提高部署效率,我们可以编写一个 Python 脚本,自动化完成上述步骤。
import paramiko
import time
# 服务器信息
server = 'your_server_ip'
username = 'your_username'
password = 'your_password'
# 本地发布路径和服务器目标路径
local_publish_path = '/path/to/publish'
remote_target_path = '/path/on/server'
# 服务文件名
service_name = 'BigDogServer.service'
# 创建 SSH 客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接到服务器
ssh.connect(server, username=username, password=password)
# 创建 SFTP 客户端
sftp = ssh.open_sftp()
# 上传发布文件
def upload_files(local_path, remote_path):
import os
for root, dirs, files in os.walk(local_path):
relative_path = os.path.relpath(root, local_path)
remote_dir = os.path.join(remote_path, relative_path)
try:
sftp.mkdir(remote_dir)
except FileExistsError:
pass
for file in files:
local_file = os.path.join(root, file)
remote_file = os.path.join(remote_dir, file)
sftp.put(local_file, remote_file)
upload_files(local_publish_path, remote_target_path)
# 创建服务文件内容
service_content = f"""
[Unit]
Description=BigDogServer ASP.NET Core Application
After=network.target
[Service]
WorkingDirectory={remote_target_path}
ExecStart=/usr/bin/dotnet {remote_target_path}/BigDogServer.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-BigDogServer
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
"""
# 上传服务文件
with sftp.file(f'/etc/systemd/system/{service_name}', 'w') as f:
f.write(service_content)
# 重新加载 Systemd 管理器配置
stdin, stdout, stderr = ssh.exec_command('sudo systemctl daemon-reload')
time.sleep(2)
# 启动服务
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl start {service_name}')
time.sleep(2)
# 启用服务
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl enable {service_name}')
time.sleep(2)
# 检查服务状态
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl status {service_name}')
print(stdout.read().decode())
# 验证服务响应
try:
stdin, stdout, stderr = ssh.exec_command('curl http://localhost:5000')
response = stdout.read().decode()
print("服务响应内容:")
print(response)
except Exception as e:
print(f"验证服务响应时出错: {e}")
# 查看服务日志
stdin, stdout, stderr = ssh.exec_command(f'sudo journalctl -u {service_name}')
print("服务日志信息:")
print(stdout.read().decode())
# 查看 .NET 运行时版本
stdin, stdout, stderr = ssh.exec_command('dotnet --list-runtimes')
print("当前系统安装的 .NET 运行时版本:")
print(stdout.read().decode())
except Exception as e:
print(f"发生错误: {e}")
finally:
# 关闭连接
ssh.close()
请将脚本中的 your_server_ip
、your_username
、your_password
、/path/to/publish
、/path/on/server
和 BigDogServer.dll
替换为实际的值。运行此脚本可以自动化完成将 BigDogServer 应用程序发布到 Linux 并作为服务运行,同时进行验证和查看 .NET 运行时版本的过程。
如果你想卸载之前通过 Systemd 配置并运行的 BigDogServer
服务,可以按照以下步骤操作,我会将这些步骤添加到之前的博客中。
9. 卸载服务
如果你想要卸载 BigDogServer
服务,可以按照以下步骤操作:
9.1 停止服务
首先,需要停止正在运行的 BigDogServer
服务。使用以下命令:
sudo systemctl stop BigDogServer.service
此命令会向服务发送停止信号,使其停止运行。
9.2 禁用服务
接下来,禁用服务以防止它在系统启动时自动启动。执行以下命令:
sudo systemctl disable BigDogServer.service
这会移除服务的启动链接,确保服务不会在系统启动时被自动拉起。
9.3 移除服务文件
服务停止并禁用后,需要移除 Systemd 服务文件。使用以下命令删除服务文件:
sudo rm /etc/systemd/system/BigDogServer.service
此操作会从系统中删除服务的配置文件。
9.4 重新加载 Systemd 管理器配置
删除服务文件后,重新加载 Systemd 管理器配置,让系统更新服务列表。执行以下命令:
sudo systemctl daemon-reload
9.5 删除应用程序文件(可选)
如果你不再需要 BigDogServer
应用程序,可以删除之前复制到服务器上的应用程序文件。使用以下命令删除应用程序目录:
sudo rm -r /path/on/server
请将 /path/on/server
替换为实际的应用程序目录路径。
完成以上步骤后,BigDogServer
服务就会从系统中完全卸载。
自动化部署脚本
为了提高部署效率,我们可以编写一个 Python 脚本,自动化完成上述步骤。
import paramiko
import time
# 服务器信息
server = 'your_server_ip'
username = 'your_username'
password = 'your_password'
# 本地发布路径和服务器目标路径
local_publish_path = '/path/to/publish'
remote_target_path = '/path/on/server'
# 服务文件名
service_name = 'BigDogServer.service'
# 创建 SSH 客户端
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接到服务器
ssh.connect(server, username=username, password=password)
# 创建 SFTP 客户端
sftp = ssh.open_sftp()
# 上传发布文件
def upload_files(local_path, remote_path):
import os
for root, dirs, files in os.walk(local_path):
relative_path = os.path.relpath(root, local_path)
remote_dir = os.path.join(remote_path, relative_path)
try:
sftp.mkdir(remote_dir)
except FileExistsError:
pass
for file in files:
local_file = os.path.join(root, file)
remote_file = os.path.join(remote_dir, file)
sftp.put(local_file, remote_file)
upload_files(local_publish_path, remote_target_path)
# 创建服务文件内容
service_content = f"""
[Unit]
Description=BigDogServer ASP.NET Core Application
After=network.target
[Service]
WorkingDirectory={remote_target_path}
ExecStart=/usr/bin/dotnet {remote_target_path}/BigDogServer.dll
Restart=always
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnet-BigDogServer
User=www-data
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
"""
# 上传服务文件
with sftp.file(f'/etc/systemd/system/{service_name}', 'w') as f:
f.write(service_content)
# 重新加载 Systemd 管理器配置
stdin, stdout, stderr = ssh.exec_command('sudo systemctl daemon-reload')
time.sleep(2)
# 启动服务
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl start {service_name}')
time.sleep(2)
# 启用服务
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl enable {service_name}')
time.sleep(2)
# 检查服务状态
stdin, stdout, stderr = ssh.exec_command(f'sudo systemctl status {service_name}')
print(stdout.read().decode())
# 验证服务响应
try:
stdin, stdout, stderr = ssh.exec_command('curl http://localhost:5000')
response = stdout.read().decode()
print("服务响应内容:")
print(response)
except Exception as e:
print(f"验证服务响应时出错: {e}")
# 查看服务日志
stdin, stdout, stderr = ssh.exec_command(f'sudo journalctl -u {service_name}')
print("服务日志信息:")
print(stdout.read().decode())
# 查看 .NET 运行时版本
stdin, stdout, stderr = ssh.exec_command('dotnet --list-runtimes')
print("当前系统安装的 .NET 运行时版本:")
print(stdout.read().decode())
except Exception as e:
print(f"发生错误: {e}")
finally:
# 关闭连接
ssh.close()
请将脚本中的 your_server_ip
、your_username
、your_password
、/path/to/publish
、/path/on/server
和 BigDogServer.dll
替换为实际的值。运行此脚本可以自动化完成将 BigDogServer 应用程序发布到 Linux 并作为服务运行,同时进行验证和查看 .NET 运行时版本的过程。
总结
通过以上步骤,你可以顺利地将 BigDogServer 这样的 ASP.NET Core 服务项目发布到 Linux 服务器,并将其作为系统服务来运行。同时,通过多种方式验证服务的运行状态,确保服务能够正常工作。了解如何查看 .NET 运行时版本也有助于你对系统环境进行管理和维护。使用自动化脚本可以提高部署效率,减少人为错误。希望本文能对你的项目部署有所帮助。