Java簡單操作k8s,創(chuàng)建Deployment、Service、訪問Nginx實踐
1.Maven依賴
<!-- k8s client -->
<dependency>
<groupId>io.fabric8</groupId>
<artifactId>kubernetes-client</artifactId>
<version>4.10.2</version>
</dependency>2.初始化 k8s 客戶端
初始化KubernetesClient客戶端
首先需要找到 /etc/kubernetes/admin.conf文件

這是連接k8s的配置文件,通過這個文件,就可以在Java程序中連接上k8s,初始化KubernetesClient客戶端
將該文件的內容復制進kubeconfig,預先存好kubeconfig的文件位置:C:\Users\26411\Desktop\AI平臺\kubeconfig
application.yml
k8s: kubeconfig: C:\Users\26411\Desktop\AI平臺\kubeconfig
編寫配置類,初始化KubernetesClient為Bean
@Configuration
public class K8sConfig {
@Value("${k8s.kubeconfig}")
private String kubeconfigPath;
@Bean
public KubernetesClient getClient() throws IOException {
File configFile = new File(kubeconfigPath);
final String configYaml = String.join("\n", Files.readAllLines(configFile.toPath()));
Config config = Config.fromKubeconfig(configYaml);
config.setTrustCerts(true);
return new DefaultKubernetesClient(config);
}
}
3.測試類測試簡單功能
測試后,在 Xshell 中使用 kubectl 命令查看正常,測試成功。
@SpringBootTest
public class K8sTest {
String namespace = "default";
@Autowired
private KubernetesClient kubernetesClient;
/**
* 獲取Pod
*/
@Test
void testGetPod(){
Pod pod = kubernetesClient.pods().inNamespace("kube-system").withName("kube-apiserver-master").get();
System.out.println(pod);
}
/**
* 創(chuàng)建deployment
*/
@Test
void testCreateDeployment(){
Deployment deployment = getDeployment();
Deployment de = kubernetesClient.apps().deployments().inNamespace(namespace).create(deployment);
}
private Deployment getDeployment() {
Map<String, String> labels = new HashMap<>();
labels.put("run","nginx");
LabelSelector labelSelector = new LabelSelector();
labelSelector.setMatchLabels(labels);
return new DeploymentBuilder()
.withNewMetadata()
.withName("nginx")
.withNamespace(namespace)
.addToLabels(labels)
.endMetadata()
.withNewSpec()
.withSelector(labelSelector)
.withNewTemplate()
.withNewMetadata()
.withName("nginx")
.addToLabels(labels)
.withNamespace(namespace)
.endMetadata()
.withNewSpec()
.addToContainers(buildContainer())
.endSpec()
.endTemplate()
.endSpec()
.build();
}
private Container buildContainer() {
ContainerPort containerPort = new ContainerPort();
containerPort.setProtocol("TCP");
containerPort.setContainerPort(80);
return new ContainerBuilder()
.withNewName("nginx")
.withNewImage("nginx:latest")
.withPorts(containerPort)
.build();
}
/**
* 創(chuàng)建Service
*/
@Test
void testCreateService(){
Service service = kubernetesClient.services().inNamespace(namespace).create(getService());
System.out.println(service);
}
private Service getService() {
HashMap<String, String> selector = new HashMap<>();
selector.put("run","nginx");
ServicePort port = new ServicePort();
port.setProtocol("TCP");
port.setPort(80);
port.setTargetPort(new IntOrString(80));
return new ServiceBuilder()
.withNewMetadata()
.withName("svc-nginx")
.withNamespace(namespace)
.endMetadata()
.withNewSpec()
.withClusterIP("10.109.179.231")
.withPorts(port)
.withSelector(selector)
.withType("NodePort")
.endSpec().build();
}
}
4.編寫工具類封裝簡單功能
@Component
public class K8sUtil {
@Autowired
private KubernetesClient kubernetesClient;
/**
* 獲取一個 Pod
*
* @param namespace 名稱空間
* @param podName Pod名字
* @return {@link Pod}
*/
public Pod getOnePod(String namespace, String podName){
return kubernetesClient.pods().inNamespace(namespace).withName(podName).get();
}
/**
* 創(chuàng)建一個 Pod
*
* @param namespace 名稱空間
* @param podBody Pod內容
* @return {@link Pod}
*/
public Pod createOnePod(String namespace, Pod podBody){
return kubernetesClient.pods().inNamespace(namespace).create(podBody);
}
/**
* 創(chuàng)建Deployment
*
* @param deploymentDto 部署dto
* @return {@link Deployment}
*/
public Deployment createDeployment(DeploymentDto deploymentDto){
Deployment deployment = getDeployment(deploymentDto);
return kubernetesClient.apps().deployments()
.inNamespace(deploymentDto.getNamespace())
.create(deployment);
}
private Deployment getDeployment(DeploymentDto deploymentDto) {
return new DeploymentBuilder()
.withNewMetadata()
.withName(deploymentDto.getDeploymentName())
.withNamespace(deploymentDto.getNamespace())
.addToLabels(deploymentDto.getLabels())
.endMetadata()
.withNewSpec()
.withReplicas(deploymentDto.getReplicas())
.withSelector(deploymentDto.getLabelSelector())
// Template() Pod模板
.withNewTemplate()
.withNewMetadata()
.addToLabels(deploymentDto.getLabels())
.endMetadata()
.withNewSpec()
.addToContainers(buildContainer(deploymentDto))
.endSpec()
.endTemplate()
.endSpec()
.build();
}
private Container buildContainer(DeploymentDto deploymentDto) {
ContainerPort containerPort = new ContainerPort();
containerPort.setProtocol(deploymentDto.getProtocol());
containerPort.setContainerPort(deploymentDto.getContainerPort());
return new ContainerBuilder()
.withNewName(deploymentDto.getContainerName())
.withNewImage(deploymentDto.getImage())
.withPorts(containerPort)
.build();
}
/**
* 創(chuàng)建Service
*
* @param serviceDto 服務dto
* @return {@link Service}
*/
public Service createService(ServiceDto serviceDto) {
Service service = getService(serviceDto);
return kubernetesClient.services().inNamespace(serviceDto.getNamespace()).create(service);
}
private Service getService(ServiceDto serviceDto) {
ServicePort port = new ServicePort();
port.setProtocol(serviceDto.getProtocol());
port.setPort(serviceDto.getPort());
port.setTargetPort(new IntOrString(serviceDto.getTargetPort()));
return new ServiceBuilder()
.withNewMetadata()
.withName(serviceDto.getServiceName())
.withNamespace(serviceDto.getNamespace())
.endMetadata()
.withNewSpec()
//.withClusterIP()
.withPorts(port)
.withSelector(serviceDto.getSelector())
.withType(serviceDto.getType())
.endSpec()
.build();
}
}
附上兩個封裝信息的實體類
@Data
public class DeploymentDto {
/**
* 名稱空間
*/
private String namespace;
/**
* deployment名字
*/
private String deploymentName;
/**
* 副本個數(shù)
*/
private Integer replicas;
/**
* Pod模板的標簽、Deployment標簽選擇器 會匹配到的標簽
*/
private Map<String,String> labels;
/**
* Deployment標簽選擇器
*/
private LabelSelector labelSelector;
// spec下的 containers
/**
* 容器要拉取運行的鏡像
*/
private String image;
/**
* 容器名稱
*/
private String containerName;
/**
* 容器端口
*/
private Integer containerPort;
/**
* 協(xié)議
*/
private String protocol;
}
@Data
public class ServiceDto {
/**
* 名稱空間
*/
private String namespace;
/**
* Service名稱
*/
private String serviceName;
/**
* 端口
*/
private Integer port;
/**
* 協(xié)議
*/
private String protocol;
/**
* 目標端口
*/
private Integer targetPort;
/**
* Service的標簽選擇器 選擇有對應標簽的Pod (但是其實通過Deployment操控)
*/
private Map<String,String> selector;
/**
* 類型 :NodePort、ClusterIP等等
*/
private String type;
}
5.訪問部署的Nginx

