Architecture

Container-Native APIs: Building for Modern Cloud Infrastructure

How to build an API that runs well in containers: a small image, clean shutdown, health endpoints, and a Kubernetes deployment with probes and autoscaling.

By the APIStack team··Updated ·9 min read

Terminal windows showing a file download and a process monitor

An API is container-native when it is written with the container runtime's expectations in mind, not just packaged into an image afterwards. The orchestrator will start, stop, move and duplicate the process at any time, and the service has to behave correctly when it does.

This article walks through what that requires for a Node.js HTTP API deployed on Kubernetes: how the process should behave, how to build the image, how to expose health, and how to configure the deployment, autoscaling and security settings. The same principles apply to other languages and orchestrators.

Design the process for the orchestrator

A container platform treats instances as replaceable. Three properties make an API safe to replace.

The first is that it keeps no state of its own. Sessions, uploads and caches that must survive a restart live in a database, object store or cache service. Any replica can then serve any request, and losing one loses nothing.

The second is that configuration comes from the environment. The same image runs in every environment; only environment variables and mounted secrets differ. The process writes logs to standard output as structured lines and leaves collection to the platform. These ideas come from the twelve-factor app guidelines, which remain a good checklist.

The third is that it shuts down cleanly. When Kubernetes removes a pod it sends SIGTERM, waits for the termination grace period (30 seconds by default) and then sends SIGKILL. A process that ignores SIGTERM drops whatever requests it was handling when it is killed. The server below stops reporting ready, finishes in-flight requests, then exits.

JavaScript
import express from 'express'

const app = express()
let shuttingDown = false

app.get('/health', (req, res) => res.sendStatus(200))
app.get('/ready', (req, res) => res.sendStatus(shuttingDown ? 503 : 200))

const server = app.listen(process.env.PORT || 3000)

process.on('SIGTERM', () => {
  shuttingDown = true
  server.close(() => process.exit(0))
  setTimeout(() => process.exit(1), 20_000).unref()
})

The timer is a backstop: if a connection never finishes, the process exits by itself before the platform kills it.

Build a small, reproducible image

A good image contains the runtime, the production dependencies and the application code, and nothing else. A multi-stage build installs dependencies in one stage and copies only the result into the final one, so build caches and tooling stay out of what ships.

Text
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

FROM node:24-alpine
ENV NODE_ENV=production PORT=3000
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --chown=node:node . .
USER 1000
EXPOSE 3000
CMD ["node", "server.js"]

Several details in this file matter. Copying the two package files before the source means the dependency layer is rebuilt only when dependencies change, which keeps most builds fast. npm ci --omit=dev installs exactly what the lockfile specifies without development dependencies. USER 1000 runs the process as the unprivileged node user that the official image provides; the numeric form lets Kubernetes verify that the container is not root. The base image tag names a supported Node.js release line; for fully reproducible builds, pin it by digest as well.

Add a .dockerignore file that excludes at least node_modules, .git and local environment files. Without it, COPY . . overwrites the clean dependencies with whatever is in the working directory and can copy secrets into the image.

A Dockerfile HEALTHCHECK instruction is not needed for Kubernetes, which ignores it and uses its own probes. It is still useful if the same image runs under plain Docker or Compose.

In the delivery pipeline, build the image once per commit, tag it with the commit SHA, scan it for known vulnerabilities with a tool such as Trivy, and promote that same image through staging to production. Rebuilding per environment means the artifact you tested is not the one you deploy.

Expose liveness and readiness separately

Kubernetes asks a container three different questions through probes, and it helps to keep them apart.

A liveness probe asks whether the process is stuck. If it fails, the container is restarted. It should check only the process itself, as /health does above. A liveness check that queries the database turns a database outage into a restart loop across every replica, which makes recovery slower.

A readiness probe asks whether this replica should receive traffic. If it fails, the pod is taken out of the service's endpoints but left running. This is the place to report that the service is still warming up, is shutting down, or cannot reach something it needs for every request.

A startup probe covers slow starts. Until it succeeds, the other two probes are not run, so a service that needs time to load data is not killed by its liveness probe before it is up.

Deploy with requests, probes and rolling updates

