首页 > 其他分享 >204 K8S API资源对象介绍03 (Job CronJob Endpoint ConfigMap Secret) 2.12-2.16

204 K8S API资源对象介绍03 (Job CronJob Endpoint ConfigMap Secret) 2.12-2.16

时间:2023-10-18 20:35:10浏览次数:44  
标签:03 CronJob Endpoint name kubectl Completed yaml job sleep

一、API资源对象Job

一次性运行后就退出的Pod

1.1 使用kubect生成YAML文件

# kubectl  create job job01 --image=busybox --dry-run=client -o yaml >job01.yaml
# vim job01.yaml 
# cat job01.yaml 
apiVersion: batch/v1
kind: Job
metadata:
  creationTimestamp: null
  name: job01
spec:
  template:
    metadata:
      creationTimestamp: null
    spec:
      containers:
      - image: busybox
        name: job01
        comand: ["/bin/echo"]
        args: ["Kubernetes","k8s!"]
      restartPolicy: OnFailure

1,.2 创建Job

# kubectl apply -f job01.yaml 
job.batch/job01 created

1.3 查看Job

# kubectl get job,pod

改容器运行完成后状态变成Completed。

对于Job,还有几个特殊字段:

  • activeDeadlineSecond,设置Pod运行的超时时间。
  • backoffLimit,设置Pod的失败重试次数。
  • completions,Job完成需要运行多少个Pod,默认是1个。
  • parallelism,它与completions相关,表示允许并发运行的Pod数量,避免过多占用资源。

 vim myjob.yaml 

apiVersion: batch/v1
kind: Job
metadata:
  name: sleep-job
spec:
  activeDeadlineSeconds: 60
  backoffLimit: 2
  completions: 4
  parallelism: 2

  template:
    spec:
      containers:
      - image: busybox
        name: echo-job
        imagePullPolicy: IfNotPresent
        command: 
          - sh
          - -c
          - sleep 10;echo done
      restartPolicy: Never

创建Job,并查看job情况

# kubectl  apply -f myjob.yaml ;kubectl  get pod -w

activeDeadlineSeconds: 15  15s就超时,completions要求运行的4个Pod没有执行完。修改为60s后再次运行

# kubectl  apply -f myjob.yaml ;kubectl  get pod -w
kubectl apply -f myjob.yaml ;kubectl get pod -w
 # kubectl  apply -f myjob.yaml ;kubectl  get pod -w
job.batch/sleep-job created
NAME                         READY   STATUS              RESTARTS      AGE
ds-demo-57qcd                1/1     Running             1 (78m ago)   23h
ds-demo-jzlpn                1/1     Running             1 (77m ago)   23h
ds-demo-m8cmz                1/1     Running             1 (77m ago)   23h
ds-demo-sfqnt                1/1     Running             1 (79m ago)   23h
job01-8zngs                  0/1     Completed           0             24m
ng-deploy-7b7ff4f9bc-d2g65   1/1     Running             1 (77m ago)   23h
ng-deploy-7b7ff4f9bc-s27c9   1/1     Running             1 (78m ago)   23h
nginxdp-7cf46d7445-8x6gs     1/1     Running             2 (77m ago)   2d11h
redis-sts-0                  1/1     Running             0             64m
redis-sts-1                  1/1     Running             0             72m
sleep-job-2gxtt              0/1     ContainerCreating   0             1s
sleep-job-bkltt              0/1     ContainerCreating   0             1s
testpod                      1/1     Running             2 (78m ago)   2d
sleep-job-bkltt              0/1     ContainerCreating   0             1s
sleep-job-2gxtt              0/1     ContainerCreating   0             1s
sleep-job-2gxtt              1/1     Running             0             2s
sleep-job-bkltt              1/1     Running             0             2s
sleep-job-2gxtt              0/1     Completed           0             12s
sleep-job-bkltt              0/1     Completed           0             12s
sleep-job-2gxtt              0/1     Completed           0             13s
sleep-job-2gxtt              0/1     Completed           0             13s
sleep-job-bkltt              0/1     Completed           0             13s
sleep-job-bkltt              0/1     Completed           0             13s
sleep-job-2gxtt              0/1     Completed           0             14s
sleep-job-drplf              0/1     Pending             0             0s
sleep-job-drplf              0/1     Pending             0             0s
sleep-job-8mk7v              0/1     Pending             0             0s
sleep-job-8mk7v              0/1     Pending             0             0s
sleep-job-drplf              0/1     ContainerCreating   0             0s
sleep-job-8mk7v              0/1     ContainerCreating   0             0s
sleep-job-2gxtt              0/1     Completed           0             14s
sleep-job-bkltt              0/1     Completed           0             14s
sleep-job-bkltt              0/1     Completed           0             14s
sleep-job-drplf              0/1     ContainerCreating   0             0s
sleep-job-8mk7v              0/1     ContainerCreating   0             0s
sleep-job-drplf              1/1     Running             0             1s
sleep-job-8mk7v              1/1     Running             0             1s
sleep-job-drplf              0/1     Completed           0             11s
sleep-job-8mk7v              0/1     Completed           0             11s
sleep-job-drplf              0/1     Completed           0             12s
sleep-job-drplf              0/1     Completed           0             12s
sleep-job-8mk7v              0/1     Completed           0             12s
sleep-job-8mk7v              0/1     Completed           0             12s
sleep-job-drplf              0/1     Completed           0             13s
sleep-job-8mk7v              0/1     Completed           0             13s
sleep-job-drplf              0/1     Completed           0             13s
sleep-job-8mk7v              0/1     Completed           0             13s

 

