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

📚 Interview question

Code review: a teammate submits a Dockerfile that builds and runs a .NET 10 API on the SDK image as root, plus a Kubernetes Deployment with one replica, no probes, no resource requests or limits, the latest image tag, and the database password in a plain env var. What do you flag, in what order, and what does the fixed version look like?

Reviewing a .NET 10 Dockerfile and Kubernetes manifest: SDK image in production, root user, secrets in env vars, :latest tags, missing probes, missing requests/limits, single replica, shell-form entry point; findings ranked by severity with a rewrite and review close-out.

Senior CodeReview Advanced code-review containers devops dockerfile kubernetes security

🎯 Key points

  • Secret in plain env var / manifest is the top blocker: rotate it, move to Workload Identity or Key Vault
  • Root user and SDK runtime image: attack surface and CVEs; multi-stage, chiseled, runAsNonRoot
  • :latest tag breaks reproducibility and rollback; tag by version/SHA, pin digest
  • No probes: traffic to unready pods, hung pods never restarted
  • No requests/limits: noisy neighbour, eviction, OOM, unpredictable .NET ProcessorCount/GC
  • Single replica, no PDB: downtime on every rollout and node drain
  • Shell-form ENTRYPOINT breaks SIGTERM and graceful shutdown
  • Close with blocking vs suggested comments, policy (Azure Policy/Gatekeeper), and image scanning in CI

⏱ 30-second answer

I rank by blast radius. Blocking first: the database password in a plain env var in Git (rotate it now, then use Workload Identity with Entra authentication to Azure SQL, or Key Vault); running as root on the SDK image (huge attack surface, compilers and a shell for an attacker: multi-stage build, chiseled runtime, runAsNonRoot).

Then reliability: :latest (you can't tell what's running or roll back: use version or SHA tags), no probes (traffic hits unready pods, hung pods never restart), no requests or limits (noisy neighbours, evictions, and .NET sizing itself to the whole node), one replica (downtime on every deploy).

Then diagnostics and polish: exec-form entry point for SIGTERM, .dockerignore, labels. I close with policy so the cluster rejects these by default.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd review it in order of what can hurt us most. The first blocker is the database password in a plain environment variable in the manifest. It's in Git history, visible to anyone with read access to the repo or kubectl get deploy -o yaml, and it'll show up in crash dumps. So I'd ask for the password to be rotated today, not just moved, and the app switched to Microsoft Entra Workload ID: the pod's service account federates to a managed identity, and Authentication=Active Directory Default in the SqlClient connection string means no password exists at all. The second blocker is running as root on the SDK image: 800-plus MB, a compiler, a shell and package managers in production, and root inside the container makes an escape far easier. Multi-stage build, chiseled aspnet runtime, non-root user, runAsNonRoot and a read-only root file system.

Then reliability. :latest means two pods can run different code and rollback is guesswork, so tag by version or commit SHA. No probes means Kubernetes sends traffic during startup and never restarts a hung process. No requests or limits means the scheduler can pack it anywhere, it's first to be evicted, and because there's no CPU limit .NET sizes its thread pool and Server GC to every core on the node. One replica with no PodDisruptionBudget means every rollout and node upgrade is an outage. And the shell-form ENTRYPOINT means /bin/sh is PID 1, SIGTERM never reaches Kestrel, and in-flight requests are cut after 30 seconds.

