Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 57 ยท Real-World Projects

Project: Containerized API with a Database

Package an API in a container, push it to Azure Container Registry, run it on Container Apps with a managed identity, Key Vault and health probes.

This project is the most common shape of a modern back end: an HTTP API, packaged as a container image, talking to a managed database, with no passwords stored anywhere. You will walk through the full path: a Dockerfile, an Azure Container Registry (ACR) to hold the image, Azure Container Apps to run it, a PostgreSQL database reached through a managed identity, a Key Vault for the few secrets that remain, and health probes that let the platform keep the service healthy.

The Azure commands and code are read-only because they need a subscription. The runnable part is a Node.js stand-in of the API and its data layer: a real HTTP server on the sandbox's loopback address with a fake database, a token-based "password", configuration validation and the health endpoints. It lets you test the logic you would deploy. The lesson builds on Azure Container Registry, Azure Container Apps, PostgreSQL, MySQL and Redis on Azure, Managed Identities and Service Principals and Key Vault.

The target architecture

flowchart LR
    C["Client"] -->|"HTTPS"| I["Container Apps ingress"]
    I --> A["shop-api container<br/>(1 to 5 replicas)"]
    A -->|"Entra token as password"| DB[("PostgreSQL<br/>Flexible Server")]
    A -->|"secret reference"| KV["Key Vault"]
    R["Container Registry"] -->|"image pull with identity"| A
    ID["User-assigned<br/>managed identity"] -.->|"AcrPull, Key Vault Secrets User,<br/>database role"| A

One identity is used for three jobs: pulling the image, reading a secret and signing in to the database.

The design rules to keep in mind:

  • No stored passwords. The identity gets short-lived tokens. Registry, database and vault all accept it.
  • Least privilege. The identity receives exactly three permissions, each at the smallest scope.
  • Stateless containers. Any replica can be stopped and replaced at any time; the database holds the state.
  • Probes tell the truth. The platform restarts containers that are stuck and stops sending traffic to those that cannot serve.

Step 1: the API and its Dockerfile

The API is a small Node.js service with GET /products, POST /products, GET /healthz and GET /readyz. A multi-stage Dockerfile keeps the final image small and runs as a non-root user (see Azure Container Registry for image basics). It is read-only here:

DOCKERFILE
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

Add a .dockerignore (excluding node_modules, .git, .env) so local secrets and junk never enter the image. Container Apps does not read a Dockerfile HEALTHCHECK; you configure probes on the app, as shown later.

Step 2: registry, identity and permissions

Create the registry and one user-assigned identity, then give that identity permission to pull images before the app exists, so the first start does not fail on a missing permission:

Terminal
az group create --name rg-shop --location westeurope

az acr create --resource-group rg-shop --name acrshop001 --sku Basic
az acr build --registry acrshop001 --image shop-api:v1 .

az identity create --resource-group rg-shop --name id-shop-api

IDENTITY_ID=$(az identity show -g rg-shop -n id-shop-api --query id -o tsv)
PRINCIPAL_ID=$(az identity show -g rg-shop -n id-shop-api --query principalId -o tsv)
ACR_ID=$(az acr show -n acrshop001 --query id -o tsv)

az role assignment create --assignee-object-id $PRINCIPAL_ID \
  --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID

az acr build sends your folder to ACR Tasks, which builds the image in the cloud, so you do not need Docker installed locally. A user-assigned identity is used (not a system-assigned one) because it exists before the app, can be granted roles first, and survives recreating the app (see the comparison in Managed Identities and Service Principals).

Step 3: the database and passwordless sign-in

Create a PostgreSQL Flexible Server and configure a Microsoft Entra administrator on it (in the portal, in Bicep or with the az postgres flexible-server commands; the exact options evolve, so check the current documentation). With Entra authentication on, a database user can be an identity instead of a password holder. As the Entra administrator, run SQL in the postgres database to create a role for the managed identity, then grant it only what the API needs in the shop database:

SQL
SELECT * FROM pgaadauth_create_principal('id-shop-api', false, false);

