.NET 快速开始
第 1 步:编写基础应用
安装 .NET Core SDK 3.1。在 Console 中,使用 dotnet 命令新建一个空 Web 项目:
dotnet new web -o helloworld-csharp
cd helloworld-csharp
更新 Program.cs
中的 CreateHostBuilder
定义,侦听 8080
端口:
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace helloworld_csharp
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
string port = "8080";
string url = String.Concat("http://0.0.0.0:", port);
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>().UseUrls(url);
});
}
}
}
将 Startup.cs
的内容更新为如下:
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace helloworld_csharp
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!\n");
});
});
}
}
}
以上代码会创建一个基本的 Web 服务器,并监听 8080
端口。
第 2 步:将应用容器化
在项目根目录下,创建一个名为 Dockerfile
的文件,内容如下:
# 使用微软官方 .NET 镜像作为构建环境
# https://hub.docker.com/_/microsoft-dotnet-core-sdk/
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-alpine AS build
WORKDIR /app
# 安装依赖
COPY *.csproj ./
RUN dotnet restore
# 将本地代码拷贝到容器内
COPY . ./
WORKDIR /app
# 构建项目
RUN dotnet publish -c Release -o out
# 使用微软官方 .NET 镜像作为运行时镜像
# https://hub.docker.com/_/microsoft-dotnet-core-aspnet/
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-alpine AS runtime
WORKDIR /app
COPY --from=build /app/out ./
# 启动服务
ENTRYPOINT ["dotnet", "helloworld-csharp.dll"]
添加一个 .dockerignore
文件,以从容器映像中排除文件:
**/obj/
**/bin/
第 3 步(可选):本地构建镜像
如果您本地已经安装了 Docker,可以运行以下命令,在本地构建 Docker 镜像:
docker build -t helloworld-csharp .
构建成功后,运行 docker images
,可以看到构建出的镜像:
REPOSITORY TAG IMAGE ID CREATED SIZE
helloworld-csharp latest 1c8dfb88c823 8 seconds ago 105MB
随后您可以将此镜像上传至您的镜像仓库。