Skip to content

Instantly share code, notes, and snippets.

@michaeldimoudis
Last active November 9, 2023 17:19
Show Gist options
  • Save michaeldimoudis/d32a6ebb79d4a0db02008c4d724c8bb5 to your computer and use it in GitHub Desktop.
Save michaeldimoudis/d32a6ebb79d4a0db02008c4d724c8bb5 to your computer and use it in GitHub Desktop.
Hardened ASP.NET Core 3.1 Runtime Dockerfile
ARG VERSION=3.1-alpine
# Acknowledgements:
# This file was dervied with the help of a combination of https://github.com/ironPeakServices/iron-alpine/blob/master/Dockerfile
# and these 2 blog posts https://medium.com/01001101/containerize-your-net-core-app-the-right-way-35c267224a8d and https://medium.com/asos-techblog/minimising-your-attack-surface-by-building-highly-specialised-docker-images-example-for-net-b7bb177ab647
# Stage 1: Build application
FROM mcr.microsoft.com/dotnet/core/sdk:$VERSION AS build-env
WORKDIR /build
COPY . .
# Publish app
RUN dotnet publish \
  -c Release \
  -o ./output \
  -r alpine-x64 \
  /p:PublishReadyToRun=true
# Stage 2: Copy application artifacts into a smaller, hardened runtime 
# environment, which is then used as our final image
FROM mcr.microsoft.com/dotnet/core/aspnet:$VERSION
# Make a pipe fail on the first failure
SHELL ["/bin/sh", "-o", "pipefail", "-c"]
# The user the app should run as
ENV APP_USER=app
# The home directory
ENV APP_DIR="/$APP_USER"
# Harden docker image
COPY --from=build-env /build/harden.sh .
RUN chmod +x harden.sh && \
  sh harden.sh && \
  rm harden.sh
# default directory is /app
WORKDIR $APP_DIR
# Copy application over
COPY --from=build-env --chown=$APP_USER:$APP_USER /build/output .
ENV ASPNETCORE_URLS=http://+:8080
# Run some post install hardening commands
COPY --from=build-env /build/post-install.sh .
RUN chmod +x post-install.sh && \
  sh post-install.sh && \
  rm post-install
# Run app as non root user
USER $APP_USER
EXPOSE 8080
ENTRYPOINT ["dotnet", "MyApp.dll"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment