Slide 1

Slide 1 text

OPTIMIZE CONTAINER IMAGES FOR .NET APPLICATIONS Basta Spring 2024

Slide 2

Slide 2 text

AGENDA ▪ Why should developers care about optimizing container images? ▪ Configure .NET applications ▪ Build container images ▪ Container Security ▪ Multi-architecture images

Slide 3

Slide 3 text

ABOUT ME Daniel Lindemann Enthusiastic .NET developer and consultant with a strange love for optimising, automating and containerising applications. What I do: ▪ Microsoft Azure ▪ Cloud-native & Serverless architectures ▪ Container technologies ▪ DevOps - Dev at night, Ops by day E-Mail: [email protected] Web: https://www.dlindemann.de LinkedIn: https://linkedin.com/in/daniel-lindemann

Slide 4

Slide 4 text

Why should developers care about optimizing container images?

Slide 5

Slide 5 text

THE WHY Why should developers care about optimizing container images? ▪ Application architecture doesn‘t matter ▪ Monoliths ▪ Distributed / Service-oriented ▪ Microservices ▪ Faster deployment and improved scalability ▪ Reduced bandwidth usage ▪ Shift security left ▪ Cost savings ▪ Enhance observability

Slide 6

Slide 6 text

Configure .NET applications

Slide 7

Slide 7 text

APPLICATION OPTIMIZATION Know the source Optimizing container images starts with optimizing the application

Slide 8

Slide 8 text

APPLICATION OPTIMIZATION 12 factor app - Configuration Configurations may vary between environments

Slide 9

Slide 9 text

CONFIGURE .NET APPLICATIONS 12 factor app - Configuration ▪ App configurations vary between environments (Development, Staging, Production) ▪ Connections to databases ▪ Connections to backing services ▪ Credentials for accessing external services ▪ Do not hard-code configurations ▪ Allows the separation of code and config ▪ Prevent pushing sensitive information to version control system ▪ Use environment variables to configure you application ▪ Allows to overwrite default configuration values ▪ Language- and OS-agnostic ▪ It’s fine to have a large set of configuration parameters

Slide 10

Slide 10 text

CONFIGURE .NET APPLICATIONS 12 factor app - Configuration in ASP.NET ▪ Configure your application via appsettings.json ▪ Set the basis of the application’s configuration ▪ Configuration values can easily be injected and verified via OptionsBuilder and IOptions interface ▪ Allows environment specific configurations ▪ During development use User Secrets to store sensitive information ▪ Store information only on your machine ▪ No changes to appsettings.json required ▪ HostBuilder reads environment variables ▪ Overwrite app settings via environment variables ▪ WebApplication.CreateBuilder() loads configurations from different resources (HostApplicationBuilder Constructor (Microsoft.Extensions.Hosting) | Microsoft Learn)

Slide 11

Slide 11 text

APPLICATION OPTIMIZATION 12 factor app - Port Binding App is self-contained and binds to a port

Slide 12

Slide 12 text

CONFIGURE .NET APPLICATIONS 12 factor app - Port Binding ▪ The app is completely self-contained ▪ Application binds to a port and can receive requests ▪ Application access can be configured Example: ▪ During development, the developer will access the application via http://localhost:1234 ▪ In production the application hosting could be reconfigured ▪ Maybe Port 1234 is already in use ▪ Maybe app runs behind a load balancer or reverse proxy

Slide 13

Slide 13 text

CONFIGURE .NET APPLICATIONS 12 factor app - Port Binding ASP.NET ▪ ASP.NET uses Kestrel to serve web application projects ▪ Kestrel is included in the .NET assembly ▪ Kestrel can be configured using the Kestrel-Options ▪ Options can be set within appsettings.json ▪ Configure options for the ASP.NET Core Kestrel web server | Microsoft Learn ▪ Kestrel and application hosting configuration can be overwritten using environment variables ▪ Use ASPNETCORE_URLS to set the url of the application ▪ Use Kestrel__Certificates__Default__Path and Kestrel__Certificates__Default__Password to configure SSL/TLS certificates

