Chapter 19 of 27 · Part 9: Deployment and scaling

Deployment patterns and Kubernetes

The deployment patterns from packages to containers, running on Kubernetes, and releasing safely.

key idea / coordinatorservice / good pathin progress / watch outproblem / failureneutral

How deployment changed

With hundreds of services, only automated, lightweight deployment is workable.

From pets to cattle1990sphysical servers2006virtual machines2013Docker containers2014serverlessServers went from hand-cared pets to throwaway, automated infrastructure.
What production must provideProduction environmentManagement APIdeploy, updateRuntime mgmtkeep N runningMonitoringlogs, metricsRoutingusers to services

Principles of deployment

Whatever platform you pick, five principles hold. From Building Microservices, ch. 8.

Isolated executionMany services per hostNoisy neighbors steal CPUHard to monitor each oneGilt hit this early onIsolated instancesOwn CPU, memory, filesystemFailures stay localVM or container eachOne host is simpler for the ops team, but the side effects add up.
PrincipleWhy it matters
AutomationMore services mean more moving parts. Gilt went from about 10 services after a year to over 450 in 2014, driven by tooling that let developers self-serve.
Infrastructure as codeMachine-readable config in source control gives an audit trail and lets you recreate an environment as of a date. One client spent months rebuilding an old system for a court case.
Zero-downtime deploymentConsumers should not notice a release, so teams can ship in working hours. Async middleware makes it easy; otherwise use rolling upgrades or blue-green. Kubernetes only for this is overkill.
Desired state managementDesired state3 instancesReality changesone instance diesPlatform noticesactual differsSelf-healstarts a new oneYou state the goal. The platform works out where and how to keep it true.
GitOpsGit repositorydesired state as codeGitOps toolFlux watches the repoClusterchanges are appliedA tool such as Flux does not give you these ideas by itself: you still have to adopt them.

Four deployment patterns

Each step up hides more of the machine from you.

PatternBenefitsDrawbacks
Language package (JAR/WAR)Fast deploy, shares resourcesNo isolation, no resource limits, ops must know the runtime
Virtual machine (AMI)Stack encapsulated, isolated, mature cloudHeavy, minutes to build and boot, patch the OS
Container (Docker)Encapsulated, isolated, limited, starts fastYou patch images and run the platform
Serverless (Lambda)No servers, elastic, pay per requestCold starts, limited to short functions
VM versus containerVirtual machineWhole OS per instanceStrong isolationSlow to build and bootContainerShares the host kernelOwn IP, filesystem, CPU/RAM limitsBuilds in seconds, starts fast
Docker in four stepsDockerfilebase + JAR + CMDdocker buildmakes imagedocker pushto a registrydocker runa containerPush sends only the layers that changed. Compose runs several containers on one machine.

Kubernetes

A Docker orchestration framework that turns many machines into one pool.

Kubernetes architectureA master runs the API server, etcd, scheduler and controller manager. Each node runs kubelet, kube-proxy and pods.MasterAPI serverkubectl talks hereetcdcluster stateSchedulerpicks a nodeController mgrdesired = actualNode (one of many)Kubeletruns podsKube-proxynetworkingPodcontainersPodcontainersPodcontainersPods share one IP per pod andare created and replaced by the master.
You declare the desired state; Kubernetes keeps making it true.
The objects you write in YAMLKubernetes objectsPodcontainers + IPDeploymentN replicasServicestable DNS nameConfigMapsettingsSecretpasswords
Service types (how the API gateway is exposed)ClusterIPDefaultinside the cluster onlyNodePortPort on every node30000–32767LoadBalancerCloud load balancereasiest from outside

From Docker to Kubernetes in practice

Bootstrapping Microservices walks the whole road with one example app. Package it, publish it, then run it on a cluster. From Bootstrapping Microservices, ch. 3, 4 and 6.

