How we deployed, scaled and monitored JsReport on AKS with Helm? - Part 3
How we deployed JsReport with Docker and Helm on AKS, then scaled, monitored, secured and operated the service.
How we deployed, scaled and monitored JsReport on AKS with Helm? - Part 3
In the previous article, we discussed how we spin up and tear down the whole AKS infrastructure with Infrastructure as Code. Once the infrastructure is ready, the next questions are obvious. How do we get our application into the cluster? How does it scale? How do we know what is happening inside it? In this article, we are going to see how we deployed JsReport with Docker and Helm, how it scales, how we monitor and secure it, the challenges we faced, and the best practices we collected along the way.
TL;DR Summary
- The deployment has four steps, build the application, build the custom Docker images and push them to ACR, prepare the Helm chart and deploy it.
- Azure Container Registry stores both our private Docker images and our Helm charts.
- Helm works like a package manager for Kubernetes. It simplifies releases, upgrades and rollbacks.
- AKS scales the cluster nodes, and the Horizontal Pod Autoscaler scales the pods.
- Container logs, infrastructure health and live log analysis are available through Azure Monitor, as long as the application writes its logs to the console.
- Keep containers ephemeral and stateless, run one application per image, version everything and use a .dockerignore file.
- “Managed” doesn’t mean “no downtime”. Node patching and cluster upgrades caused an application outage until we designed for them.
- Azure Key Vault stays the single source of truth for secrets. The Secrets Store CSI Driver syncs them into Kubernetes secrets, and the pods read them through
secretKeyRef. - The platform brought its own moving parts, frequent Kubernetes upgrades with deprecated APIs, the Helm 2 to Helm 3 move, expiring service principal secrets and Docker Hub pull limits.
Steps to Deploy
Let us first see the deployment steps at a high level,
- Prepare the application build.
- Prepare the custom Docker images and push them to Azure Container Registry (ACR).
- Prepare the Helm chart.
- Deploy the Helm chart into AKS.
All four steps run in the Azure DevOps deployment pipeline. Nobody runs docker push or helm upgrade from their machine against a shared environment.
Azure Container Registry
ACR is our private registry, and we use it for two things,
- Store all our private Docker images.
- Store all our Helm charts.
Keeping both in one place gives us a single source for everything we deploy. The cluster pulls the images from ACR using the AcrPull role that we assigned in the infrastructure step, so we don’t keep any registry credentials in the cluster.
What is Helm?
Helm is a package manager for Kubernetes. In simple terms, it does for Kubernetes what NuGet or npm does for our code. Instead of applying a long list of YAML files one by one, we package them into a chart, give it a version, and install or upgrade it as one unit.
Our JsReport chart manages the following Kubernetes objects,
- Ingress controller - The entry point that routes the incoming traffic to our services.
- Services - A load balancer service for the external traffic and cluster IP services for the internal traffic.
- Deployment - It describes the JsReport pods, the image version, the replicas and the resources.
- Secret - It stores the sensitive information like connection strings and keys.
- ConfigMaps - It stores the non-sensitive configuration.
- HorizontalPodAutoscaler - It defines when to add or remove pods.
Helm also manages the external chart dependencies, so we don’t need to install them separately.
Why Helm made a difference?
Here are some of the reasons why we found Helm useful,
- Simplified release and upgrade - One command (or one pipeline step) installs or upgrades the whole application with all its objects.
- Simplified rollback - Every release has a revision. When something goes wrong, we roll back to the previous revision instead of fixing YAML files under pressure.
- One chart, many environments - The same chart is deployed into pre-production and production with different values.
Scalability
Scaling happens at two levels in our setup,
- Cluster level - AKS auto scales the cluster, it adds nodes when the pods don’t fit anymore and removes them when they are not needed.
- Pod level - The Horizontal Pod Autoscaler scales the JsReport pods based on the load.
These two work together. The Horizontal Pod Autoscaler asks for more pods, and when the existing nodes run out of capacity, the cluster autoscaler adds more nodes. Keep in mind that the pod level scaling works well only when the pods are stateless, which is why our templates and PDFs live outside the containers.
Pod level scaling
Our Horizontal Pod Autoscaler rules scale out the JsReport pods when the average CPU utilization goes above 70% or the average memory utilization goes above 80%. Report rendering is both CPU and memory hungry, so CPU alone was not enough. Keep in mind that scaling on memory needs the autoscaling/v2beta2 API, the older autoscaling/v1 supports only CPU. When both metrics are defined, the autoscaler calculates the required number of pods for each metric and takes the higher one.
Cluster level scaling
Initially, we expected the cluster to scale the same way as the pods, add a node when the CPU or memory of the nodes stays above 80% for 5 minutes. That is how the autoscale rules of a normal virtual machine scale set work, but it is not how the AKS cluster autoscaler works, and putting such rules on the node pool’s scale set is not supported in AKS.
The cluster autoscaler doesn’t look at the CPU or memory utilization of the nodes at all. It works like this,
- Scale out - When the Horizontal Pod Autoscaler creates new pods and the scheduler can’t place them on any node because there is not enough requested CPU or memory left, the pods stay in Pending state. The cluster autoscaler watches for these pending pods and adds a node.
- Scale in - When a node is under-used for a while (by default, when the requested resources of its pods are below 50% of the node capacity for 10 minutes) and its pods can be moved to other nodes, the cluster autoscaler drains and removes it.
- Boundaries - We set the minimum and maximum node count for the node pool in our ARM template, so the cluster never goes below what we need for availability or above what we are ready to pay for.
So, in our case, the 70% CPU and 80% memory rules of the Horizontal Pod Autoscaler indirectly decide when a new node is added. The pod rules add pods, and the new pods that don’t fit trigger the new node.
The biggest learning here is that the cluster autoscaler works on the resource requests, not on the actual usage. If the pods don’t define the CPU and memory requests, the scheduler thinks they need almost nothing, it keeps placing them on the same nodes, the nodes get overloaded and the cluster autoscaler never adds a node. Always define realistic resource requests in the deployment, it is the input for both the scheduler and the cluster autoscaler.
Monitoring
A container that you can’t see into is a black box. Find below what we monitor and how,
- Infrastructure health and metrics - Node and pod CPU, memory and status through Azure Monitor and our Log Analytics workspace.
- Container logs - All container logs are collected into Log Analytics, so we can query them after the pod is gone.
- Deployment - The status of our deployments and rollouts.
- Live log analysis - We can watch the logs as they happen, which is very handy right after a deployment.
There is one important condition for all of this, the application logs must be written to the console. Containers are ephemeral, so a log file inside a container disappears with the container. When the application writes to the console (standard output), the platform collects the logs for us.
Security
Security is the area where we did the basics first and planned the rest,
- Sensitive information is stored in Azure Key Vault and reaches the pods as Kubernetes secrets, not through the images or the chart values committed to Git.
- Access to the cluster is controlled through Azure Active Directory and RBAC.
- Planned - SSL configuration.
- Planned - Custom domain with Cloudflare in front of the cluster.
Be honest about what is done and what is planned. A “planned” item is not a security control yet.
Connecting Azure Key Vault through secret references
Kubernetes secrets are only base64 encoded, not encrypted, and anyone who can read the secret in the cluster can read the value. On the other hand, our organization already keeps the connection strings, keys and certificates in Azure Key Vault. So, we didn’t want a second copy of the secrets maintained by hand in the cluster. We wanted Key Vault to remain the single source of truth and the pods to consume the secrets from it.
At that time, the way to do it was the Secrets Store CSI Driver with the Azure Key Vault provider. Both were open source projects, still in early versions, and not yet a built-in AKS feature. We installed them into the cluster with their Helm charts. Simply put, the driver mounts the Key Vault secrets into the pod as files, and it can also sync them into a regular Kubernetes secret, so the application can read them through the usual secret references.
Here is how the pieces fit together,
- SecretProviderClass - A custom resource that tells the driver which Key Vault to use and which secrets to fetch. With the
secretObjectssection, it also creates a Kubernetes secret from the fetched values. - Identity to access Key Vault - The driver needs an identity that has permission to read the secrets. At that time, the options were a service principal whose credentials are stored as a Kubernetes secret, AAD Pod Identity, or the managed identity of the nodes. We used a service principal and gave it a Key Vault access policy with only the Get permission on secrets.
- Volume mount - The pod mounts a CSI volume that refers to the SecretProviderClass.
- Secret reference - The container reads the synced Kubernetes secret as an environment variable through
secretKeyRef.
The following is a simplified version of the SecretProviderClass, with the values replaced by place holders,
apiVersion: secrets-store.csi.x-k8s.io/v1alpha1
kind: SecretProviderClass
metadata:
name: jsreport-keyvault
spec:
provider: azure
secretObjects:
- secretName: jsreport-secrets
type: Opaque
data:
- objectName: storage-connection-string
key: StorageConnectionString
parameters:
usePodIdentity: "false"
keyvaultName: "<KeyVaultName>"
tenantId: "<TenantId>"
objects: |
array:
- |
objectName: storage-connection-string
objectType: secret
And the deployment mounts the volume and refers to the synced secret,
containers:
- name: jsreport
image: <AcrName>.azurecr.io/jsreport:<Version>
env:
- name: StorageConnectionString
valueFrom:
secretKeyRef:
name: jsreport-secrets
key: StorageConnectionString
volumeMounts:
- name: secrets-store
mountPath: /mnt/secrets-store
readOnly: true
volumes:
- name: secrets-store
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes:
secretProviderClass: jsreport-keyvault
nodePublishSecretRef:
name: secrets-store-creds
Here are the learnings from this integration,
- The Kubernetes secret is created only when a pod mounts the volume. If no pod mounts the CSI volume, the synced secret doesn’t exist and the
secretKeyReffails, so the pod is stuck at start up. Keep the volume mount even if the application reads only the environment variables. - Changing a secret in Key Vault doesn’t change the running pods. Automatic rotation was not something we could rely on in those early versions, and environment variables are read only at start up anyway. So, after updating a secret in Key Vault, we restarted the pods through a new rollout.
- The identity that reads Key Vault is one more secret to manage. The service principal credentials stored in
secrets-store-credsalso expire, exactly like the cluster service principal in the challenges below. Track them, otherwise the pods can’t start after the expiry. - Keep the SecretProviderClass in the Helm chart, next to the deployment. Only the Key Vault name and the tenant change per environment, so they are just values in the chart.
- Give the identity the least privilege. Get permission on secrets is enough, it doesn’t need to list or change them.
Challenges
Not everything was smooth. Find below the challenges we faced, and the ones that the platform itself brings to anyone running AKS.
Patching the underlying VMs
This one hurt us the most. AKS is a managed service, but the nodes are still virtual machines, and they need OS patches and reboots. Azure applies the security patches to the Linux nodes, but some of the patches need a reboot to take effect, and the node image and Kubernetes upgrades replace the nodes one by one. During this process, each node is cordoned and drained, which means all the pods on that node are evicted and rescheduled somewhere else.
Though it is managed by Azure, our application had an outage until the patching completed. When the pods are evicted and there are no other healthy replicas to serve the requests, the service is simply down until the new pods are up and ready. A “managed” service manages the infrastructure, not the availability of our application.
Here is what we learned to do,
- Run at least two replicas of the application, and spread them across nodes, otherwise one node reboot takes the whole service down.
- Define a PodDisruptionBudget, so Kubernetes doesn’t evict all the pods at the same time during a drain.
- Configure readiness probes, so the traffic goes only to the pods that are actually ready to serve.
- Plan the reboots and upgrades in a low traffic window instead of letting them happen whenever. At that time, the tools for this were still maturing, so we had to plan it ourselves, for example with a reboot daemon like kured and a scheduled upgrade process.
Keeping up with Kubernetes versions
Kubernetes moves fast, and it releases a new minor version every few months. AKS supports only a limited window of recent versions, so a cluster that is not upgraded regularly quickly falls out of support. Upgrading is not just clicking a button. Kubernetes 1.16 removed the old extensions/v1beta1 and apps/v1beta1 APIs for deployments, and charts and manifests written with them stopped working. The Ingress API was also moving to networking.k8s.io/v1. Keep in mind that every cluster upgrade is also a check of your Helm charts.
The move from Helm 2 to Helm 3
Helm 3 was released recently and the community was in the middle of the migration. Helm 3 removed Tiller, the server side component of Helm 2, which was good news for security, but it also changed how releases are stored. Many examples and charts on the internet were still written for Helm 2, and the old stable chart repository was being deprecated. We had to be careful to follow the Helm 3 way and not copy the Helm 2 examples blindly.
Service principal secrets expire
The AKS cluster used a service principal to talk to other Azure resources, like the container registry and the network. The secret of a service principal expires, by default after one year, and when it expires, the cluster can no longer pull images or manage the load balancer. It is a time bomb if nobody tracks it. Managed identities for AKS remove this problem, but they were still new and our templates were built around the service principal. So, we had to track the expiry and plan the credential rotation.
Docker Hub pull limits
Docker Hub started to enforce pull rate limits for anonymous and free users. Base images pulled from Docker Hub during the build or by the cluster could suddenly fail. Keeping our images and the base images we depend on in our own Azure Container Registry reduces this risk, and it is one more reason to have a private registry.
Docker as the container runtime
Kubernetes announced that Docker as a container runtime (dockershim) is deprecated, and AKS moved new node pools to containerd from Kubernetes 1.19. It sounded scary at first, but our images built with Docker run the same on containerd. The real impact is only on anything that depends on the Docker daemon on the node, like mounting the Docker socket.
Some of the Best Practices
Here are the best practices we collected during this journey,
- Create ephemeral and stateless containers. Use a persistent volume or a centralized storage or datastore for the data, otherwise you lose the data when a pod is replaced and you can’t scale out.
- Run one application per image for better operations. It keeps the images small, the logs clean and the scaling independent.
- Use proper versions for the Docker images and also include the latest tag. A versioned image tells you exactly what is running, and the latest tag is convenient for local use.
- Use proper versions for the Helm charts as well, otherwise rollbacks become guesswork.
- Use a .dockerignore file. It keeps unnecessary files out of the build context and out of the image, which makes the builds faster and the images smaller.
Where Else Can Docker Help Us?
This experience also made us think about where else containers can help us. Here are two use cases we identified,
- Strangler pattern - To improve the scalability of a monolith, we can move parts of it into containers one by one. It is applicable only when the business logic is processed inside the application, not inside the database.
- High performance computing - Task Parallel Library (TPL), a grid computing provider and Docker together can scale out the heavy calculations. Our candidates are the CLR calculation engine and the decumulation calculation engine.
Self-Reflection
Let me close this series with a few personal reflections.
- Containers are not just a packaging format. They changed how we think about state, logs, configuration, secrets and scaling. Every “small” habit from the virtual machine world, like writing logs to a local file, had to change.
- Kubernetes is powerful, and the power comes with a cost. We had to learn ingress controllers, services, deployments, secrets, config maps and autoscalers before we could run one reporting service. For a small application, that is a lot. It is important to ask whether a simpler option is enough before choosing Kubernetes.
- Helm was the tool that made Kubernetes manageable for us. Without it, we would have spent our time managing YAML files instead of the application.
- Automation is a discipline. Everything we did manually once, we eventually had to automate. Doing it in the pipeline from day one would have saved us time.
- The experience was worth more than the application. JsReport was a small service, but the skills we built in Docker, Kubernetes, Helm, IaC and Azure are now the foundation for our next containerization work.
Wrap up
In this article, we have looked at how we deployed JsReport with Docker and Helm, how ACR stores our images and charts, how the cluster and the pods scale, how we monitor and secure the application, the challenges of patching and keeping up with the platform, and the best practices and use cases that came out of it. I really appreciate that you took the time to read this article. In the next article, I will walk you through how we set up disaster recovery for JsReport across two Azure regions, and why a stateless service still had its own challenges.
Related Posts
What we learned from containerizing JsReport on AKS? - Part 1
Lessons from containerizing JsReport on AKS, including Docker, Helm, Azure infrastructure, pipelines, scaling and the disposable environment lifecycle.
How we set up disaster recovery for a stateless service on AKS? - Part 4
How we designed active-passive disaster recovery for JsReport across Azure regions, including replicated storage, failover and recovery trade-offs.
How we spin up and tear down AKS with Infrastructure as Code? - Part 2
How we created and removed JsReport’s AKS infrastructure with ARM templates and Azure DevOps pipelines, including drift and permissions lessons.