Slide 14

Slide 14 text

APPLICATION OPTIMIZATION 12 factor app - Logging App generates logs as continuous, time-ordered stream and does not attempt to manage or route

Slide 15

Slide 15 text

CONFIGURE .NET APPLICATIONS 12 factor app - Logs ▪ ASP.NET allows the configuration of logging ▪ Configure via Logging property in appsettings.json ▪ Log settings can be overwritten via environment variables ▪ Implement logging best practices for containers ▪ Always log to console (STDOUT) ▪ Use JSON format for logging ▪ You can also use logging frameworks like Serilog or log4net

Slide 16

Slide 16 text

Build container images

Slide 17

Slide 17 text

CONTAINER IMAGE Why should container images be small? ▪ Performance and efficiency ▪ Small images make the moving faster (push/pull) ▪ Improves the performance of the build and deployment ▪ Security ▪ Smaller image have less libraries and tools ▪ Reduces the attack surface ▪ Maintainability ▪ Installing dependencies to a small base image gives you control over the dependency ▪ Modifying dependencies becomes more easy

Slide 18

Slide 18 text

IMAGE SIZE ASP.NET Default Image

Slide 19

Slide 19 text

IMAGE SIZE ASP.NET Default Image The default image used is based on Debian Linux

Slide 20

Slide 20 text

IMAGE SIZE Reduce image size - Use Alpine base image ▪ Alpine is a very small distro ▪ Tools and libraries for debugging could be missing ▪ Fast and easy change

Slide 21

Slide 21 text

▪ Trim application dependencies to a subset of the framework ▪ Possible to publish the application as single file ▪ Use alpine for best effort ▪ Complex changes in Dockerfile IMAGE SIZE Reduce image size - Self containing .NET application .NET 7 .NET 8

Slide 22

Slide 22 text

IMAGE SIZE Future with Ubuntu chiseled images ▪ Distroless base images powered by Ubuntu ▪ General available ▪ .NET 8 ▪ Also .NET 6 & 7 ▪ Features ▪ Ultra-small size, which reduces the potential attack surface ▪ No package manager or shell installed ▪ Uses a non-root user by default Using .NET with Chiseled Ubuntu Containers | .NET Conf 2022 - YouTube dotnet-docker/documentation/ubuntu-chiseled.md (github.com) Announcing .NET Chiseled Containers - .NET Blog (microsoft.com)

Slide 23

Slide 23 text

BUILD IMAGES Best practices Use linting Hadolint

Slide 24

Slide 24 text

BASE IMAGES Know the source Use trusthworthy images

Slide 25

Slide 25 text

Application configuration Docker image Image best practices

Slide 26

Slide 26 text

Container Security

Slide 27

Slide 27 text

CONTAINER SECURITY Attack surfaces of container applications ▪ Container Host ▪ Base Image ▪ Application Image ▪ Application ▪ OWASP vulnerabilities ▪ Outdated/vulnerable dependecies

Slide 28

Slide 28 text

SECURITY OPTIMIZATIONS Remove unused tools and libraries ▪ Use a small image ▪ Small images will not contain many distro tools ▪ Minimizes attack vector ▪ Most tools are not required to run your application

Slide 29

Slide 29 text

SECURITY OPTIMIZATIONS Run application as non-root ▪ Restrict application execution to specific non-root user ▪ Not allowed to install tools (e.g., via apt-get) ▪ Not allowed to execute privileged scripts ▪ Not allowed to adjust permissions ▪ Not allowed to bind privilege ports ▪ The non-root user will be restricted, even if the container itself is privileged ▪ Container Compliance ▪ CIS (Center for Internet Security) ▪ NIST (National Institute of Standards and Technology) ▪ Run the application as a specific user RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app USER appuser

Slide 30

Slide 30 text

RUN SECURE CONTAINERS File system Tip: Use readonly file system

Slide 31

Slide 31 text

