I want my application to behave differently based on whether it's running within K8s vs on developer machines.
Is there any way that my Java application can get to know if it's running within the context of K8s?
There is nothing foolproof, but there are several good enough strategies. The most common is checking for the service account credentials mount path. Another is explicit env vars.
One way would be to look for environment variables that are exclusively present when your application is running in a Kubernetes cluster.
You can get a list of those variables with: kubectl exec -it -n <namespace> <pod> printenv | grep '^KUBERNETES_'
. For reference, these are the variables I get (service pod):
KUBERNETES_SERVICE_HOST
KUBERNETES_PORT_443_TCP
KUBERNETES_SERVICE_PORT_HTTPS
KUBERNETES_PORT
KUBERNETES_PORT_443_TCP_ADDR
KUBERNETES_PORT_443_TCP_PORT
KUBERNETES_SERVICE_PORT
KUBERNETES_PORT_443_TCP_PROTO