K8S - 资源清单

集群资源分类:

  1. 名称空间级别
  2. 集群级别
  3. 元数据级别

资源实例化之后别叫作对象

YAML文件

常用字段

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

请添加图片描述
请添加图片描述

生命周期

容器环境初始化:1:init C -初始化容器 ----> main C -主容器 [主容器启动会执行start ,结束会执行stop] ---->readiness 就绪检测 ---->Liceness 生存检测

init C

每一个init C 都要等前一个initC结束之后才能开始执行,initC意外停止 不会导致pod死亡

如果pod的init容器失败k8s会不断重启该pod,知道initC成功为止,然而如果pod对应的retartPolicy为Never,它不会重新启动

启动和退出

请添加图片描述

控制器

pod的分类

自主式pod:pod退出了,此类型的pod就不会被创建
控制器管理的pod:在控制器的生命周期里,始终要维持pod的副本数目

控制器分类

RC/RS(不适用)
Deployment
Daemonset
StateFulSet
job/cronjob
Horizontal pod Autoscaling

Deployment

Deployment概念:用于部署无状态的服务,这个最常用的控制器。一般用于管理维护企业内部无状态的微服务,比如configserver、zuul、springboot。他可以管理多个副本的Pod实现无缝迁移、自动扩容缩容、自动灾难恢复、一键回滚等功能。
虽然ReplicaSet可以确保在任何给定时间运行的Pod副本达到指定的数量,但是Deployment(部署)是一个更高级的概念,它管理ReplicaSet并为Pod和ReplicaSet提供声明性更新以及许多其他有用的功能,所以建议在实际使用中,使用Deployment代替ReplicaSet。
如果在Deployment对象中描述了所需的状态,Deployment控制器就会以可控制的速率将实际状态更改为期望状态。也可以在Deployment中创建新的ReplicaSet,或者删除现有的Deployment并使用新的Deployment部署所用的资源。

c# 创建k8s连接

KubernetesClientConfiguration config = null;
            Kubernetes client = null;
            // 从计算机上的默认kubeconfig加载.
            //var config = KubernetesClientConfiguration.BuildConfigFromConfigFile();

            // 通过默认的 Service Account 访问,必须在 kubernetes 中运行时才能使用
            //var config = KubernetesClientConfiguration.BuildDefaultConfig();

             从特定文件加载
            // var config = KubernetesClientConfiguration.BuildConfigFromConfigFile("./kubeconfig");

             从群集中配置加载:
            // var config = KubernetesClientConfiguration.InClusterConfig();

            // 使用config对象创建客户端。
            //var client = new Kubernetes(config);
            if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
            {
                // 通过配置文件
               // config = KubernetesClientConfiguration.BuildConfigFromConfigFile("./kubeconfig");
                config = KubernetesClientConfiguration.BuildConfigFromConfigFile("./admin.conf");
                //config.SkipTlsVerify = true;
            }
            else
            {
                // 通过默认的 Service Account 访问,必须在 kubernetes 中运行时才能使用
              config = KubernetesClientConfiguration.BuildDefaultConfig();
            }
            try { client = new Kubernetes(config); } catch(Exception ex) { Console.WriteLine(ex.Message); }

            return client;