RUN SECURE CONTAINERS Read-only file system ▪ No changes to file system allowed ▪ Prohibit attackers to download scripts (e.g. with curl) ▪ Configurable for container execution ▪ How to apply ▪ Kubernetes: Set readOnlyRootFilesystem: true in yaml-Manifest ▪ Docker: Run container with option --read-only ▪ Warning: Some applications or dependencies need to write to the file system ▪ E.g., for temp files, lock files ▪ Solution: Use temporary file system (tmpfs, Docker) or ephemeral volumes (emptyDir, Kubernetes)

Slide 32

Slide 32 text

VULNERABILITY SCANNING Check for vulnerabilities ▪ Risk Mitigation: Identify security risks before deploying to production ▪ Early Detection: Catch vulnerabilities at an early stage of development ▪ Third-Party Component Analysis: Get insights into the security of dependencies ▪ Improved Security Hygiene: Encourages a culture of security awareness ▪ Tools ▪ Trivy (aquasecurity/trivy: Find vulnerabilities, misconfigurations, secrets, SBOM in containers, Kubernetes, code repositories, clouds and more (github.com)) ▪ Claire (quay/clair: Vulnerability Static Analysis for Containers (github.com)) ▪ Snyk (Container vulnerability management and Kubernetes workload security | Snyk) ▪ Docker Scout (Container Security Monitoring for Developers | Docker)

Slide 33

Slide 33 text

▪ Targets ▪ Container Images ▪ Filesystem ▪ Kubernetes ▪ and many more … ▪ Scanners ▪ OS packages and software dependencies in use (SBOM) ▪ Known vulnerabilities (CVEs) ▪ IaC issues and misconfigurations ▪ Sensitive information and secrets ▪ Software licenses VULNERABILITY SCANNING Trivy

Slide 34

Slide 34 text

VULNERABILITY SCANNING Resolve vulnerabilities in images ▪ Check for updates of the base image ▪ Use another base image with less depedencies ▪ Use Copacetic to rectivy vulnerabilities ▪ project-copacetic/copacetic: CLI tool for directly patching container images using reports from vulnerability scanners (github.com) ▪ Use obtained knowledge to close gaps ▪ Remove application dependencies ▪ Update infrastructure (e.g., close firewall on port 22) ▪ Run vulnerability checks frequently ▪ Check images during CI/CD process ▪ Many cloud providers have integrated vulnerability scanning (e.g., Microsoft Defender for Cloud)

Slide 35

Slide 35 text

SIGNING IMAGES Why signing container images ▪ Integrity: Image downloaded matches image originally built ▪ Non-repudiation: Be certained who created the image ▪ Tools ▪ Notation CLI (notaryproject/notation: A CLI tool to sign and verify artifacts (github.com)) ▪ Sigstore Cosign (sigstore/cosign: Container Signing (github.com)) ▪ Docker CLI Content Trust (Content trust in Docker | Docker Docs)

Slide 36

Slide 36 text

SIGNING IMAGES Notation ▪ Notation CLI: Signing and verifying container images and OCI artifacts ▪ Easy to use ▪ Integration into CI/CD pipelines ▪ Plugin system ▪ Azure Key Vault (Azure/notation-azure-kv: Azure Provider for Notation CLI (github.com)) ▪ AWS (Prerequisites for signing container images - AWS Signer (amazon.com))

Slide 37

Slide 37 text

SIGNING IMAGES Signing process Announcing Notation Azure Key Vault plugin v1.0 for signing container images (microsoft.com) Dev Ops

Slide 38

Slide 38 text

Run application as non-root Vulnerability scan Signing images

Slide 39

Slide 39 text

Multi-architecture images

Slide 40

Slide 40 text

MULTI-ARCHITECTURE IMAGES Advantages of multi-architecture images ▪ Developers use different OSes and architectures ▪ ARM getting more popular ▪ Performance benefits ▪ Energy efficient ▪ Cloud providers offer x64 and arm container environments ▪ Azure Kubernetes Services ▪ AWS Elastic Kubernetes Services

Slide 41

Slide 41 text

MULTI-ARCHITECTURE IMAGES Running Container Workloads x64 arm x64 arm