二、API资源对象CronJob

CronJob简称(cj)是一种周期运行的Pod,比如有些任务每天执行一次

使用kubectl生成YAML文件

# kubectl create cj cj01 --image=busybox --schedule="" --dry-run=client -o yaml >cj01.yaml

vim cj01.yaml 编辑配置文件

apiVersion: batch/v1
kind: CronJob
metadata:
  name: cj01
spec:
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - image: busybox
            name: cj01
            imagePullPolicy: IfNotPresent
            command: ["/bin/echo"]
            args: ["hello","kubernetes!"]
          restartPolicy: OnFailure
  schedule: "*/1 * * * *"

运行并查看

# kubectl apply -f cj01.yaml 
cronjob.batch/cj01 created
# kubectl get cj
NAME   SCHEDULE      SUSPEND   ACTIVE   LAST SCHEDULE   AGE
cj01   */1 * * * *   False     0        <none>          9s

三、API 资源对象Endpoint

Endpoint(简称ep)资源是和Service一一对应,每个Service都会对应一个Endpoint

# kubectl get ep
NAME         ENDPOINTS                              AGE
kubernetes   192.168.1.230:6443                     19d
nginxsvc     10.244.154.26:80                       2d12h
ngx-svc      10.244.154.25:80,10.244.167.163:80     24h
redis-svc    10.244.154.28:6379,10.244.29.45:6379   22h
# kubectl get  svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP        19d
nginxsvc     NodePort    10.102.250.93    <none>        80:31681/TCP   2d12h
ngx-svc      ClusterIP   10.97.206.107    <none>        8080/TCP       24h
redis-svc    ClusterIP   10.110.151.202   <none>        6379/TCP       22h

Endpoint 可以理解为Service后端对应的资源。

如果k8s里的Pod需要访问外部资源,比如访问外部MySQL服务,可以定义一个对外资源的Endpoint,然后再定义一个Service,这样k8s里面的其他Pod可以访问mysql服务。

vim testep.yaml

apiVersion: v1
kind: Endpoints
metadata:
  name: external-mysql
subsets:
  - addresses:
    - ip: 192.168.1.230
    ports:
      - port: 3306

---
apiVersion: v1
kind: Service  ##注意,该service里并不需要定义selector,只要Service name和Endpoint name保持一致即可
metadata:
  name: external-mysql
spec:
  ports:
    - port: 3306

应用YAML文件

# kubectl  apply -f testep.yaml 
endpoints/external-mysql created
service/external-mysql created

测试