For example, at [company] I reviewed [a similar PR for a new service]. I marked the secret and root user as blocking, paired with the author on the rewrite, and then we added [Azure Policy for AKS rules] so the cluster rejects root containers and missing limits. [The next quarter's audit had zero container findings.] The mistake I see in reviews is leading with style nits and burying the leaked password at comment twelve."


Code under review

FROM mcr.microsoft.com/dotnet/sdk:10.0          # 1 SDK image in production, runs as root
WORKDIR /app
COPY . .                                        # 2 no .dockerignore, no restore caching
RUN dotnet publish -c Release -o out
ENTRYPOINT dotnet out/Orders.Api.dll            # 3 shell form: SIGTERM not forwarded
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-api }
spec:
  replicas: 1                                   # 4 single replica, no PDB
  selector: { matchLabels: { app: orders-api } }
  template:
    metadata: { labels: { app: orders-api } }
    spec:
      containers:
        - name: api
          image: crorders.azurecr.io/orders-api:latest   # 5 mutable tag
          env:
            - name: ConnectionStrings__Default
              value: "Server=sql-orders.database.windows.net;User Id=app;Password=Sup3rS3cret!"  # 6 secret in plain text
          # 7 no probes
          # 8 no resources
          # 9 no securityContext

Findings, ranked by severity

# Severity Finding Fix
6 Blocking: security Password in plain text in Git and the pod spec Rotate now; Workload Identity + Entra auth to Azure SQL
1, 9 Blocking: security SDK image and root at runtime; no security context Multi-stage, chiseled runtime, runAsNonRoot, drop capabilities, read-only root FS
5 Blocking: release safety :latest tag Version/SHA tag; digest pinning in CD
7 Blocking: availability No startup/readiness/liveness probes Health endpoints and three probes
4 Blocking: availability One replica, no PDB 2+ replicas, PDB minAvailable: 1, maxUnavailable: 0
8 High: stability No requests/limits Requests from load tests, memory limit = request, generous CPU limit
3 High: data loss on deploy Shell-form entry point Exec form so Kestrel gets SIGTERM and drains
2 Medium: build No .dockerignore, restore not cached Copy project files and restore first

The rewrite

See the code example for the full Dockerfile and manifest.

How I'd close the review

  • Blocking: secret (with rotation confirmed), root/SDK image, :latest, probes, replicas.
  • Suggested: resource numbers from a load test, .dockerignore, OCI labels.
  • Systemic: Azure Policy for AKS / Gatekeeper constraints (no root, no :latest, requests required), secret scanning (GitHub push protection), image scanning with Defender for Containers or Trivy as a CI gate, and a shared Helm chart so the next service starts compliant.

Production example

After this kind of rewrite, the image went from 860 MB to 115 MB, high-severity CVEs from 38 to 0, and rollouts stopped producing 502s because readiness probes and two replicas kept capacity during every deploy.

🔍 What the interviewer is checking

Checks that the candidate can prioritise container and Kubernetes review findings by real risk and turn them into lasting guardrails.

Green flags

  • Leads with the leaked secret and insists on rotation
  • Explains root/SDK image risk and the chiseled, non-root fix
  • Catches :latest, probes, replicas, resources and shell-form entry point with reasons
  • Proposes Workload Identity instead of moving the password around
  • Closes with policy, scanning and a shared template

Red flags

  • Treats all findings as equal or starts with formatting
  • Moves the password into a Kubernetes Secret and stops
  • Doesn't know why PID 1 and SIGTERM matter

📚 Learn in depth

1. Why the secret is the top finding

A secret in a manifest is exposed in at least four places: Git history (forever, even after a revert), the cluster's etcd, kubectl get output for anyone with read access, and process environment visible in dumps and /proc/1/environ. Under the Privacy Act 1988, a breach of a database holding personal information may be an eligible data breach under the Notifiable Data Breaches scheme. Rotation is mandatory because you can't prove nobody copied it.

The passwordless path on AKS:

 Pod (service account orders-api, label azure.workload.identity/use=true)
   │ projected service account token (OIDC)
   ▼
 Microsoft Entra ID ── federated credential trusts the AKS OIDC issuer + SA name
   │ access token for the user-assigned managed identity
   ▼
 Azure SQL (CREATE USER [id-orders-api] FROM EXTERNAL PROVIDER)

2. Root and the SDK image