Slide 42

Slide 42 text

MULTI-ARCHITECTURE IMAGES Running Container Workloads x64 arm x64 arm docker buildx

Slide 43

Slide 43 text

MULTI-ARCHITECTURE IMAGES Multi-arch image manifest Example: mcr.microsoft.com/dotnet/aspnet:7.0 architecture: amd64 os: linux architecture: arm os: linux variant: v7 architecture: arm64 os: linux architecture: amd64 os: windows os.version: 10.0.17763.4851 architecture: amd64 os: windows os.version: 10.0.20348.1970

Slide 44

Slide 44 text

MULTI-ARCHITECTURE IMAGES Build with Docker Buildx ▪ Docker Buildx is a tool to create multi-architecture images on the fly ▪ Released in 2019 (included in Docker version 19.03) ▪ Uses BuildKit to create images ▪ Think of it as A single container image contains multiple versions of your application, each targeting a specific OS and architecture

Slide 45

Slide 45 text

MULTI-ARCHITECTURE IMAGES Configure buildx ▪ Setting up a new builder docker buildx create --name mybuilder --platform linux/amd64,linux/arm64 --use ▪ Check the new builder docker buildx inspect ▪ Build multi-arch container docker buildx build --platform linux/amd64,linux/arm64 --load -t sample-app:1.0.0 . ▪ Inspect multi-arch images docker buildx imagetools inspect sample-app:1.0.0

Slide 46

Slide 46 text

MULTI-ARCHITECTURE IMAGES Update DOCKERFILE for .NET applications ▪ Use docker’s automatic platform args to configure platform and architecture settings ▪ Dockerfile reference - Automatic platform ARGs in the global scope | Docker Docs ▪ Set build platform FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:8.0 AS build ▪ Add target architecture argument ARG TARGETARCH ▪ Set architecture on dotnet build and publish RUN dotnet build „MyProject.csproj" -c Release \ -a $TARGETARCH

Slide 47

Slide 47 text

Build multi-arch image

Slide 48

Slide 48 text

QUESTIONS?

Slide 49

Slide 49 text

RESOURCES Links ▪ daniellindemann/dotnet-container-optimization: Repository to show container optimizations for .NET applications (github.com)

Slide 50

Slide 50 text

Nehmen Sie Kontakt mit uns auf. www.abtis.de +49 7231 4431 - 100 [email protected] abtis GmbH • Wilhelm-Becker-Straße 11b • 75179 Pforzheim © 2023 Alle Rechte vorbehalten. Dieses Dokument ist urheberrechtlich geschützt. Sämtliche Inhalte dienen der Dokumentation. Jede andere Nutzung, insbesondere die Weitergabe an Dritte, die Verbreitung oder die Bearbeitung, auch in Teilen, ist ohne schriftliche Einwilligung der abtis GmbH untersagt. Die verwendeten Firmen-, Marken- und Produktnamen und Warenzeichen sind eingetragene Markenzeichen oder Warenzeichen der jeweiligen Inhaber und werden hiermit anerkannt. Die abtis GmbH verfügt über mehr als 20 Jahre Erfahrung in der Planung und dem Betrieb von Microsoft Infrastrukturen und betreut bereits mehr als 100.000 Anwender:innen der Cloudplattformen Microsoft 365 und Azure. Ausgezeichnet als Microsoft Solutions Partner und MXDR Verified Partner mit 12 Advanced Specializations sind wir einer der wichtigsten Fokuspartner von Microsoft für den Mittelstand in Deutschland. Damit setzen wir ein starkes Zeichen als verlässlicher Partner und Vorreiter in der IT-Branche. Die abtis GmbH ist Teil der abtis Gruppe, die mit vier Tochterunternehmen und über 170 Mitarbeitenden ein fester Bestandteil der IT-Welt ist. Das Portfolio der abtis Gruppe umfasst die Kernthemen einer zukunftsorientierten IT: von Modern Workplace, über Datacenter, Security, Power Platform, Application Development, Industrial IoT, Adoption & Change Management bis hin zu Data & AI.