从零到一:在Ubuntu Server上部署你的第一个.NET 8 Web API(含Dockerfile编写与容器化实战)
从零到一在Ubuntu Server上部署你的第一个.NET 8 Web API含Dockerfile编写与容器化实战最近两年.NET跨平台开发能力突飞猛进特别是.NET 8的发布让Linux服务器部署变得前所未有的简单。作为一名长期在Linux环境部署.NET应用的全栈开发者我想分享一个完整的实战流程——从裸机Ubuntu Server开始到最终运行在Docker容器中的Web API服务。这个过程不仅涉及基础环境配置更重要的是教会你如何将开发成果转化为可部署的生产级应用。1. 环境准备Ubuntu Server与.NET 8 SDK在开始之前确保你有一台运行Ubuntu Server 22.04 LTS的机器物理机或云实例均可。这个版本之所以被推荐是因为它提供了最完整的.NET支持且生命周期长达5年。1.1 安装基础依赖首先更新系统包索引并安装必要的工具链sudo apt update sudo apt upgrade -y sudo apt install -y curl wget git unzip1.2 安装.NET 8 SDK对于Ubuntu 22.04微软提供了官方的APT源配置方式sudo apt install -y dotnet-sdk-8.0安装完成后验证版本dotnet --version # 预期输出8.0.x注意如果系统提示找不到包可能需要先添加微软的GPG密钥和软件源wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb sudo dpkg -i packages-microsoft-prod.deb rm packages-microsoft-prod.deb2. 创建你的第一个Web API项目2.1 初始化项目结构使用.NET CLI创建一个最小化的Web API项目dotnet new webapi -n WeatherAPI --no-https -o ~/WeatherAPI cd ~/WeatherAPI这个命令创建了一个不启用HTTPS的Web API项目简化开发环境配置名为WeatherAPI的天气服务示例项目目录位于用户主文件夹下2.2 关键代码解析打开Program.cs你会看到一个精简的现代.NET API模板var builder WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app builder.Build(); app.MapControllers(); app.Run();相比传统Startup类这种最小API模式更符合现代开发习惯。让我们添加一个简单的天气控制器touch Controllers/WeatherForecastController.cs编辑该文件并加入using Microsoft.AspNetCore.Mvc; namespace WeatherAPI.Controllers; [ApiController] [Route([controller])] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries new[] { Freezing, Bracing, Chilly, Cool, Mild, Warm, Balmy, Hot, Sweltering, Scorching }; [HttpGet(Name GetWeatherForecast)] public IEnumerableWeatherForecast Get() { return Enumerable.Range(1, 5).Select(index new WeatherForecast { Date DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC Random.Shared.Next(-20, 55), Summary Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }2.3 本地运行测试启动开发服务器dotnet run用curl测试API端点curl http://localhost:5000/WeatherForecast | jq你应该能看到返回的JSON格式天气数据。按CtrlC停止服务。3. 容器化部署Docker实战3.1 安装Docker引擎在Ubuntu上安装Docker CEsudo apt install -y docker.io sudo systemctl enable --now docker sudo usermod -aG docker $USER newgrp docker # 刷新用户组3.2 编写生产级Dockerfile在项目根目录创建Dockerfile# 构建阶段 FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build WORKDIR /src COPY . . RUN dotnet restore RUN dotnet publish -c Release -o /app # 运行时阶段 FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime WORKDIR /app COPY --frombuild /app . EXPOSE 80 ENTRYPOINT [dotnet, WeatherAPI.dll]这个多阶段构建的Dockerfile具有以下优化分离构建环境和运行时环境减小最终镜像体积使用官方微软镜像确保兼容性明确暴露80端口HTTP标准端口3.3 构建并运行容器执行构建命令docker build -t weatherapi .运行容器实例docker run -d -p 8080:80 --name weather weatherapi验证服务curl http://localhost:8080/WeatherForecast | jq4. 生产环境优化建议4.1 性能调优参数在docker run命令中添加.NET运行时优化参数docker run -d -p 8080:80 \ -e DOTNET_SYSTEM_GLOBALIZATION_INVARIANT1 \ -e ASPNETCORE_ENVIRONMENTProduction \ --name weather weatherapi关键环境变量说明变量名推荐值作用DOTNET_SYSTEM_GLOBALIZATION_INVARIANT1禁用全球化特性提升性能ASPNETCORE_ENVIRONMENTProduction启用生产模式配置COMPlus_ReadyToRun1启用AOT编译优化4.2 日志与监控配置修改Program.cs添加结构化日志builder.Logging.ClearProviders(); builder.Logging.AddJsonConsole(options { options.IncludeScopes true; options.TimestampFormat HH:mm:ss; options.JsonWriterOptions new() { Indented true }; });4.3 健康检查端点添加健康检查路由app.MapGet(/health, () Results.Ok(new { status healthy }));然后在Dockerfile中添加健康检查指令HEALTHCHECK --interval30s --timeout3s \ CMD curl -f http://localhost/health || exit 15. CI/CD集成示例5.1 GitHub Actions自动化流程创建.github/workflows/docker-build.ymlname: Docker Build on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkoutv3 - name: Login to Docker Hub uses: docker/login-actionv2 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_TOKEN }} - name: Build and push uses: docker/build-push-actionv4 with: push: true tags: yourusername/weatherapi:latest5.2 多架构镜像构建修改Dockerfile支持ARM64# syntaxdocker/dockerfile:1.4 FROM --platform$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 AS build # ...其余内容保持不变...构建命令更新为docker buildx build --platform linux/amd64,linux/arm64 -t yourusername/weatherapi:multiarch --push .在实际部署中发现这种多阶段构建配合ARM64支持的配置能让同一套代码无缝运行在树莓派到云服务器的各种环境。特别是在Kubernetes集群中部署时节点架构差异完全由Docker自动处理大大简化了运维复杂度。