Container isolation relies on the shared kernel. Root in the container is UID 0 on the host unless user namespaces are used, so a kernel or runtime bug gives much more power. The SDK image adds compilers, curl, git and a shell that make post-exploitation easy. Chiseled images have no shell or package manager, which also removes most OS CVEs. Kubernetes securityContext enforces this: runAsNonRoot, allowPrivilegeEscalation: false, capabilities.drop: [ALL], readOnlyRootFilesystem: true, seccompProfile: RuntimeDefault. These are the "restricted" Pod Security Standard.

3. Mutable tags

:latest with imagePullPolicy: Always means a pod restarted at 3 am can pull a different image from the one running on its siblings. Rollback (kubectl rollout undo) re-applies the same :latest string and achieves nothing. Tag by semantic version and commit SHA; CD can resolve to a digest (@sha256:...) so what runs is exactly what was scanned.

4. Probes and replicas

Without readiness, a new pod receives traffic as soon as the container starts, while .NET is still JIT-compiling and warming connections: 502s on every deploy. Without liveness, a deadlocked process stays in rotation forever. With one replica, a node drain (AKS upgrades happen several times a year) is downtime. A PodDisruptionBudget stops voluntary disruptions from taking all replicas.

5. Resources and the runtime

No requests means BestEffort QoS, first to be evicted. No CPU limit means Environment.ProcessorCount equals node cores, so the Server GC and thread pool size themselves for the whole node. Memory without a limit can grow until the node is under pressure, affecting other pods.

6. PID 1 and signals

Shell form runs /bin/sh -c "dotnet ...". The shell is PID 1 and does not forward SIGTERM; after terminationGracePeriodSeconds the kubelet sends SIGKILL and in-flight requests die. Exec form makes dotnet PID 1, and the .NET host's SIGTERM handler triggers IHostApplicationLifetime.ApplicationStopping and Kestrel draining.

Try it yourself

  1. Run trivy image on the original and rewritten images and compare.
  2. Apply the original manifest to a cluster with the Pod Security Admission restricted level and read the rejection.
  3. Run the shell-form image, send docker stop, and time how long it takes (10 s timeout = SIGKILL).
  4. Deploy with one replica and run kubectl drain on its node while load testing.
  5. Set up Workload Identity in a test AKS cluster and connect to Azure SQL with no password.

💻 Code

The rewritten Dockerfile:

# syntax=docker/dockerfile:1
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY src/Orders.Api/Orders.Api.csproj src/Orders.Api/
RUN dotnet restore src/Orders.Api/Orders.Api.csproj
COPY src/ src/
RUN dotnet publish src/Orders.Api/Orders.Api.csproj -c Release --no-restore -o /app/publish

FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled
WORKDIR /app
COPY --from=build /app/publish .
# chiseled: non-root 'app' user by default, no shell
ENTRYPOINT ["dotnet", "Orders.Api.dll"]

The rewritten manifest:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: orders-api
  annotations:
    azure.workload.identity/client-id: "<managed-identity-client-id>"
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: orders-api }
spec:
  replicas: 3
  strategy: { rollingUpdate: { maxSurge: 1, maxUnavailable: 0 } }
  selector: { matchLabels: { app: orders-api } }
  template:
    metadata:
      labels: { app: orders-api, azure.workload.identity/use: "true" }
    spec:
      serviceAccountName: orders-api
      securityContext:
        runAsNonRoot: true
        seccompProfile: { type: RuntimeDefault }
      containers:
        - name: api
          image: crorders.azurecr.io/orders-api:1.4.2-3f9c2ab   # version + commit SHA
          ports: [{ containerPort: 8080 }]
          env:
            # No password: Entra authentication through Workload Identity
            - name: ConnectionStrings__Default
              value: "Server=sql-orders.database.windows.net;Database=Orders;Authentication=Active Directory Default;Encrypt=True"
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
          resources:
            requests: { cpu: 500m, memory: 512Mi }
            limits: { cpu: "2", memory: 512Mi }
          startupProbe:   { httpGet: { path: /healthz/live,  port: 8080 }, periodSeconds: 2, failureThreshold: 30 }
          livenessProbe:  { httpGet: { path: /healthz/live,  port: 8080 }, periodSeconds: 10 }
          readinessProbe: { httpGet: { path: /healthz/ready, port: 8080 }, periodSeconds: 5 }
          volumeMounts: [{ name: tmp, mountPath: /tmp }]
      volumes: [{ name: tmp, emptyDir: {} }]
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata: { name: orders-api }
spec:
  minAvailable: 2
  selector: { matchLabels: { app: orders-api } }

