Using C# with Kubernetes

Ali Kanso
3 min readJul 29, 2021

The C-Sharp (C#) K8s client library offers a rich set of features allowing developers to write K8s client applications to deploy and manage their workloads.

In this article, we present a comprehensive example of using this C-Sharp library, by creating:

  • deployments,
  • pods,
  • configmaps,
  • secrets,
  • and services.

In addition, we will show configuration patterns such as:

  • liveness probes,
  • readiness probes,
  • init containers,
  • mounting configmaps as volumes,
  • and using secrets as environment variables
K8s Full Example

Application Overview

Our deployment is an Nginx server, it serves html content that is defined in a configmap. It also has its env variables configured from two sources, a secret and a configmap.

The configmap data, is inserted as a file called index.htm that is mounted in the default directory where Nginx serves static content under /usr/share/nginx/html.

The secret data keys are used to populate env variables in the deployment.

The deployment is abstracted by a service of type NodePort.

Finally, we have a pod that constantly is checking that our Nginx server is running.

Deployment Content:

The patterns we use here include: mounting the configmap as a volume, using the secret keys as env variables and using an HTTP liveness probe. We also use the Downward API to pass the IP address of the deployment’s pod as an environment variable.

ConfigMaps Content

In the data section of the configmap, we set the “hmtl” key into the desired html content we wish our nginx deployment’s pods to serve. This key will be mounted as a file inside the nginx containers.

Secret Content

Our secret contains two keys in the data section. One thing to note here is that the value of the key is an array of bytes.

Service Content

Our service is of type NodePort allowing us to reach the nginx from outside the K8s cluster.

Pod Content:

Our Pod has an init container that checks if the DNS lookup is successful for our service defined above, once the service has endpoints configured, the init container exits allowing the main container to start. We apply readiness probes to the main container.

This is a common design pattern to reflect dependency. In our use case, the nginx deployment has to be up and exposed before our pod start sending requests to it.

Conclusion

In this article, we presented an example of using the C# K8s client library to create most of the constructs a developer might need when interacting with K8s. Such constructs can be used in a K8s Operator that manages the dependencies and life-cycle of a given application.

--

--

Ali Kanso

Ali is a Principle Software Engineer at Microsoft, He previously worked for IBM Research and Ericsson Research. He holds a Ph.D. in computer engineering.