How to connect to k8s api server within a pod using k8s java client



I have a java application built as a docker image.

The image is deployed in a k8s cluster.

In the java application, I want to connect to the api server and save something in Secrets.

How can I do that with k8s java client?

Current Attempts

The k8s official document says:

From within a pod the recommended ways to connect to API are:

  • run kubectl proxy in a sidecar container in the pod, or as a background process within the container. This proxies the Kubernetes API to the localhost interface of the pod, so that other processes in any container of the pod can access it.
  • use the Go client library, and create a client using the rest.InClusterConfig() and kubernetes.NewForConfig() functions. They handle locating and authenticating to the apiserver.

But I can't find similar functions neither similar examples in java client.

-- kevin807210561

1 Answer


With the assumption that your Pod has a serviceAccount automounted -- which is the default unless you have specified otherwise -- the ClientBuilder.cluster() method reads the API URL from the environment, reads the cluster CA from the well known location, and similarly the ServiceAccount token from that same location.

Then, while not exactly "create a Secret," this PatchExample performs a mutation operation which one could generalize into "create or update a Secret."

-- mdaniel
Source: StackOverflow