在 Docker 容器中运行 ASP.NET Core 应用
创建Docker支持生成Dockerfile文件
在解决方案asp.net core项目下右键添加Dockerfile支持、选择目标OS为Linux,生成Dockerfile文件
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Log-Frame/HECore.SerilogWebApi/HECore.SerilogWebApi.csproj", "Log-Frame/HECore.SerilogWebApi/"]
RUN dotnet restore "Log-Frame/HECore.SerilogWebApi/HECore.SerilogWebApi.csproj"
COPY . .
WORKDIR "/src/Log-Frame/HECore.SerilogWebApi"
RUN dotnet build "HECore.SerilogWebApi.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "HECore.SerilogWebApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "HECore.SerilogWebApi.dll"]
在 Linux 容器或 Windows 容器中运行
# 停止容器
docker stop hecore.serilogwebapi
# 删除容器
docker rm hecore.serilogwebapi
# 删除镜像
docker rmi hecore.serilogwebapi:latest
# 重要:进入解决方案根目录(注:.sln 文件所在的目录)
# 构建hecore.serilogwebapi:latest镜像
docker build -f ./Log-Frame/HECore.SerilogWebApi/Dockerfile -t hecore.serilogwebapi:latest .
# 运行hecore.serilogwebapi容器,设置环境变量为:Development
docker run --name hecore.serilogwebapi -d --restart=always -e "ASPNETCORE_ENVIRONMENT=Development" -p 5151:80 hecore.serilogwebapi:latest
# 删除所有悬空镜像,不删除未使用镜像
docker rmi $(docker images -f "dangling=true" -q)
# 查看日志
docker logs hecore.serilogwebapi
博客内容仅代表个人观点,如发现阐述有误,麻烦指正,谢谢!