GRANT CONNECT ON DATABASE shop TO "id-shop-api";
GRANT USAGE ON SCHEMA public TO "id-shop-api";
GRANT SELECT, INSERT, UPDATE ON products TO "id-shop-api";

The role name is the identity's name. The API never gets DROP or ALTER rights; schema migrations run separately under a different account. The connection code uses the Azure Identity library to fetch a token and passes it as the password. The pg library accepts an async function for the password, so each new connection gets a fresh token (read-only):

JavaScript
import pg from "pg";
import { DefaultAzureCredential } from "@azure/identity";

const credential = new DefaultAzureCredential(); // uses AZURE_CLIENT_ID to pick the user-assigned identity

export const pool = new pg.Pool({
  host: process.env.PGHOST,
  database: process.env.PGDATABASE,
  user: process.env.PGUSER,          // "id-shop-api"
  port: 5432,
  ssl: true,
  max: 10,
  password: async () => {
    const t = await credential.getToken("https://ossrdbms-aad.database.windows.net/.default");
    return t.token;
  },
});

Connections already open keep working after their token expires, because the token is checked at sign-in, but new connections need a valid token, which the function provides. Always use parameterized queries (pool.query("INSERT ... VALUES ($1, $2)", [name, price])) so input can never become SQL.

Step 4: a secret in Key Vault

Even with passwordless access to the database, you may need a third-party API key. Store it in Key Vault and give the identity the Key Vault Secrets User role on that vault. Container Apps can then expose the secret to your container through a reference, without the value ever appearing in the app's configuration:

Terminal
az role assignment create --assignee-object-id $PRINCIPAL_ID \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope $(az keyvault show -n kv-shop-001 --query id -o tsv)

The secret is declared with the vault URL and the identity (shown inside the create command next), and the environment variable points at the secret by name.

Step 5: deploy to Container Apps

Terminal
az containerapp env create --name cae-shop --resource-group rg-shop --location westeurope

az containerapp create \
  --name shop-api --resource-group rg-shop --environment cae-shop \
  --image acrshop001.azurecr.io/shop-api:v1 \
  --registry-server acrshop001.azurecr.io --registry-identity $IDENTITY_ID \
  --user-assigned $IDENTITY_ID \
  --target-port 3000 --ingress external \
  --min-replicas 1 --max-replicas 5 \
  --secrets "payment-key=keyvaultref:https://kv-shop-001.vault.azure.net/secrets/payment-api-key,identityref:$IDENTITY_ID" \
  --env-vars \
    PGHOST=pg-shop-001.postgres.database.azure.com \
    PGDATABASE=shop PGUSER=id-shop-api \
    AZURE_CLIENT_ID=$(az identity show -g rg-shop -n id-shop-api --query clientId -o tsv) \
    PAYMENT_API_KEY=secretref:payment-key

The database firewall must allow the app to connect: the simplest secure option is private networking (a private endpoint or VNet integration, see Private Endpoints, VPN and ExpressRoute); during a lab you can allow Azure services and tighten it later. A minimum of one replica avoids cold starts for an API; use --min-replicas 0 only when slow first requests are acceptable.

Health probes

Container Apps supports three probes, defined on the container in the app's YAML (for example with az containerapp update --yaml app.yaml):

YAML
properties:
  template:
    containers:
      - name: shop-api
        image: acrshop001.azurecr.io/shop-api:v1
        probes:
          - type: Startup
            httpGet: { path: /healthz, port: 3000 }
            periodSeconds: 3
            failureThreshold: 10
          - type: Liveness
            httpGet: { path: /healthz, port: 3000 }
            periodSeconds: 10
            failureThreshold: 3
          - type: Readiness
            httpGet: { path: /readyz, port: 3000 }
            periodSeconds: 5
            failureThreshold: 3

The meaning of each:

  • Startup gives a slow-starting app time before the other probes begin.
  • Liveness asks "is the process alive?" A failure restarts the container. It must not depend on the database, otherwise a database outage would restart every replica in a loop and make things worse.
  • Readiness asks "can this replica serve requests right now?" A failure removes the replica from the load balancer without restarting it. It is the right place to check the database.
