Dinesh/ Blog
cloud engineering

Deploying Web Applications in Azure with Docker

Trace Docker image, process and network boundaries; develop a digest-pinned Azure deployment plan with explicit version, identity, permission and service-execution limits.

16 min read
Checking device speech…

In this article

  • A new tag is pushed after staging tests and production pulls the same tag name. Was the tested artifact promoted?
  • Explain the version and execution boundaries before applying the examples
Background & source details

Level: intermediate

Bring with you

Sources checked: . A source check does not change the publication or update date.

Editorial review: · What review means

In this article · 23 sections

Review and execution boundary

Docker multi-stage builds, Compose v2 and Azure hosting concepts; no build, registry push or deployment executed.

Originally reviewed on 7 October; the commands and consequential platform contracts below were rechecked against official documentation on 9 October 2026. Source review is not deployment/security certification. Setup commands and exercises were not executed; no cloud resources or packages were created. Private recovery assets are not lesson prerequisites.

Deploying Web Applications in Azure with Docker

What you'll leave with: a correct mental model of containers (not just the commands), a secure production-oriented Dockerfile pattern, a local dev-loop reference with Docker Compose, and two deployment paths on Azure — App Service (classic) and Container Apps (modern, scale-to-zero) — with the exact CLI commands, gotchas, and cost/architecture tradeoffs.


1. A correct mental model: containers are not VMs

A very common misunderstanding is that containers are "lightweight VMs". They are not. A VM virtualises hardware (its own kernel, bootloader, emulated devices). A container virtualises the OS view for a group of processes — they all share the host kernel.

For ordinary Linux containers, these mechanisms supply isolation, resource accounting and layered storage:

FeatureWhat it gives youExample
NamespacesIsolated view of resourcespid (its own PID 1), net (its own NIC), mnt (its own filesystem root), uts (its own hostname), ipc, user
cgroups v2Resource limits & accounting--memory=512m, --cpus=1.5
Union FS (overlayfs)Layered, copy-on-write imagesFilesystem-changing build steps produce image layers; a container gets a writable layer on top

Consequences that matter:

  • Kernel features the host lacks, you can't get inside the container. (e.g. newer io_uring features, newer eBPF, modern seccomp profiles.)
  • You cannot run Linux containers on Windows/macOS natively — Docker Desktop runs a tiny Linux VM for you; that's why file-sync can be slow.
  • Image size is dominated by layers, so ordering COPY and RUN correctly is a real perf/cost lever.

The runtime stack on Linux: docker CLI → dockerd → containerd → runc. runc is the OCI reference that actually calls clone(), sets up the namespaces and cgroups, pivot_roots the filesystem, and execves your entrypoint. Knowing this lets you debug "why is my container dying with exit 137?" (possible cause: OOM kill; exit 137 alone only indicates SIGKILL-style termination).


2. A production-oriented Dockerfile pattern

Common packaging problems:

  1. Runs as root.
  2. Uses COPY . /app before pip install, so every code change busts the pip cache.
  3. Uses a single stage — your build tools (gcc, dev headers, pip wheel cache) ship to production.
  4. No HEALTHCHECK, no EXPOSE discipline, no explicit WORKDIR.

Here is a pattern that fixes all of this for a Python/Flask app (the same shape works for Node/Go/Java):

# syntax=docker/dockerfile:1.7
# ---------- Stage 1: builder ----------
FROM python:3.12-slim AS builder
 
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_NO_CACHE_DIR=1
 
WORKDIR /build
 
