K8S Fabric8 API + deploy, pod and service in one go?

11/16/2019

In K8S Fabric8 API is there an example or sample code to create deployment, pod and service in one go?

Please help!

-- TuneIt
fabric8
kubernetes

1 Answer

1/16/2020

You can create a Deployment and expose it using a Service like this here:

try (KubernetesClient client = new DefaultKubernetesClient()) {
    // Create a simple Nginx Deployment
    Deployment deployment = new DeploymentBuilder()
            .withNewMetadata().withName("nginx-deployment").addToLabels("app", "nginx").endMetadata()
            .withNewSpec()
            .withReplicas(3)
            .withNewSelector()
            .withMatchLabels(Collections.singletonMap("app", "nginx"))
            .endSelector()
            .withNewTemplate()
            .withNewMetadata().addToLabels("app", "nginx").endMetadata()
            .withNewSpec()
            .addNewContainer()
            .withName("nginx")
            .withImage("nginx:1.7.9")
            .addNewPort().withContainerPort(80).endPort()
            .endContainer()
            .endSpec()
            .endTemplate()
            .endSpec()
            .build();
    client.apps().deployments().inNamespace("default").create(deployment);

    // Expose the above created Deployment using a NodePort service
    Service service = new ServiceBuilder()
            .withNewMetadata().withName("nginx-svc").addToLabels("app", "nginx").endMetadata()
            .withNewSpec()
            .addNewPort()
            .withName("http")
            .withPort(80)
            .withTargetPort(new IntOrString(80))
            .endPort()
            .withSelector(Collections.singletonMap("app", "nginx"))
            .withType("NodePort")
            .endSpec()
            .build();
    client.services().inNamespace("default").create(service);
}

Once created, you can check the resources created:

~ : $ kubectl get deploy
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
nginx-deployment   3/3     3            3           3m33s
~ : $ kubectl get svc
NAME         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1      <none>        443/TCP        4m31s
nginx-svc    NodePort    10.96.166.83   <none>        80:32174/TCP   3m35s
~ : $ kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-54f57cf6bf-dkh67   1/1     Running   0          4m48s
nginx-deployment-54f57cf6bf-dx2ql   1/1     Running   0          4m48s
nginx-deployment-54f57cf6bf-mwgkk   1/1     Running   0          4m48s
~ : $ minikube ip
192.168.39.39

Once all pods are ready, you can access your application at $MINIKUBE_IP:$NODEPORT(32174 in our case)enter image description here

-- Rohan Kumar
Source: StackOverflow