<p>In kubernetes I create a service:</p>

<pre><code>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);
</code></pre>

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

<p><strong>How to issue a wait request in Java until a service starts</strong>?</p>

mercury0114
<p>It's typical in Kubernetes to just crash.  Make sure to log an exception or error message.</p>

<p>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.</p>

<p>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 <code>kubectl logs</code> and see what's actually going on.</p>

<p>Other tricks like the <a href="https://github.com/vishnubob/wait-for-it" rel="nofollow noreferrer">wait-for-it.sh script</a> 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.</p>
