📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is a container, and how is it different from a virtual machine? Explain images versus containers, image layers, and why most teams now ship .NET services as containers.

Containers versus VMs (shared kernel, namespaces and cgroups), images versus running containers, layered images and caching, and why .NET 10 services are shipped as container images.

Junior Theory Beginner containers devops docker dotnet oci-images virtual-machines

🎯 Key points

  • Container = isolated process sharing the host kernel (namespaces + cgroups)
  • VM = full guest OS on a hypervisor; stronger isolation, heavier
  • Image = read-only, layered OCI template; container = running instance with a writable layer
  • Layers are content-addressed and cached; order Dockerfile steps for cache hits
  • Linux containers need a Linux kernel; Windows containers need Windows
  • Benefits: same artefact dev to prod, fast start, density, immutable deploys
  • .NET images from mcr.microsoft.com: sdk to build, aspnet/runtime/runtime-deps to run
  • Containers are not a security boundary as strong as a VM

⏱ 30-second answer

A container is an ordinary process that the Linux kernel isolates with namespaces (its own view of files, network, process IDs) and limits with cgroups (CPU and memory). A virtual machine runs a whole guest operating system on a hypervisor. Containers share the host kernel, so they start in milliseconds and pack densely; VMs isolate more strongly but are heavier.

An image is the read-only, layered template (an OCI image); a container is a running instance of it with a thin writable layer on top. Layers are cached and shared, so rebuilds and pulls are fast.

We ship .NET services as containers because the same immutable artefact runs on a laptop, in CI and in Azure Container Apps or AKS. The trade-off: weaker isolation than a VM and a new set of things to operate.

🗣 Full answer (senior)

How I would answer this in an interview

"A container is not a tiny VM. It is a normal Linux process that the kernel fences off. Namespaces give it its own view of the file system, network interfaces, hostname and process IDs, and cgroups cap how much CPU and memory it can use. Because every container on a host shares the same kernel, there is no guest OS to boot, so a container starts in well under a second and I can run dozens on one node. A virtual machine emulates hardware through a hypervisor and boots a full operating system, so it is heavier but gives a much stronger isolation boundary.

An image is the template: a stack of read-only, content-addressed layers plus metadata such as the entry point, environment variables and exposed port, in the OCI format. When I run it I get a container: those layers plus a thin writable layer that disappears when the container is removed. Each Dockerfile instruction that changes files makes a layer, and layers are cached, so if I copy the .csproj and restore before copying the source, a code change only rebuilds the last layers. For .NET, Microsoft publishes images on mcr.microsoft.com: dotnet/sdk to build, and dotnet/aspnet, dotnet/runtime or dotnet/runtime-deps to run.

The reason teams ship containers is the artefact: the image tested in CI is byte-for-byte the image that runs in production, with the runtime and native dependencies baked in. That removes 'works on my machine' and makes rollback a matter of pointing at the previous tag. The mistake I see is treating a container like a pet server: SSHing in, patching it, writing data to its file system. Containers are disposable; state goes in a database, blob storage or a volume."


Containers versus virtual machines

Container Virtual machine
Isolation mechanism Kernel namespaces + cgroups Hypervisor, separate kernel
Kernel Shared with host Own guest kernel
Start time Milliseconds to ~1 s Tens of seconds to minutes
Size Tens to hundreds of MB GBs
Density High Lower
Security boundary Weaker (kernel exploit escapes) Stronger
Typical .NET use APIs, workers on Container Apps / AKS Legacy IIS apps, domain-joined workloads

Image versus container

Term What it is
Image Read-only layered template + config (entry point, env, user, port)
Layer A diff of file-system changes, identified by its SHA-256 digest
Tag A movable, human name for an image (orders-api:1.4.2)
Digest Immutable ID (@sha256:...); what you pin for reproducibility
Container A running (or stopped) instance: image layers + writable layer
Registry Stores and serves images (Azure Container Registry, Docker Hub, GHCR)

When containers are not the answer

  • A single small web app where App Service code deployment already gives you slots and patching.
  • Workloads tied to Windows features (full IIS, COM, GAC). Windows containers exist but are large and less supported on managed platforms.
  • When you need a hard multi-tenant security boundary: use VMs or sandboxed runtimes.

Production example

A team moved a .NET API from a hand-built VM to a container on Azure Container Apps. Deployments went from a 25-minute scripted copy with occasional config drift to a 90-second image swap, and rollback became choosing the previous revision. The image was 120 MB on the chiseled ASP.NET base, and cold start was about 1.5 seconds.

