How to wait until kubernetes service starts?

7/1/2019

In kubernetes I create a service:

V1ServicePort servicePort = new V1ServicePort().port(2000);
servicePort.setName("clientPort");

V1ServiceSpec spec = new V1ServiceSpec();
spec.addPortsItem(servicePort);
spec.setType("NodePort");
spec.putSelectorItem("app", "myAppName");

V1Service service = new V1Service();
service.setMetadata(new V1ObjectMeta().name("my_service"));
service.setSpec(spec);

api.createNamespacedService(namespace, myService, null);

but it does not start immediately. I can connect to a service using a specific port only after 10 seconds.

How to issue a wait request in Java until a service starts?

-- mercury0114
java
kubernetes
service

1 Answer

7/1/2019

It's typical in Kubernetes to just crash. Make sure to log an exception or error message.

This sounds bad, but what will happen in reality is that Kubernetes defaults to restarting crashed pods. Given JVM startup time it's likely the second startup will have taken 10 seconds. If your process starts up really quickly you will briefly enter CrashLoopBackOff state, which just means Kubernetes is pausing in between restarting the pod.

One important consequence of this approach is that if the backend service fails to actually come up, the services that depend on it will show as failed too (they will get stuck in CrashLoopBackOff). Then you can diagnose this with kubectl logs and see what's actually going on.

Other tricks like the wait-for-it.sh script that's common in Docker Compose setups or just putting your connect call in a for loop would work too, but would take longer to fail if the system as a whole is unhealthy.

-- David Maze
Source: StackOverflow