# kubectl  get ep
NAME             ENDPOINTS                              AGE
external-mysql   192.168.1.230:3306                     22s
kubernetes       192.168.1.230:6443                     19d
nginxsvc         10.244.154.26:80                       2d12h
ngx-svc          10.244.154.25:80,10.244.167.163:80     24h
redis-svc        10.244.154.28:6379,10.244.29.45:6379   22h
# kubectl  get svc
NAME             TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
external-mysql   ClusterIP   10.109.90.174    <none>        3306/TCP       26s
kubernetes       ClusterIP   10.96.0.1        <none>        443/TCP        19d
nginxsvc         NodePort    10.102.250.93    <none>        80:31681/TCP   2d12h
ngx-svc          ClusterIP   10.97.206.107    <none>        8080/TCP       24h
redis-svc        ClusterIP   10.110.151.202   <none>        6379/TCP       22h

进入testpod 安装mysql 客户端命令,访问mysql

验证见第四节。

四、API资源对象ConfigMap

ConfigMap(简称cm)用来存储配置信息,比如服务端口、运行参数、文件路径等。

4.1 YAML示例

apiVersion: v1
kind: ConfigMap
metadata:
  name: mycm
data:
  DATABASE: 'db'
  USER: 'wp'
  PASSWORD: '12345678'
  ROOT_PASSWORD: '12345678'
  HOST: 'external-mysql'

创建cm

# kubectl apply -f mycm.yaml 
configmap/mycm unchanged

查看

# kubectl  get cm
NAME               DATA   AGE
kube-root-ca.crt   1      19d
mycm               5      2d1h
# # kubectl   describe cm mycm
Name:         mycm
Namespace:    default
Labels:       <none>
Annotations:  <none>

Data
====
DATABASE:
----
k8s
HOST:
----
external-mysql
PASSWORD:
----
12345678
ROOT_PASSWORD:
----
12345678
USER:
----
root

BinaryData
====

Events:  <none>

 4.2 在其他Pod引用ConfigMap

vi  testpod.yaml

# cat testpod.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: testpod
  labels:
    app: testpod

spec:
  containers:
  - image: mariadb:10
    name: maria1
    imagePullPolicy: IfNotPresent
    command: [ "/bin/bash", "-ce", "tail -f /dev/null" ]
    ports:
    - containerPort: 3306

    envFrom:   ##将cm里的字段全部导入该pod
    - prefix: 'MARIADB_'  ##将导入的字段名前面自动加上前缀,例如MARIADB_DATABASE, MARIADB_USER
      configMapRef:  ##定义哪个cm
        name: mycm

4.3 验证:

# kubectl exec -it testpod -- bash
# echo $MARIADB_PASSWORD
12345678
# echo $MARIADB_HOST
external-mysql
# echo $MARIADB_DATABASE
k8s
# mysql -u$MARIADB_USER -p$MARIADB_PASSWORD -h$MARIADB_HOST 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 7
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| k8s                |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.001 sec)

五、API资源对象Secret

Secret 和cm的结构和用法很类似,比如:

  • 访问私有镜像仓库的认证信息
  • 身份识别的凭证信息
  • HTTPS通信的证书和私钥
  • 一般的机密信息

5.1 YAML示例

vim mysecret.yaml

# cat mysecret.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: mysecret

data:
  host: ZXh0ZXJuYWwtbXlzcWw=    #echo -n "external-mysql"|base64
  user: cm9vdA==   # echo -n "root"|base64
  passwd: MTIzNDU2Nzg= ## echo -n "12345678"|base64

查看

# kubectl  apply  -f mysecret.yaml 
secret/mysecret created
# kubectl  get secret
NAME       TYPE     DATA   AGE
mysecret   Opaque   3      33s
# kubectl  describe secret mysecret
Name:         mysecret
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
user:    4 bytes
host:    14 bytes
passwd:  8 bytes

5.2 在Pod引用Secret

vi testpod2.yaml

apiVersion: v1
kind: Pod
metadata:
  name: testpod3

spec:
  containers:
  - image: mariadb:10
    name: maria3
    imagePullPolicy: IfNotPresent
    command: ["/bin/sleep", "300"]

    env:
      - name: USERNAME
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: user
      - name: PASSWORD
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: passwd
	  - name: HOST
        valueFrom:
          secretKeyRef:
            name: mysecret
            key: host

 5.3 验证:

# kubectl  apply -f testpod3.yaml 
pod/testpod3 unchanged
[root@master-1-230 2.16]# kubectl  exec -it testpod3 -- bash
root@testpod3:/# echo $HOST
external-mysql
root@testpod3:/# echo $USERNAME
root
root@testpod3:/# echo $PASSWORD
12345678
root@testpod3:/# mysql -u$USERNAME -p$PASSWORD  -h$HOST
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 9
Server version: 5.5.68-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> show databasses;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'databasses' at line 1
MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| k8s                |
| mysql              |
| performance_schema |
| test               |
+--------------------+
5 rows in set (0.001 sec)

标签:03,CronJob,Endpoint,name,kubectl,Completed,yaml,job,sleep
From: https://www.cnblogs.com/pythonlx/p/17768315.html

相关文章

  • 90V转12伏恒压芯片WT6037
     WT6037是一款高压同步降压转换器,可在10V到90V的宽输入电压范围内工作适用于宽电压输入12V-72V电池组系统降压和60V-90V降压应用。WT6037可提供4A连续负载电流,转换效率高达92%。  WT6037采用具有内置补偿的固定频率峰值电流控制,无需外部组件。高侧MOSFET中的逐周期电流限制......
  • vue进行跳转之后出现Cannot read properties of undefined (reading 'router') TypeEr
    问题描述使用router进行页面跳转时,就出现了这样的问题:也就是这里出现了问题:问题解决本来是按照网上的教程:const_this=this;但是,但是,我本来就是用的这种方法呀~然后就打算直接在这个界面引用:importrouterfrom'@/router'router.push('/one');里面引用的跳转页面......
  • [914] In Python's datetime library, you can format dates using the strftime() me
    InPython'sdatetimelibrary,youcanformatdatesusingthestrftime()method.Thismethodallowsyoutocreateaformattedstringrepresentationofadatetimeobject,specifyingtheformatyouwant.Here'showyoucanformatadateusingstrft......
  • Cocos Creator 2D/3D基础/ 第003节3D模型的基本概念
    3.1计算机如何制作一个3D模型 讲述这个问题之前,我们先来看下现实生活中我们要做一个模型,应该如何做呢?首先我们要把模型的形状给雕刻构建出来,现实生活中的物体都是由分子组成的连续的表面,计算机是离散的无法做到这点,所以计算机通过微分的方式,把一个曲面分成”多个平面”来模拟......
  • Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregate
    这个报错的完整信息Expression#3ofSELECTlistisnotinGROUPBYclauseandcontainsnonaggregatedcolumn'jira.ji.ID'whichisnotfunctionallydependentoncolumnsinGROUPBYclause;thisisincompatiblewithsql_mode=only_full_group_by这个说的意......
  • Program does not contain a static 'Main' method suitable for an entry point
    http://www.kangry.net/blog/?article_id=391&type=article修改办法,对着项目右键-》属性-》application-》outputtype设为ClassLibrary即可。  ......
  • Plugin 'org.springframework.boot:spring-boot-maven-plugin:' not found
    Plugin'org.springframework.boot:spring-boot-maven-plugin:'notfound 一、问题现象pom.xml文件中有报红的错误提示,“Plugin'org.springframework.boot:spring-boot-maven-plugin:'notfound”。pom.xml中的信息如下:<build><plugins>......
  • 18_常用命令03
    1.字符串包含子串#使用方法1[root@vm1zk]#[["aaabb"=~"bb"]]&&echo"包含"||echo"不包含"包含[root@vm1zk]#[root@vm1zk]#[["aaab"=~"bb"]]&&echo"包含"||echo"不包含&q......
  • python报错解决-ValueError: Trusted host URL must include a host part: '#!
    删掉#后面的字符参考:pipinstall总是报错:ValueError:TrustedhostURLmustincludeahostpart:‘#‘-CSDN博客......
  • ModuleNotFoundError: No module named 'conda.auxlib'
    [~/software]$condaTraceback(mostrecentcalllast): File"/ppp/software/Anaconda3.8/bin/conda",line15,in<module>   sys.exit(main()) File"/ppp/software/Anaconda3.8/lib/python3.8/site-packages/conda/cli/main.py",line11......