The road to productionDockerfilebuilds the imageRegistryprivate, versionedDeploymentpods, replicasServicestable addressA deploy.yaml file describes pod, deployment and service. kubectl apply sends it.
ToolUsed for
Docker ComposeRun the whole app on your computer while developing and testing. It simulates the cluster without the weight.
Local Kubernetes (Docker Desktop)Learn and rehearse a deployment: switch it on, apply, test, delete.
Managed Kubernetes (for example Azure)Production. A few clicks, or Terraform code, give you a cluster with a container registry attached.

A bare pod is not enough for production. A deployment keeps the chosen number of pods running, and a service gives them one stable address. Each pod here hosts one container, though a pod can host several (the sidecar pattern).

Infrastructure as code with Terraform

Clicking through a cloud portal does not repeat. Terraform is a language and tool for describing cloud infrastructure, and it is executable documentation that cannot go out of date. From Bootstrapping Microservices, ch. 7.

The Terraform cycleinitget the providersapplycreate or updateStatetracks resourcesdestroytear it all downProviders plug in each cloud (Azure, AWS), so one skill works across vendors.

Grow the code in small steps: a resource group first, then the container registry, then the Kubernetes cluster, sharing settings through variables. Outputs expose values such as the registry address, but avoid outputting passwords, since they land in plain text in the state file.

Alternatives: Newman notes Pulumi (normal programming languages) and the AWS-only CloudFormation and CDK. He prefers a cross-platform tool like Terraform, kept in version control next to the service.

Kubernetes: limits and when to use it

An orchestrator decides where containers run and keeps the desired state true, so you do not script it by hand. Kubernetes won this space, but it has limits. From Building Microservices, ch. 8.

Sharing clusters between teamsOne shared clusterBest use of capacityWeak tenant controlsPlatform on topRich access controlsVendor layer to learnFederated clustersStrong separationHard to move capacityMultitenancy was left out of Kubernetes on purpose, so organizations work around it.
ToolRole
HelmA package manager: install third-party software such as Kafka
OperatorManages the ongoing life cycle, such as upgrades. Can be used with Helm.
CRDCustom resource definition: extend the Kubernetes API with your own object types
Should you use it? Running your own cluster is a big job. Prefer a fully managed one. In the public cloud, ask whether you need Kubernetes at all: a FaaS or PaaS platform may hide the complexity. Newman expects Kubernetes to sit beneath higher-level layers such as Knative.

Safe releases

Roll out without downtime, then release gradually.

Zero-downtime rolling updatev1 podsserving trafficNew v2 podstartingReady?readiness probeOld pod gonerepeat to the endLiveness probe restarts a stuck pod. Readiness probe decides if it gets traffic. kubectl rollout undo reverts.
Service mesh: separate deployment from releaseDeploy v2no traffic yetTest usersrouted to v2Shift 5%real users100% v2remove v1Deploy = running in production. Release = users get it. Istio's Envoy sidecars route the traffic.
Routing rules in IstioAPI gatewayEnvoy sidecarConsumer v1Consumer v2GET /consumers/1normal user → v1header testusertest user → v2Then weight 95/5 → 0/100, then delete v1.

Progressive delivery

Progressive delivery is continuous delivery with fine-grained control over the blast radius. It rests on one idea: deployment (installing a version) is not release (users get it). From Building Microservices, ch. 8.

TechniqueIdeaNote
Blue-greenRun the new version beside the old, check it, then switch trafficSimple zero-downtime option
Feature toggleHide deployed code behind a switchSupports trunk-based work. Start with a config file.
Canary releaseA small subset sees the new version, then widenTools such as Spinnaker can ramp up on error rates
Parallel runSend each request to both versions and compareOnly one result is used
A parallel runRequestfrom a userRoutercopies the callOld versionsource of truthNew versionresult ignoredComparediff resultsGuard side effects: do not send two real order updates. The user sees only the old result.

Recap

Quick check

Rolling updates already wait for the readiness probe. Why add Istio?
Show answer

Readiness only shows the pod started. A bug that appears under real traffic would still spread. Istio lets you test v2 with test users, then shift traffic slowly and revert at once.