前言
本篇 建立一個 .Net Core 3.1 WebAPI 專案
並參考 .Net Core 3.1 類別庫專案
撰寫 Dockerfile 讓專案跑在 Docker Container 中
建立範例專案
建立 .Net Core 3.1 WebAPI 專案 作範例測試
# ~
mkdir dockerSample
cd dockerSample
# ~/dockerSample
dotnet new sln
dotnet new webapi -f netcoreapp3.1 -o dockerSample_WebApi
dotnet new classlib -f netcoreapp3.1 -o dockerSample_Service
# 專案檔 加入 dockerSample_WebApi、dockerSample_Service
dotnet sln add dockerSample_WebApi/dockerSample_WebApi.csproj
dotnet sln add dockerSample_Service/dockerSample_Service.csproj
# dockerSample_WebApi 加入參考 dockerSample_Service
dotnet add dockerSample_WebApi/dockerSample_WebApi.csproj reference dockerSample_Service/dockerSample_Service.csproj
修改 dockerSample_Service > Class1.cs
namespace dockerSample_Service
{
public class Class1
{
public string Test()
{
return "dockerSample_Service";
}
}
}
修改 dockerSample_WebApi > Controllers > WeatherForecastController.cs
using dockerSample_Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace dockerSample_WebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public string Get()
{
return new Class1().Test();
}
}
}
撰寫 Dockerfile
# ~/dockerSample
echo. > Dockerfile
Dockerfile
# https://hub.docker.com/_/microsoft-dotnet
FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /source
# copy csproj and restore as distinct layers
COPY *.sln .
COPY dockerSample_WebApi/*.csproj ./dockerSample_WebApi/
COPY dockerSample_Service/*.csproj ./dockerSample_Service/
RUN dotnet restore
# copy everything else and build app
COPY dockerSample_WebApi/. ./dockerSample_WebApi/
COPY dockerSample_Service/. ./dockerSample_Service/
WORKDIR /source/dockerSample_WebApi
RUN dotnet publish -c release -o /app --no-restore
# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:3.1
WORKDIR /app
COPY --from=build /app ./
ENTRYPOINT ["dotnet", "dockerSample_WebApi.dll"]
編譯、執行 DockerImage
編譯 Image
# ~/dockerSample
docker build -t dockersample_webapi --no-cache .
# 編譯完成後 查看 Image
docker images
# 輸出
REPOSITORY TAG IMAGE ID CREATED SIZE
dockersample_webapi latest 95f60d82602c 2 minutes ago 208MB
建立 Container
docker run --name dockersample_webapi -d -p 8080:80 dockersample_webapi
# 建立完成後 確認 Container
docker ps -a
# 輸出
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
38ac29c81f36 dockersample_webapi "dotnet dockerSample…" 20 seconds ago Up 19 seconds 0.0.0.0:8080->80/tcp dockersample_webapi
呼叫 API 確認功能是否正常
http://localhost:8080/weatherforecast
轉載請註明來源,若有任何錯誤或表達不清楚的地方,歡迎在下方評論區留言,也可以來信至 leozheng0621@gmail.com
如果文章對您有幫助,歡迎斗內(donate),請我喝杯咖啡