The app side: health checks and passwordless SQL:

using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

// 'Authentication=Active Directory Default' makes SqlClient use DefaultAzureCredential,
// which picks up the Workload Identity token in the pod.
builder.Services.AddDbContext<OrdersDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Default")));

builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
    .AddDbContextCheck<OrdersDbContext>(tags: ["ready"]);

var app = builder.Build();
app.MapHealthChecks("/healthz/live", new() { Predicate = r => r.Tags.Contains("live") });
app.MapHealthChecks("/healthz/ready", new() { Predicate = r => r.Tags.Contains("ready") });
app.Run();

⚠ Common mistakes

  • Mistake: Moving the leaked password into a Kubernetes Secret and calling it fixed. Why it is wrong: The old value is still in Git history and Secrets are only base64. Instead: Rotate it, then remove the password entirely with Workload Identity.
  • Mistake: Leading the review with style comments. Why it is wrong: The author fixes the easy ones and the security blocker gets lost. Instead: Rank by severity and mark blocking items clearly.
  • Mistake: Accepting :latest because "CI always pushes the newest". Why it is wrong: Pods restart at different times and pull different images; rollback re-applies the same tag. Instead: Immutable version/SHA tags.
  • Mistake: Adding a liveness probe that checks the database. Why it is wrong: A database blip restarts every pod. Instead: Liveness checks the process; readiness checks dependencies if at all.
  • Mistake: Setting readOnlyRootFilesystem without testing. Why it is wrong: .NET and some libraries write to /tmp, so the app fails at runtime. Instead: Mount an emptyDir at /tmp and test in a lower environment.
  • Mistake: Fixing only this PR. Why it is wrong: The next service repeats the same problems. Instead: Policy (Azure Policy for AKS, Pod Security Admission restricted), a shared chart and CI image scanning.

🏛 Senior insight: trade-offs

A good container review is a security and operability review first and a YAML review second. My heuristic order is: secrets, privilege, supply chain (base image, tags, scanning), availability (probes, replicas, PDB, shutdown), resources, then build hygiene. The senior move is to turn each finding into a guardrail so reviewers don't have to catch it again: admission policies that reject root and :latest, push protection for secrets, and a paved-road chart or template.

Control When it fits Cost When not to
Review checklist Every team Reviewer time, inconsistent As the only control
Azure Policy for AKS / Gatekeeper Shared clusters, compliance needs Policy upkeep, exemptions process Throwaway dev clusters
Shared Helm chart / template Many services Chart maintenance One-off experiments
CI image scanning gate All production images Build time, false positives to triage Never skip for prod

