k8s简单使用

警告
本文最后更新于 2022-07-01,文中内容可能已过时。

摘要

  • Pod
  • Node
  • Namespace
  • Service
  • Volume
  • PersistentVolume
  • Deployment
  • Secret
  • StatefulSet
  • DaemonSet
  • ServiceAccount
  • ReplicationController
  • ReplicaSet
  • Job
  • CronJob
  • SecurityContext
  • ResourceQuota
  • LimitRange
  • HorizontalPodAutoscaling
  • Ingress
  • ConfigMap
  • Label
  • CustomResourceDefinition
  • Role
  • ClusterRole

我将它们简单的分类为以下几种资源对象:

类别名称
资源对象Pod、ReplicaSet、ReplicationController、Deployment、StatefulSet、DaemonSet、Job、CronJob、HorizontalPodAutoscaling、Node、Namespace、Service、Ingress、Label、CustomResourceDefinition
存储对象Volume、PersistentVolume、Secret、ConfigMap
策略对象SecurityContext、ResourceQuota、LimitRange
身份对象ServiceAccount、Role、ClusterRole

kubectl get 类似于 docker ps ,查询资源列表

kubectl describe 类似于 docker inspect ,获取资源的详细信息

kubectl logs 类似于 docker logs ,获取容器的日志

kubectl exec 类似于 docker exec ,在容器内执行一个命令

用k8s跑一个nginx

创建一个nginx.yaml文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
apiVersion: apps/v1 # apiVersion:语法关键字,注意大小写。apps/v1:版本标签
kind: Deployment # 资源类型:deployment控制器
metadata: # 资源的元数据
  name: nginx-deployment # 资源名称,在同一个namespace中必须唯一
  labels: # 定义资源的标签
    app: nginx
spec: # 定义容器模板
  replicas: 2 # 定义副本数量
  selector: # 选择器
    matchLabels: # 匹配标签
      app: nginx # 匹配模板名称
  template: # 模板
    metadata:
      labels:
        app: nginx
    spec:
      containers: # 定义容器信息
      - name: nginx # -:表示参数,容器名与标签名要相同
        image: nginx:latest # 容器使用的镜像以及版本
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service # 类型
metadata: # 元数据
  name: nginx-service # 名称
  labels: # 标签
    app: nginx
spec:
  type: NodePort # 发布的类型:NodePort
  ports:
  - port: 80 # 内部端口
    targetPort: 80  # 映射指向的端口
    nodePort: 30080 # 对外端口
  selector:  # 选择器
    app: nginx

创建资源

1
kubectl create -f nginx.yaml

查看pods

1
kubectl get pods

查看svc

1
kubectl get svc

创建一个redis

创建redis.yaml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
apiVersion: apps/v1
kind: Deployment
metadata:
  name: redis
  labels:
    name: redis
spec:
  replicas: 2
  selector:
    matchLabels:
      name: redis
  template:
    metadata:
      labels:
        name: redis
    spec:
      containers:
      - name: redis
        image: redis
        ports:
        - containerPort: 6379
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  labels:
    name: redis
spec:
  type: NodePort # 发布的类型:NodePort
  ports:
  - port: 6379
    targetPort: 6379
  selector:
    name: redis

相关内容