🔍 What the interviewer is checking

Checks that the candidate understands what a container really is and why it changes delivery, not just the Docker commands.

Green flags

  • Mentions namespaces, cgroups and the shared kernel
  • Explains layers and caching, and the image versus container distinction
  • Knows the .NET image family and building with sdk, running with aspnet
  • Says containers are disposable and state lives elsewhere

Red flags

  • "A container is a small VM"
  • Thinks deleting a file in a later layer removes it from the image
  • No idea why the same image across environments matters

📚 Learn in depth

1. What the kernel actually does

           Host (Linux kernel)
 ┌─────────────────────────────────────────────┐
 │  cgroups: cpu.max, memory.max per container │
 │  namespaces: pid, net, mnt, uts, ipc, user  │
 │                                             │
 │  ┌────────────┐  ┌────────────┐             │
 │  │ orders-api │  │  worker    │  processes  │
 │  │ PID 1      │  │ PID 1      │  (own view) │
 │  └────────────┘  └────────────┘             │
 └─────────────────────────────────────────────┘
  • pid namespace: your app is PID 1 inside the container, so it must handle SIGTERM (ASP.NET Core's host does this and triggers graceful shutdown).
  • net namespace: own interfaces and ports; the container listens on 8080 and the runtime maps it.
  • mnt namespace: own root file system, assembled from image layers by a union file system (overlayfs).
  • cgroups v2: memory.max and cpu.max. The .NET runtime reads these, so Environment.ProcessorCount and the GC heap limit follow the container limits, not the host.

2. How layers work

Overlayfs stacks read-only lower directories (image layers) under one writable upper directory. Reading a file finds the top-most copy; writing a file copies it up first (copy-on-write). Deleting writes a "whiteout" marker, so deleting a file in a later layer does not shrink the image. This is why secrets copied in an early layer stay in the image even if a later step deletes them.

3. The OCI standards

The Open Container Initiative defines the image spec (manifest, config, layers), the runtime spec (what runc does) and the distribution spec (registry API). Docker, Podman, containerd, Kubernetes and dotnet publish all speak OCI, which is why an image built by the .NET SDK runs on AKS.

4. .NET base images

Image Contains Use
dotnet/sdk:10.0 SDK, compilers, NuGet Build stage only
dotnet/aspnet:10.0 ASP.NET Core + .NET runtime Web APIs
dotnet/runtime:10.0 .NET runtime Workers, console apps
dotnet/runtime-deps:10.0 Native deps only Self-contained or Native AOT apps
-noble-chiseled variants Ubuntu Chiseled: no shell, no package manager, non-root Smaller attack surface

Since .NET 8 the images listen on port 8080 by default and include a non-root app user, so you can run without root.

5. Containers and security

A kernel vulnerability can let a process escape every container on the host. Mitigations: run as non-root, drop Linux capabilities, read-only root file system, small base images, scan images (Microsoft Defender for Containers, Trivy), and keep nodes patched. That maps to ACSC Essential Eight items such as patching applications and restricting admin privileges.

Try it yourself

  1. Run docker run --rm -it mcr.microsoft.com/dotnet/runtime-deps:10.0 ps aux and see that only one process exists.
  2. Run docker history mcr.microsoft.com/dotnet/aspnet:10.0 and read the layers and their sizes.
  3. Start a container with --memory 256m --cpus 1 and print Environment.ProcessorCount and GC.GetGCMemoryInfo().TotalAvailableMemoryBytes from a tiny app.
  4. Build an image, change one .cs file, rebuild and watch which steps say CACHED.
  5. Create a file in a container, remove the container and start a new one: the file is gone.

💻 Code

A tiny app that shows the runtime sees the container's limits, not the host's:

// Program.cs (.NET 10, top-level statements, nullable enabled)
var gcInfo = GC.GetGCMemoryInfo();

Console.WriteLine($"Processors seen by .NET: {Environment.ProcessorCount}");
Console.WriteLine($"Memory available to GC: {gcInfo.TotalAvailableMemoryBytes / 1024 / 1024} MB");
Console.WriteLine($"Running in container: {Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") ?? "false"}");
# Build and run it with limits; .NET reads cgroup limits automatically
docker build -t limits-demo .
docker run --rm --memory 512m --cpus 2 limits-demo
# Processors seen by .NET: 2
# Memory available to GC: ~384 MB  (75% of the limit by default)
# Running in container: true
# Minimal two-stage Dockerfile for the demo
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/runtime:10.0
WORKDIR /app
COPY --from=build /app .
USER $APP_UID
ENTRYPOINT ["dotnet", "LimitsDemo.dll"]