C# 首次创建pod 创建控制器与服务(pod创建完成之后需要通过server进行端口映射)

  public async Task<string> UpPod(string deploymentName , string appName,string serverName,int PortNumber, NodePortType type, int userId)
        {
            bool IsCreateInitialDeployment = true;
            bool IsCreateInitialServer = true;
            V1NamespaceList nameSpaces = null;
           // Kubernetes client = await CreatingTheClient(); //获取Kubernetes客户端
            #region 创建Deployment,发布服务
            try
            {
                V1DeploymentList DeploymentclientList = client.ListNamespacedDeployment("default");
                V1ServiceList ServiceList = client.ListNamespacedService("default");
                //查询Deploymentclient控制器是否已经被创建,如果已经被创建就不在创建控制器  开始
                foreach (var Deploymentclient in DeploymentclientList) {
                    if (Deploymentclient.Name() == deploymentName)
                    {
                        IsCreateInitialDeployment = false;
                    }
                }
                if (IsCreateInitialDeployment) {
                    //实例deploymentName为ngx-dep3,ngx为appName
                    var Deployment = await CreateInitialDeployment(client, deploymentName, appName, "default",1,userId);
                }
                //查询Server控制器是否已经被创建,如果已经被创建就不在创建服务  结束
                foreach (var Service in ServiceList) {
                    if (Service.Name() == $"{appName}-svc") {
                        IsCreateInitialServer = false;
                    }
                }
                if (IsCreateInitialServer)
                {
                    //serverName为nginx  appName为ngx
                    var Server = await CreateInitialServer(client, "default", serverName, appName, PortNumber, type);
                }
                //查询Server控制器是否已经被创建,如果已经被创建就不在创建服务  开始
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return "ok";
            #endregion

        }

c# 创建控制器

 private async Task<V1Deployment> CreateInitialDeployment(Kubernetes client, string deploymentName,string appName, string deploymentNamespace,int replicas,int userId)
        {
            V1Deployment initialDeployment = null;
            if (client == null)
                throw new ArgumentNullException(nameof(client));

            if (String.IsNullOrWhiteSpace(deploymentName))
                throw new ArgumentException($"deploymentName不能为空");

            if (String.IsNullOrWhiteSpace(deploymentNamespace))
                throw new ArgumentException($"deploymentNamespace不能为空");
            try
            {
                List<V1Container> containers = new List<V1Container>();
                containers.Add(new V1Container() { 
                Name = "nginx",
                Image = "docker-mirror.sh.synyi.com/dorowu/ubuntu-desktop-lxde-vnc:focal",
                VolumeMounts = new V1VolumeMount[]{new V1VolumeMount() { 
                MountPath=$"/root/Desktop",// 容器里面的挂载路径
                Name=$"os{userId}"//卷名字,必须跟下面定义的名字一致
                }
                }
                });
                V1Deployment deployment = new V1Deployment()
                {
                    Metadata = new V1ObjectMeta
                    {
                        Name = deploymentName,
                        Labels = new Dictionary<string, string> { ["app"] = appName, ["type"] = "webservice" }
                    },
                    Spec = new V1DeploymentSpec
                    {
                        Selector = new V1LabelSelector
                        {
                            MatchLabels = new Dictionary<string, string>
                            {
                                ["app"] = appName,
                            }
                        },
                        Replicas = replicas,
                        Template = new V1PodTemplateSpec
                        {
                            Metadata = new V1ObjectMeta
                            {
                                Labels = new Dictionary<string, string> { ["app"] = appName }
                            },
                            Spec = new V1PodSpec { 
                            Containers = containers,
                            Volumes = new V1Volume[] {
                            new V1Volume{ 
                            Name = $"os{userId}",// # 卷名字
                            HostPath = new V1HostPathVolumeSource{ 
                            Path = $"/data/os/{userId}",//# 节点上的路径
                            Type = "DirectoryOrCreate",//# 指向一个目录,不存在时自动创建
                            }
                            }
                            }
                            },
                            

                        },
                       
                    }
                    
                };

                 initialDeployment = client.CreateNamespacedDeployment(deployment, deploymentNamespace);
            }
            catch (Exception ex) { 
            Console.WriteLine(ex.Message);
            }
            // Re-fetch Deployment state so we pick up annotations added by the controller.
            // initialDeployment = await client.DeploymentsV1().Get(initialDeployment.Metadata.Name, initialDeployment.Metadata.Namespace);

            return initialDeployment;
        }

c# 创建服务

 private async Task<V1Service> CreateInitialServer(Kubernetes client,string Namespace, string servername, string appName, int nodePort, NodePortType type) {

            try
            {
                V1Service v1Service = new V1Service();
                if (type == NodePortType.NodePort) { 
                    v1Service = new V1Service()
                    {
                        ApiVersion = "v1",
                        Kind = "Service",
                        Metadata = new V1ObjectMeta { 
                            Name =$"{appName}-svc",
                                Labels = new Dictionary<string, string>
                                {
                                    ["app"] = appName
                                }
                        },
                        Spec = new V1ServiceSpec {
                            Selector = new Dictionary<string, string>
                            {
                                ["app"] = appName
                            },
                            Ports = new V1ServicePort[] { new V1ServicePort { 
                            Name = $"{servername}-ports",
                            Protocol = "TCP",
                            Port = 80,
                            NodePort = nodePort,
                            TargetPort = 80,
                            } },
                            Type = "NodePort"
                        },
                    };

                }
                var createService = client.CreateNamespacedService(v1Service, Namespace);
                return createService;
            }
            catch (Exception ex)
            {

                Console.WriteLine($"CreateInitialServer:{ex.Message}");
                throw;
            }
        
        }

c# 将控制器摧毁

 public async Task<string> PodPending(string deploymentName) {
            V1DeploymentList DeploymentclientList = client.ListNamespacedDeployment("default");
            try
            {
                client.DeleteNamespacedDeployment(deploymentName, "default");
            }
            catch(Exception ex) {
                Console.WriteLine($"{ex.Message}");
                return ex.Message;
            }

                    return "ok";
        }

c# 将控制器重启

从新创建控制器即可

借鉴资源

https://blog.csdn.net/qq_46470349/article/details/120911842
https://cloud.tencent.com/developer/article/1454819
https://blog.csdn.net/yemuxiaweiliang/article/details/107147917

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