訪問 http://192.168.242.100:30439/

6.后續(xù)擴展
封裝操作更多的功能,操作更多資源,例如 ingress
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Flink流處理引擎零基礎速通之數(shù)據(jù)的抽取篇
今天不分享基礎概念知識了,來分享一個馬上工作需要的場景,要做數(shù)據(jù)的抽取,不用kettle,想用flink。實際就是flink的sql、table層級的api2022-05-05
Java隨機值設置(java.util.Random類或Math.random方法)
在編程中有時我們需要生成一些隨機的字符串作為授權碼、驗證碼等,以確保數(shù)據(jù)的安全性和唯一性,這篇文章主要給大家介紹了關于Java隨機值設置的相關資料,主要用的是java.util.Random類或Math.random()方法,需要的朋友可以參考下2024-08-08
java調用openoffice將office系列文檔轉換為PDF的示例方法
本篇文章主要介紹了java使用openoffice將office系列文檔轉換為PDF的示例方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-11-11
spring boot與spring mvc的區(qū)別及功能介紹
這篇文章主要介紹了spring boot與spring mvc的區(qū)別是什么以及spring boot和spring mvc功能介紹,感興趣的朋友一起看看吧2018-02-02
SpringBoot中實現(xiàn)數(shù)據(jù)脫敏的六種常用方案
在日常的開發(fā)開發(fā)工作中,我相信各位老鐵肯定遇到過這種需求手機號中間四位得用*顯示等,既要展示部分數(shù)據(jù),又要保證敏感信息不泄露,這就是所謂的數(shù)據(jù)脫敏,所以今天給大家分享6種我在項目中常用的脫敏方案,需要的朋友可以參考下2025-09-09