flowchart TD
    P["Probe request"] --> L{"Liveness /healthz<br/>fails 3 times?"}
    L -->|"yes"| RS["Restart container"]
    L -->|"no"| RD{"Readiness /readyz<br/>fails 3 times?"}
    RD -->|"yes"| OUT["Take out of rotation<br/>(no restart)"]
    RD -->|"no"| IN["Receives traffic"]

Liveness decides restarts; readiness decides traffic.

The API and data layer: a runnable stand-in

The program below starts a real HTTP server on loopback and calls it with fetch. The "database" is an in-memory object that behaves like the Entra-protected server in one respect: a connection is accepted only if the token used as password is valid for the right user. A small "platform" loop probes /healthz and /readyz and reports whether the replica would be in rotation. Everything about Azure itself (the real token service, the real network) is replaced by simple stand-ins.

Node.js API, data layer and health probes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output with the probe table in mind. During the outage, liveness stays 200, so the replica is not restarted, while readiness flips to 503 and takes it out of rotation. When the database returns, the pool opens a new connection, which asks for a fresh token. Inputs that fail validation are rejected before they reach the database.

Failing fast on bad configuration

Containers get their settings from environment variables, and a missing one is the most common reason a new deployment does not work. A good service validates its configuration at startup and exits with a clear message, so the platform shows a failed revision instead of a half-working one. The second stand-in validates settings the same way and masks secrets in its log.

Node.js Validate and log configuration safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Printing a secret's first two characters is already generous; many teams log only that it is set. Never log the whole value, and never print the token.

Operating the service

  • Revisions and rollbacks. Each deployment creates a revision; you can split traffic or roll back (see Deployment Slots, Blue-Green and Canary). Tag images with a version or commit hash, not only latest.
  • Scaling. Add an HTTP concurrency rule so replicas scale with requests (--scale-rule-http-concurrency), and keep max-replicas below what the database can handle: connection limits on small database tiers are low, so cap the pool size per replica.
  • Logs and metrics. The environment sends console logs to Log Analytics; query them with KQL (see Azure Monitor, Log Analytics and Application Insights).
  • Migrations. Run schema changes as a separate job with its own elevated identity, never from every replica at startup.
  • Cost. A Burstable database tier and a Basic registry keep a lab inexpensive; delete the resource group when you finish (see Pricing, Cost Management and Budgets).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why should the liveness probe NOT check the database?

    Liveness restarts the container. Restarting does not repair a database, so dependency checks belong in the readiness probe, which only removes the replica from rotation.
  2. 2. How does the API sign in to PostgreSQL without a stored password?

    With Entra authentication, a database role maps to the identity. The token has a short lifetime and is requested whenever a new connection is opened.
  3. 3. Why is the AcrPull role granted to the identity before the container app is created?

    The platform pulls the image with the identity. If the permission is missing at first start, the pull fails and the revision does not become healthy.
  4. 4. What does a failing readiness probe do?

    Readiness controls whether a replica receives traffic. The container keeps running so it can recover, for example when the database comes back.
  5. 5. Which is the best way to build the image in this project?

    Multi-stage builds keep tools out of the runtime image, .dockerignore keeps secrets and junk out, and a non-root user limits the damage of a compromise.

Summary

  • Package the API with a multi-stage Dockerfile, build it in ACR with az acr build, and run it on Container Apps.
  • Use one user-assigned managed identity for three jobs: AcrPull on the registry, Key Vault Secrets User on the vault and a least-privilege role in the database.
  • Pass an Entra token as the PostgreSQL password through an async password function; use parameterized queries.
  • Reference Key Vault secrets from the app instead of copying values; validate configuration at startup and never log secrets.
  • Liveness decides restarts (no dependencies), readiness decides traffic (check the database), startup protects slow boots.
  • Deploy small, tag images, cap connection pools below the database limits, and clean up lab resources.

Next: Project: Serverless Data Pipeline and Report.