This maps directly to ACSC Essential Eight themes: restrict administrative privileges, patch applications, and application control. I measure: policy violations blocked per month, CVEs per image, and rollouts causing errors.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate rewrites the Dockerfile Why: Checks depth on multi-stage builds, caching and non-root images
    How to answer

    I use a multi-stage build: the first stage uses mcr.microsoft.com/dotnet/sdk:10.0, copies only the project files and runs dotnet restore so that layer is cached until a package changes, then copies the source and runs dotnet publish -c Release. The final stage starts from dotnet/aspnet:10.0-noble-chiseled, copies only the publish output, and runs as the built-in non-root user on port 8080.

    The result is roughly 100–130 MB instead of 800+ MB, with no compilers, no shell and no root.

    For straightforward apps I often skip the Dockerfile: dotnet publish /t:PublishContainer builds an OCI image straight from MSBuild with sensible defaults. The trade-off: the Dockerfile gives full control (native packages, custom steps); SDK containers give less to maintain.

  2. When: Candidate asks for requests and limits Why: Checks how they would size the pod for the .NET runtime
    How to answer

    Requests are what the scheduler reserves and set the pod's QoS class; limits are enforced by cgroups: exceed the memory limit and the container is OOMKilled, exceed the CPU limit and it is throttled within each 100 ms CFS period.

    The .NET runtime reads the cgroup limits: Environment.ProcessorCount follows the CPU limit (rounded up) and the GC's heap hard limit defaults to 75% of the memory limit. With no CPU limit, .NET sees every node core.

    I set memory request equal to limit, sized from load tests with headroom for native memory. For CPU I set a realistic request and a generous limit or none, because throttling turns GC and JIT bursts into p99 latency spikes. DOTNET_GCHeapHardLimitPercent is for when native memory needs more room. The trade-off is density versus tail latency.

  3. When: Candidate mentions SIGTERM or graceful shutdown Why: Checks they can drain in-flight requests during rollouts
    How to answer

    On SIGTERM, Kubernetes removes the pod from endpoints and signals the container at roughly the same time, but endpoint removal takes a few seconds to reach every node and ingress. So I fail readiness as soon as ApplicationStopping fires and add a preStop sleep of about 5–10 s so routing catches up. I let the host finish in-flight requests within HostOptions.ShutdownTimeout (30 s by default since .NET 8), and keep terminationGracePeriodSeconds longer than the preStop delay plus the shutdown timeout. Background services must honour the stopping token. I verify with a load test during a rolling deploy: zero 5xx.

🛠 Real-world problems: how you handle them

Database password found in a deployment manifest during review
Situation
A new [orders] .NET 10 service was about to go to production on AKS in Australia East, holding [customer names and addresses]. The PR contained a Dockerfile on the SDK image and a Deployment with the Azure SQL password inline.
Signals
GitHub secret scanning raised an alert on the PR. The image scan in CI reported [38] high-severity CVEs. A test rollout produced 502s for about [20 seconds] because there were no readiness probes and a single replica.
Investigation
Checked Git history: the password had been committed [three days] earlier on a feature branch and pushed. Reviewed Azure SQL auditing logs in Log Analytics for logins from unexpected IPs (none found). Ran `trivy image` to confirm the CVEs came from SDK image packages. Reviewed the manifest against the Pod Security Standards `restricted` profile.
Resolution
Immediate: rotated the SQL password, confirmed no unexpected logins, and marked the PR as blocked. Real fix: switched to Workload Identity with an Entra-authenticated SQL user, rewrote the Dockerfile as multi-stage chiseled non-root, added probes, three replicas, a PDB, resources and version tags. The rollout then completed with zero errors.
Prevention
GitHub push protection on the organisation, Azure Policy for AKS denying root containers, `:latest` and missing limits, a CI gate failing on high-severity image CVEs, and a shared Helm chart with secure defaults. Added the review order (secrets, privilege, supply chain, availability) to the team's PR checklist.

How to tell it (STAR)

**S:** A new [orders] service holding [personal data] was a day from production, and the PR had the Azure SQL password inline, ran as root on the SDK image, and had no probes. **T:** As the reviewer I had to stop the risk without derailing the release. **A:** I marked the secret as blocking, got the password rotated within [the hour], and checked SQL audit logs for misuse. I paired with the author to switch to Workload Identity, rewrite the Dockerfile as chiseled non-root, and add probes, replicas and limits. Then I proposed Azure Policy rules and push protection so it couldn't happen again. **R:** We shipped [one day late] with no password at all, CVEs went from [38] to [0], rollouts had zero 502s, and [the next audit] had no container findings.

↩ Usually asked after

More in Containers

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me