k8s

471 阅读2分钟

创建镜像

FROM openjdk:8-jdk-alpine
ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
COPY test-app-1.0-SNAPSHOT.jar /opt/app.jar
COPY run.sh /opt/run.sh

EXPOSE 8899
ENTRYPOINT ["/bin/sh", "/opt/run.sh"]

运行脚本

#!/bin/bash
java -jar /opt/app.jar 2>&1

k8s client 配置

package com.k8s.ops.config;

import io.fabric8.kubernetes.api.model.NamespaceList;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class K8sClientConfig {

    @Bean
    public KubernetesClient kubernetesClient() {
        Config config = new ConfigBuilder().withMasterUrl("https://localhost:6443").build();
        KubernetesClient client = new DefaultKubernetesClient(config);
        NamespaceList namespaceList = client.namespaces().list();
        namespaceList.getItems().forEach(System.out::println);
        return client;
    }
}

测试controller


import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
public class CommandController {

    @Autowired
    private KubernetesClient client;

    @GetMapping("deploy/{tenant}")
    public String deploy(@PathVariable("tenant") String tenant) {

        String namespace = "ns" + tenant;
        String label = "rcs-" +tenant;
        Namespace ns = new NamespaceBuilder().withNewMetadata().withName(namespace).addToLabels("tenant", tenant).endMetadata().build();
        log.info("Created namespace: {}", client.namespaces().createOrReplace(ns));
        try {
            log.info("Namespace: {}", ns);
            Deployment deployment = client.apps().deployments().inNamespace(namespace).load(CommandController.class.getResourceAsStream("/endpoints-deployment.yml")).get();

            log.info("Deployment created");
            client.apps().deployments().inNamespace(namespace).create(deployment);

            Service service = client.services().inNamespace(namespace).load(CommandController.class.getResourceAsStream("/endpoints-service.yml")).get();

            log.info("Service created");
            client.services().inNamespace(namespace).create(service);

//            Endpoints endpoints = new EndpointsBuilder()
//                    .withNewMetadata().withName("external-web").withNamespace(namespace).endMetadata()
//                    .withSubsets().addNewSubset().addNewAddress().withIp("10.10.50.53").endAddress()
//                    .addNewPort().withPort(80).withName("apache").endPort()
//                    .endSubset()
//                    .build();
//            log.info("Endpoint created");
//            client.endpoints().inNamespace(namespace).create(endpoints);
//            log.info("Endpoint url");
//            endpoints = client.endpoints().inNamespace(namespace).withName("external-web").get();
//            log.info("Endpoint Port {}", endpoints.getSubsets().get(0).getPorts().get(0).getName());
//            return endpoints.getSubsets().get(0).getPorts().get(0).getName();


            String serviceURL = client.services().inNamespace(namespace).withName(service.getMetadata().getName()).getURL("http");

            log.info(serviceURL);

            return serviceURL;

        } catch (Exception e) {
            log.error("Exception occurred: {}", e.getMessage(), e);
        } finally {
//            client.namespaces().withName(namespace).delete();
        }
        return null;
    }
}

获取服务状态

 @GetMapping("status/{tenant}")
    public String getSatus(@PathVariable("tenant") String tenant) {
        try{
            String namespace = "ns" + tenant;
            String phase = client.pods().inNamespace(namespace).withLabel("app", "rcs").list().getItems().get(0).getStatus().getPhase();
            if("Running".equals(phase)) {
                return "1";
            }
        } catch (Exception e) {
            return "0";
        }
        return "0";
    }

服务扩缩容

@GetMapping("replicas/{tenant}/{size}")
    public String replicas(@PathVariable("tenant") String tenant,@PathVariable("size") Integer size) {

        String namespace = "ns" + tenant;
        Deployment deployment = client.apps().deployments().inNamespace(namespace)
                .load(CommandController.class.getResourceAsStream("/endpoints-deployment.yml")).get();

        deployment.getSpec().setReplicas(size);

        log.info("Deployment created");
        client.apps().deployments().inNamespace(namespace).createOrReplace(deployment);

        return "success";
    }

endpoint-deployment.yaml


#
# Copyright (C) 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

apiVersion: apps/v1
kind: Deployment
metadata:
  name: deployment-rcs
  labels:
    app: rcs
spec:
  replicas: 1
  selector:
    matchLabels:
      app: rcs
  template:
    metadata:
      labels:
        app: rcs
    spec:
      containers:
        - name: container-rcs
          image: test-app:1.0
          ports:
            - containerPort: 8899

endpoints-service.yml

#
# Copyright (C) 2015 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

apiVersion: v1
kind: Service
metadata:
  name: service-rcs
spec:
  type: NodePort
  ports:
    - name: http
      port: 8899
      targetPort: 8899
      protocol: TCP
  selector:
    app: rcs

pom.xml

 <dependency>
            <groupId>io.fabric8</groupId>
            <artifactId>kubernetes-client</artifactId>
            <version>5.0.0</version>
        </dependency>