How to make kubernetes service handle multiple ports in JAVA?

6/26/2019

I am trying to make my service listen to multiple ports:

V1Service service = new V1Service();
service.setMetadata(new V1ObjectMeta().name("tests"));
V1ServiceSpec spec = new V1ServiceSpec();
spec.setType("NodePort");
spec.putSelectorItem("name", "tests");
spec.addPortsItem(new V1ServicePort().port(25452));

// WHEN I ADD ANY OF THE 3 LINES BELOW, THE CODE CRASHES, WHY?
spec.addPortsItem(new V1ServicePort().port(24932));
spec.addPortsItem(new V1ServicePort().port(25445));
spec.addPortsItem(new V1ServicePort().port(25432));

service.setSpec(spec);

mmaService = api.createNamespacedService(namespace, service, null);

However, the code executes only if one port is included, otherwise an exception

io.kubernetes.client.ApiException: Unprocessable Entity
at io.kubernetes.client.ApiClient.handleResponse(ApiClient.java:882)
at io.kubernetes.client.ApiClient.execute(ApiClient.java:798)
at io.kubernetes.client.apis.CoreV1Api.createNamespacedServiceWithHttpInfo(CoreV1Api.java:9237)
at io.kubernetes.client.apis.CoreV1Api.createNamespacedService(CoreV1Api.java:9221)

is thrown when calling the createNamespacedService method. How to fix this?

-- mercury0114
java
kubernetes
port
service

1 Answer

6/26/2019

If you want to expose more than one service port, you must assign each of them a unique name. Either use the constructor with a name or call .setName() on a reference variable, since that is not a builder method.

-- Thomas
Source: StackOverflow