The manifest below puts those pieces together. It runs three replicas, replaces them one at a time without dropping below three, and gives each container time to drain.

YAML
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  selector:
    matchLabels:
      app: api
  template:
    metadata:
      labels:
        app: api
    spec:
      terminationGracePeriodSeconds: 30
      containers:
        - name: api
          image: registry.example.com/api:1.4.2
          ports:
            - containerPort: 3000
          resources:
            requests:
              cpu: 250m
              memory: 256Mi
            limits:
              memory: 256Mi
          startupProbe:
            httpGet: { path: /health, port: 3000 }
            periodSeconds: 2
            failureThreshold: 30
          livenessProbe:
            httpGet: { path: /health, port: 3000 }
            periodSeconds: 10
          readinessProbe:
            httpGet: { path: /ready, port: 3000 }
            periodSeconds: 5
          lifecycle:
            preStop:
              exec:
                command: ["sleep", "5"]

Resource requests tell the scheduler how much capacity to reserve, and they are what the autoscaler measures utilization against, so set them from observed usage. Setting the memory limit equal to the request means the container is never scheduled onto memory it cannot keep. The manifest sets no CPU limit: a CPU limit throttles the container even when the node has idle cores, which shows up as latency spikes. Whether to set one is a judgment call that depends on how much you need to protect neighbours on shared nodes.

The preStop sleep closes a small race. Removing the pod from load balancing and sending SIGTERM happen in parallel, so for a moment new requests can still arrive at a pod that has begun shutting down. Sleeping a few seconds before the signal lets the endpoint change propagate first. The sleep counts against the grace period, which is why the application's own backstop timer is shorter than 30 seconds.

A rolling update is the default strategy and suits most APIs, provided that two adjacent versions can run side by side: database migrations and response formats must stay compatible with the previous release. Blue-green and canary releases, which shift traffic between two full versions, are not built into the Deployment resource. They need a traffic-splitting layer such as the Gateway API or a controller such as Argo Rollouts.

Scale on measured load

A HorizontalPodAutoscaler adjusts the replica count to hold a metric near a target. The stable API version is autoscaling/v2; the earlier v2beta1 and v2beta2 versions have been removed from Kubernetes. This example keeps average CPU use at about 70 percent of the requested amount.

YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api
  minReplicas: 3
  maxReplicas: 10
  metrics:
    - type: Resource
      resource:
        name: cpu
        target:
          type: Utilization
          averageUtilization: 70

Once the autoscaler owns the replica count, remove replicas from the Deployment manifest; otherwise every apply resets the count to the fixed value. CPU is a reasonable signal for request-bound APIs. For services that mostly wait on I/O, a custom metric such as requests per second or queue depth tracks load better.

Scaling adds replicas only after load has risen, and new pods take time to start, so keep the minimum high enough to absorb a normal burst. A PodDisruptionBudget (policy/v1) with minAvailable set stops node maintenance from evicting too many replicas at once.

Restrict what the container can do

The image already runs as a non-root user. The pod specification can enforce that and remove other privileges the API does not need. This fragment goes under the api container in the Deployment above.

YAML
securityContext:
  runAsNonRoot: true
  allowPrivilegeEscalation: false
  readOnlyRootFilesystem: true
  capabilities:
    drop: ["ALL"]
  seccompProfile:
    type: RuntimeDefault

A read-only root filesystem prevents an attacker who gains code execution from modifying the application or dropping tools into the container. If the service needs scratch space, mount an emptyDir volume at that path. These settings match the restricted profile of the Pod Security Standards, which can be enforced per namespace.

Keep secrets out of the image and out of the manifest. Reference them from a Secret object or an external secret manager and inject them as environment variables or mounted files at runtime.

Summary

  • Write the service to be replaceable: stateless, configured from the environment, logging to standard output and shutting down cleanly on SIGTERM.
  • Build a small multi-stage image that runs as a non-root user, and promote one scanned image per commit through every environment.
  • Keep liveness checks limited to the process itself, use readiness to control traffic, and add a startup probe for slow starts.
  • Set resource requests from observed usage and let an autoscaling/v2 HorizontalPodAutoscaler own the replica count.
  • Drop privileges in the pod's security context and supply secrets at runtime.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading