microsoft / DockerTools

Tools For Docker, including Visual Studio Provisioning and Publishing
Other
175 stars 26 forks source link

In Dockerfile template, non-root user definition should be in the final stage and use UID instead of username #435

Open lbussell opened 4 months ago

lbussell commented 4 months ago

Hello, I noticed a few inconsistencies between the .NET Docker Samples and the automatically-generated Dockerfile from Visual Studio.

First, the non-root user definition should use UID instead of the username, since the Kubernetes option `runAsNonRoot only works with UIDs: https://github.com/dotnet/dotnet-docker/issues/4506#issuecomment-1483424853

Second, the non-root user definition should be as late in the Dockerfile as possible. This allows users to install additional packages if necessary without switching the user back to root.

You can reference the dotnet-docker sample Dockerfile, or I've created a diff of how the Dockerfile should be changed below:

- #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.
+ # 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:8.0 AS base
- USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["aspnetapp/aspnetapp.csproj", "aspnetapp/"]
RUN dotnet restore "./aspnetapp/aspnetapp.csproj"
COPY . .
WORKDIR "/src/aspnetapp"
RUN dotnet build "./aspnetapp.csproj" -c $BUILD_CONFIGURATION -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./aspnetapp.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
+ USER $APP_UID
ENTRYPOINT ["dotnet", "aspnetapp.dll"]
realrajaryan commented 3 months ago

Hi,

Thank you for the suggestion. We'll swap it over to use $APP_UID in 17.12.

We although need to keep APP in the base stage because we only build the base stage for fastmode in Visual Studio, and we want it to be set as the right user when we build it in fastmode.