# Install only build-time OS deps, then drop them
RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential gcc \
    && rm -rf /var/lib/apt/lists/*
 
# Copy ONLY dependency manifests first so this layer is cached on code-only changes
COPY requirements.txt .
RUN pip install --prefix=/install -r requirements.txt
 
# ---------- Stage 2: runtime ----------
FROM python:3.12-slim AS runtime
 
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PORT=8000
 
# Non-root user; writable app directory for local Compose watch
WORKDIR /app
RUN useradd --create-home --shell /usr/sbin/nologin --uid 10001 app \
    && chown app:app /app
 
# Copy installed packages and scripts (including gunicorn), not build tools
COPY --from=builder /install /usr/local
 
# App code last = best cache behaviour
COPY --chown=app:app src/ ./
 
USER app
EXPOSE 8000
 
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
  CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status==200 else 1)"
 
# Use gunicorn, not `python app.py`, in production
CMD ["gunicorn", "-b", "0.0.0.0:8000", "-w", "2", "--threads", "4", "app:app"]

Read the stage boundary as a packaging decision: the builder installs dependencies under a separate prefix, and the runtime receives that installation without the compiler toolchain. Copying dependency manifests before application code lets a code-only change reuse the expensive install layer. This assumes src/app.py exports the Flask object app, serves /healthz, and root-level requirements.txt declares Flask, Gunicorn and the app dependencies. Supply any native runtime libraries separately; the prefix copy does not include OS libraries. Pin tested base digests and dependency versions for release. EXPOSE documents a port; it does not publish it.

Pair it with a strict .dockerignore:

.git
.venv
__pycache__
*.pyc
.env
.env.*
tests/
docs/
node_modules/

Measure the actual build: record the base digest, architecture, dependency lock, image size and cold/cached build times. Reusing the dependency layer can avoid reinstalling packages; neither a size nor a speedup is guaranteed. Non-root reduces privilege, not a measured percentage of exploit paths.


3. Local dev loop with Docker Compose

Real apps have more than one process. A docker-compose.yml lets you bring up the whole system with one command and a consistent network. In this example, follow the web service to the database and cache by service name; the database volume has a different lifetime from any one container. The sample credentials and published port are local-development choices, not production access controls.

services:
  web:
    build: .
    ports: ["127.0.0.1:8000:8000"]
    environment:
      DATABASE_URL: postgresql://app:app@db:5432/app
      REDIS_URL: redis://cache:6379/0
    depends_on:
      db: { condition: service_healthy }
      cache: { condition: service_healthy }
    develop:
      watch:
        - action: sync+restart
          path: ./src
          target: /app
        - action: rebuild
          path: ./requirements.txt
 
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: app
      POSTGRES_DB: app
    volumes: ["pgdata:/var/lib/postgresql/data"]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      retries: 5
 
  cache:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      retries: 5
 
volumes:
  pgdata:

Key points most tutorials get wrong:

  • Service name = DNS name. web reaches Postgres at host db, not localhost. Compose puts every service on a user-defined bridge network where Docker's embedded DNS resolves service names.
  • depends_on alone does not wait for readiness. Use condition: service_healthy with a healthcheck.
  • Database storage: the named volume survives container replacement, not deliberate volume deletion. Back up and test restores; host/filesystem behavior matters, and bind mounts are not inherently corrupt.
  • sync+restart requires Compose 2.23.0+ and a writable target. Here source changes restart Gunicorn; dependency changes rebuild. Plain sync needs an application reloader and would leave these workers serving old code. Health-gated startup is not runtime recovery: the application still needs bounded reconnect/retry behavior.

Run: docker compose up --watch.


4. Security hardening checklist

Production containers need more than "it works":

  • ☑ Non-root user (USER directive in Dockerfile; runAsNonRoot: true in Kubernetes).
  • ☑ Minimal compatible base — slim/distroless alternatives can reduce shipped packages. Check native libraries and wheel availability; musl-based Alpine is not a drop-in substitute for glibc wheels.
  • ☑ Pin versions — a supported tested base by digest, not an unreviewed moving tag.
  • ☑ No secrets in layers. Copied files can remain recoverable from image layers even after later deletion; docker history shows build history, not arbitrary file contents. Use BuildKit secret mounts for build credentials and restricted runtime secret references; avoid logging resolved values.
  • ☑ Scan on every build — docker scout cves <image>, trivy image <image>, or grype <image>.
  • ☑ Read-only root filesystem at runtime — --read-only + a tmpfs mount for /tmp if needed.
  • ☑ Drop capabilities — --cap-drop=ALL --cap-add=NET_BIND_SERVICE (if you need < 1024 ports).
  • ☑ Resource limits — always set --memory and --cpus (or their Compose/K8s equivalents). Without them, one runaway container can OOM the whole host.

An example vulnerability-policy gate (define GIT_SHA first; scanner results are not proof of exploitability or complete security):

trivy image --severity HIGH,CRITICAL --exit-code 1 myapp:${GIT_SHA}

5. Pushing the image: Azure Container Registry (ACR)

ACR supports managed-identity pulls; private networking is a separate tier/configuration decision. The Basic example below does not create a private endpoint. Authenticate to your intended subscription first, choose a globally unique registry name, and confirm build/push and role-assignment permissions. These are unexecuted, billable reference commands, not setup performed by this review.

az group create -n rg-blog -l eastus
ACR=myblogacr  # replace with your available registry name
az acr create -n "$ACR" -g rg-blog --sku Basic
LOGIN_SERVER=$(az acr show -n "$ACR" --query loginServer -o tsv)
TAG=$(git rev-parse HEAD)
az acr login -n "$ACR"
docker build -t "$LOGIN_SERVER/blog:$TAG" .
docker push "$LOGIN_SERVER/blog:$TAG"
# Alternative to the two local build/push commands, not an additional promotion:
# az acr build -r "$ACR" -t "blog:$TAG" .
DIGEST=$(az acr repository show -n "$ACR" --image "blog:$TAG" --query digest -o tsv)
IMAGE="$LOGIN_SERVER/blog@$DIGEST"
 
# Pre-create the identity so its grants exist before the first private pull.
az identity create -g rg-blog -n blog-pull
PULL_ID=$(az identity show -g rg-blog -n blog-pull --query id -o tsv)
PULL_PRINCIPAL=$(az identity show -g rg-blog -n blog-pull --query principalId -o tsv)
ACR_ID=$(az acr show -n "$ACR" --query id -o tsv)
az role assignment create --assignee-object-id "$PULL_PRINCIPAL" \
  --assignee-principal-type ServicePrincipal --role AcrPull --scope "$ACR_ID"

This AcrPull grant assumes RBAC Registry Permissions mode. In ABAC-enabled repository-permissions mode, use the documented Container Registry Repository Reader grant/conditions instead. Managed-identity pulls also require registry acceptance of ARM audience tokens and a reachable registry/DNS path. Allow role propagation and verify access before deploying; never solve a denied pull by enabling admin credentials.

For the database examples, provision your database and an RBAC-enabled Key Vault separately. Save its connection string through a protected secret-entry flow, then set SECRET_URI to the secret's URI (not its value) and KV_ID to that vault's resource ID. Grant the identity read access:

az role assignment create --assignee-object-id "$PULL_PRINCIPAL" \
  --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" \
  --scope "${KV_ID:?set the existing vault resource ID}"
: "${SECRET_URI:?set the existing database secret URI}"

Use a dedicated vault/identity per environment and confirm vault/database network access. Neither grant provisions a database, firewall rule or secret. Test and scan $IMAGE; promote that recorded digest, not a tag re-resolved after tests. Remote az acr build avoids a local Docker daemon but is not inherently faster.


6. Deployment path A — Azure App Service (classic PaaS)

A suitable option for a steady web workload. This reference uses the classic, non-sidecar Linux custom-container configuration. B1 is a starting cost choice, not a production sizing recommendation; it does not support staging slots.

az appservice plan create -g rg-blog -n plan-blog --is-linux --sku B1
az webapp create -g rg-blog -p plan-blog -n myblog-app \
  --container-image-name "$IMAGE" --assign-identity "$PULL_ID" \
  --acr-use-identity --acr-identity "$PULL_ID"
az webapp update -g rg-blog -n myblog-app \
  --set keyVaultReferenceIdentity="$PULL_ID"
az webapp config appsettings set -g rg-blog -n myblog-app --settings \
  WEBSITES_PORT=8000 WEBSITES_ENABLE_APP_SERVICE_STORAGE=false \
  "DATABASE_URL=@Microsoft.KeyVault(SecretUri=$SECRET_URI)"
az webapp config set -g rg-blog -n myblog-app --always-on true

Gotchas that catch people:

  • Port contract: classic custom containers use WEBSITES_PORT for a nondefault HTTP port. Sidecar-enabled apps use site-container target-port configuration; WEBSITES_PORT does not apply there. Match Gunicorn’s actual listener, not merely EXPOSE.
  • Always On: enable it on a supporting tier such as this B1 plan. Without it, idle unloading can cause warm-up latency; no fixed 20-second cold-start duration is promised.
  • Deployment slots require Standard, Premium or Isolated, not B1; counts vary by tier. Zero downtime must be verified for the workload: deploy to staging, test, then az webapp deployment slot swap — DNS doesn't change, and the slot warms up before swap.
  • Log streaming: az webapp log tail -g rg-blog -n myblog-app.

7. Deployment path B — Azure Container Apps (modern, serverless)

Useful for bursty/event-driven services with suitable scaling rules. Use a current compatible Azure CLI/Container Apps extension. The pre-created identity from §5 avoids the bootstrap problem: a system identity cannot resolve a Key Vault secret during the initial create operation. Verify the resulting revision and probe health before sending production traffic.

az provider register -n Microsoft.App --wait
az provider register -n Microsoft.OperationalInsights --wait
 
az containerapp env create \
  -g rg-blog -n cae-blog -l eastus
 
az containerapp create \
  -g rg-blog -n ca-blog \
  --environment cae-blog \
  --image "$IMAGE" \
  --registry-server "$LOGIN_SERVER" \
  --user-assigned "$PULL_ID" --registry-identity "$PULL_ID" \
  --target-port 8000 --ingress external \
  --min-replicas 0 --max-replicas 10 \
  --cpu 0.5 --memory 1Gi \
  --secrets "db-url=keyvaultref:$SECRET_URI,identityref:$PULL_ID" \
  --env-vars "DATABASE_URL=secretref:db-url"

For latency-sensitive traffic, compare a warm replica with scale-to-zero using your image and region. The table describes hosting contracts, not measured application performance.

Why you'd pick this over App Service:

DimensionApp ServiceContainer Apps
Scale to zeroNot this dedicated B1 planPossible with suitable rules/minimum replicas
BillingAllocated plan capacityConsumption resource/request usage; zero replicas has no resource-consumption charge, but other services/fees can remain; Dedicated differs
Queue/custom scalingPlan/application dependentKEDA-based rules
Staging/trafficSlots on eligible tiers, not fixed at twoRevisions; configure multiple-revision mode for splits
Dapr integrationNot the managed ACA Dapr featureManaged Dapr integration
NetworkingOutbound VNet integration differs from inbound private endpointsEnvironment/ingress/network configuration matters
Cold startPossible after unload/restartMeasure pull, startup and readiness; no universal 2–5 s

Rule of thumb: one user-facing monolith with steady traffic → App Service. Many small services or bursty/event-driven → Container Apps.


8. Observability you should turn on day one

  • Logs: configure App Service diagnostic settings to send console logs to Log Analytics; configure the ACA environment’s log destination separately. These use different tables.
  • Tracing: configure an Application Insights/OpenTelemetry exporter, resource identity and instrumentation. Instrumentation alone does not choose or configure an exporter.
  • Container health probes — App Service Health Check uses a configured platform health-check path; do not assume Dockerfile HEALTHCHECK is consumed; ACA has explicit liveness / readiness / startup probes you should configure.
  • Alerts: choose thresholds and windows from your SLO/baseline; for example investigate HTTP 5xx above 1% over five minutes with sufficient requests. These are illustrative, not universal safe limits.

This App Service query counts console messages containing error terms, not HTTP error rate. It needs the AppServiceConsoleLogs table; ACA logs have a different schema:

AppServiceConsoleLogs
| where TimeGenerated > ago(15m)
| where ResultDescription has_any ("ERROR","Exception","Traceback")
| summarize count() by bin(TimeGenerated, 1m), _ResourceId
| render timechart

9. Common mistakes to avoid (corrections to the original post)

Earlier recommendations needing correction:

  1. ❌ "Use python:3.8-slim" — 3.8 reached end-of-life in Oct 2024. Use a supported Python (3.11/3.12 at the time of writing).
  2. ❌ Flask development server in production — use a production WSGI server such as Gunicorn for this Flask app. ASGI frameworks require a compatible ASGI server/worker; gthread is not an ASGI worker.
  3. Registry choice — Docker Hub can work; authentication, quotas, network access and cost differ. ACR is used here for Microsoft Entra managed-identity pulls, not because every other registry is invalid.
  4. ❌ "Day 1 / Day 2" fake learning plan — replace with concrete milestones tied to the repo you actually ship.
  5. ❌ No .dockerignore — without it, COPY . . leaks your .git, .env, and __pycache__ into the image.

10. TODO — self-sufficient action list

These are optional application-specific verification tasks, not completed work. Consult the linked versioned/current platform docs before incurring cost; provision dependencies and permissions first.

Foundations

  • Install Docker Desktop (or Colima on macOS for a lighter alternative), run docker run hello-world, then explain in your own words what namespaces/cgroups did (§1).
  • Use docker inspect for .State.Pid; on the Linux daemon host inspect /proc/<pid>/ns/ and /proc/<pid>/cgroup. Docker Desktop’s Linux host is a VM, not the macOS/Windows host; storage-driver fields vary.

Build a real image

  • Port the two-stage Dockerfile in §2 to your actual app (Python or otherwise). Commit a .dockerignore.
  • Record image sizes before and after multi-stage. Set a workload-specific size budget rather than treating language-based limits as guarantees.
  • Add a HEALTHCHECK that hits a real /healthz endpoint and returns JSON including git SHA + uptime.

Local dev loop

  • Write a docker-compose.yml for app + Postgres + Redis with health-gated startup (§3). Verify source edits sync and restart the service without an image rebuild; verify dependency edits rebuild.

Security pass

  • Run trivy image against your image; triage HIGH/CRITICAL findings under a documented release policy, updating dependencies and recording any time-bounded exceptions.
  • Confirm with docker run --rm myapp whoami that the process is NOT root.
  • Add --read-only + tmpfs /tmp to your docker run command and verify the app still boots.

Ship to ACR

  • Create an ACR, push a tagged image built remotely with az acr build (no local Docker needed).
  • Record the commit tag and resolved image digest; promote the tested digest, not the tag name alone.

Deploy — pick ONE path to start, then do the other

  • App Service path: provision Linux plan + webapp, wire mode-appropriate managed-identity pull permissions, set the classic container port, deploy, hit the public URL.
  • On an eligible tier (not B1), add staging, deploy/test v2, then swap; measure errors and in-flight requests rather than assume zero downtime.
  • Container Apps path: provision an environment, deploy with --min-replicas 0, confirm scale-to-zero after idle, confirm cold-start behaviour.
  • Enable multiple-revision mode, create a second healthy revision, test a 50/50 split, then promote to 100% with rollback ready.

Observability

  • Enable App Insights (SDK in code + connection string in env).
  • Write 3 KQL queries in Log Analytics: error rate by endpoint, p95 latency, slow DB calls.
  • Wire one alert: HTTP 5xx > 1% over 5 min → email/Teams.

Stretch (only after the above)

  • Codify infrastructure in Bicep or Terraform; using azd up additionally requires a compatible Azure Developer CLI project/service configuration.
  • Add GitHub Actions: build → scan → push to ACR → az containerapp update --image … on merge to main.
  • Compare cost for your actual traffic pattern: App Service B1 24×7 vs Container Apps scale-to-zero. Document the break-even point.

Corrected contracts and failure analysis

Promote the tested image digest and review deployment configuration: immutable image identity alone does not freeze runtime settings.

App Service Health Check is configured with a path in the platform; do not assume it consumes the image's Docker HEALTHCHECK. Container Apps has revision/probe/traffic concepts of its own. A revision is immutable, but referenced secrets, dependencies and traffic routing are separate operational state. Creating a private registry does not make it private networking by default, and registry authentication requires identity grants before an image pull can succeed.

Record image digest, region, runtime, cold/warm samples and request counts when comparing hosting costs or latency.

Boundary exercise with solution

A new tag is pushed after staging tests and production pulls the same tag name. Was the tested artifact promoted?

Solution and reasoning

Not necessarily. Resolve and record the image digest; deploy that digest or enforce immutable tag policy. Then verify the running revision references it. A green pipeline plus the same human-readable tag is insufficient artifact provenance.

Source-backed review notes

Historical 7 October snapshots support multi-stage packaging, App Service Health Check, revision immutability, and outbound VNet versus inbound private access. They are not deployment receipts.

Rechecked 9 October 2026: Compose develop actions/version gates, watch permissions, build secrets, webapp CLI, classic container configuration, sidecars, slot tiers, Key Vault references, ACA image-pull identity, ACA secret bootstrap, billing, ACR permission modes, and console-log schema. Cloud, Docker build/run, registry push, secret resolution and KQL service execution remain unperformed.

Pause / Recall / Apply

Can you explain it without the page?

Close the example. Reconstruct the core idea, then change one assumption. Mark complete when you’re ready; you can always undo it.

Stored in this browser only. No account, no sync. Clearing browser data removes your record.