受欢迎的博客标签

Part 1 - how to containerize a .NET application with Docker - using Alpine Linux image

Published

If you want the smallest possible footprint without using Microsoft images, you can use Alpine Linux. Because Alpine uses a different C library (musl), you must explicitly target linux-musl-x64 during compilation.

# Stage 1: Build on raw Alpine
FROM alpine:latest AS build-env

# Install bash, curl, and build-dependencies required for the installer script
RUN apk add --no-cache bash curl icu-libs libintl krb5-libs libgcc libstdc++

# Download and install .NET 10.0.300 SDK
RUN curl -sSL https://dot.net | bash /dev/stdin --version 10.0.300 --install-dir /usr/share/dotnet
ENV PATH="${PATH}:/usr/share/dotnet"

WORKDIR /src
COPY . .

# Crucial: Target linux-musl-x64 for Alpine compatibility
RUN dotnet publish -c Release -r linux-musl-x64 --self-contained true -o /app/publish

# Stage 2: Final minimal Alpine runtime
FROM alpine:latest
WORKDIR /app

# Install minimal OS-level dependencies for running native .NET code
RUN apk add --no-cache icu-libs libssl3 libstdc++

COPY --from=build-env /app/publish .

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

ENTRYPOINT ["./YourWebAppProjectName"]

 

需要安装 .NET 程序在 Linux 系统上运行所必需的底层系统依赖库(如 glibc、libssl、zlib、crypto 等)。

 

samples

https://github.com/nopSolutions/nopCommerce/blob/develop/Dockerfile

# create the build instance 
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build

ARG TARGETPLATFORM
ARG BUILDPLATFORM

WORKDIR /src                                                                    
COPY ./src ./

# build solution   
RUN dotnet build NopCommerce.sln --no-incremental -c Release

# publish project
WORKDIR /src/Presentation/Nop.Web   
RUN dotnet publish Nop.Web.csproj -c Release -o /app/published

WORKDIR /app/published

RUN mkdir logs bin

RUN chmod 775 App_Data \
              App_Data/DataProtectionKeys \
              bin \
              logs \
              Plugins \
              wwwroot/bundles \
              wwwroot/db_backups \
              wwwroot/files/exportimport \
              wwwroot/icons \
              wwwroot/images \
              wwwroot/images/thumbs \
              wwwroot/images/uploaded \
	      wwwroot/sitemaps

# create the runtime instance 
FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime 

# add globalization support
RUN apk add --no-cache icu-libs icu-data-full
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false

# installs required packages
RUN apk add tiff --no-cache --repository https://dl-cdn.alpinelinux.org/alpine/edge/main/ --allow-untrusted
RUN apk add libgdiplus --no-cache --repository https://dl-cdn.alpinelinux.org/alpine/edge/community/ --allow-untrusted
RUN apk add libc-dev tzdata gcompat --no-cache

WORKDIR /app

COPY --from=build /app/published .

ENV ASPNETCORE_URLS=http://+:80
EXPOSE 80
                            
ENTRYPOINT ["dotnet", "Nop.Web.dll"]