⚠ Common mistakes

  • Mistake: Calling a container a lightweight VM. Why it is wrong: It shares the host kernel; there is no guest OS, and isolation is weaker. Instead: Describe it as an isolated process using namespaces and cgroups.
  • Mistake: Writing important data to the container file system. Why it is wrong: The writable layer is lost when the container is replaced, which happens on every deploy. Instead: Use a database, Blob Storage or a mounted volume.
  • Mistake: Deleting a secret in a later Dockerfile step and assuming it is gone. Why it is wrong: Earlier layers still contain it and anyone who pulls the image can extract it. Instead: Use build secrets (--mount=type=secret) and runtime managed identity.
  • Mistake: Deploying with the latest tag. Why it is wrong: It moves, so you cannot tell what is running or roll back reliably. Instead: Tag with a version or commit SHA and pin by digest where it matters.
  • Mistake: Patching a running container by hand. Why it is wrong: The fix vanishes on restart and the image drifts from what was tested. Instead: Rebuild the image and redeploy.
  • Mistake: Shipping the SDK image to production. Why it is wrong: It is several times larger and includes compilers and tools an attacker can use. Instead: Build with sdk, run on aspnet or a chiseled image.

🏛 Senior insight: trade-offs

Containers standardise the artefact and the runtime contract (port, environment variables, signals, health endpoints), not the platform. That is their real value: the same image runs on Container Apps, AKS, App Service for Containers or ECS, so the hosting decision can change without touching the app. What they don't give you for free is patching: you now own the base image cadence, so rebuild on every Microsoft image update (monthly Patch Tuesday) and scan in CI.

Option When it fits Cost When not to
Container Microservices, portable deploys, CI parity Image patching, registry, orchestration One small app where code deploy is enough
VM Legacy Windows/IIS, strong isolation OS patching, slow deploys New cloud-native services
App Service code deploy Few web apps, minimal ops Platform lock-in, less control Many services, custom native deps

I measure it by deployment lead time, image size and vulnerability count from the registry scanner.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions building images for .NET apps Why: Checks they know the publish options, including SDK container support and self-contained builds
    How to answer

    By default dotnet publish gives a framework-dependent folder that needs the .NET runtime on the server. Self-contained (--self-contained -r linux-x64) bundles the runtime, so nothing needs installing, but the output is bigger and you patch the runtime by redeploying. On top of that: single-file packs everything into one executable, trimming removes unused code, ReadyToRun precompiles to speed up start-up, and Native AOT compiles to a native binary with very fast start-up and low memory but no dynamic code generation. The SDK can also build a container image directly. I choose based on where it runs, start-up and memory needs, and whether the libraries are trim- and AOT-safe, and I measure the result.

  2. When: Candidate mentions ports or the default 8080 port Why: Checks they can debug a container that does not answer on its port
    How to answer

    A port is a 16-bit number (0 to 65535) that lets one IP address host many services. A socket is the OS object for one endpoint: a listening socket bound to IP:port, and a connected socket for each accepted connection, identified by the 4-tuple (client IP, client port, server IP, server port).

    The Docker problem is almost always binding: the app listens on localhost (127.0.0.1) inside the container, which is unreachable from outside its network namespace, or it listens on a different port from the one you mapped. The official .NET 10 images set ASPNETCORE_HTTP_PORTS=8080, which binds all interfaces on 8080 (the default since .NET 8), so map it with -p 5000:8080 and do not override it with a localhost URL.

  3. When: Candidate says they build with sdk and run with aspnet Why: Checks they can choose a base image for size, security and app type
    How to answer

    sdk (mcr.microsoft.com/dotnet/sdk:10.0) has the full SDK, compilers and NuGet; use it only in the build stage and CI. aspnet has the ASP.NET Core and .NET runtimes: the default for web APIs. runtime has just the .NET runtime, for workers and console apps. runtime-deps has only the native libraries .NET needs (libc, OpenSSL, ICU where included), for self-contained apps and Native AOT (ahead-of-time compiled to native code, so no runtime or JIT is needed: faster start and less memory, but trimming and reflection limits).

    Chiseled Ubuntu variants (-noble-chiseled, plus -extra with ICU and tzdata) remove the shell and package manager and run as non-root: about 100 MB smaller than full images and far fewer OS CVEs. The trade-off is debugging: no shell, so you use ephemeral debug containers.

↩ Usually asked after

More in Containers

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me