K8s实战入门(三)

文章目录

      • [3. 实战入门](#3. 实战入门)
        • [3.1 Namespace](#3.1 Namespace)
          • [3.1.1 测试两个不同的名称空间之间的 Pod 是否连通性](#3.1.1 测试两个不同的名称空间之间的 Pod 是否连通性)
        • [3.2 Pod](#3.2 Pod)
        • [3.3 Label](#3.3 Label)
        • [3.4 Deployment](#3.4 Deployment)
        • [3.5 Service](#3.5 Service)

3. 实战入门

本章节将介绍如何在kubernetes集群中部署一个nginx服务,并且能够对其进行访问。

3.1 Namespace

Namespace是kubernetes系统中的一种非常重要资源,它的主要作用是用来实现多套环境的资源隔离 或者多租户的资源隔离

默认情况下,kubernetes集群中的所有的Pod都是可以相互访问的。但是在实际中,可能不想让两个Pod之间进行互相的访问,那此时就可以将两个Pod划分到不同的namespace下。kubernetes通过将集群内部的资源分配到不同的Namespace中,可以形成逻辑上的"组",以方便不同的组的资源进行隔离使用和管理。

可以通过kubernetes的授权机制,将不同的namespace交给不同租户进行管理,这样就实现了多租户的资源隔离。此时还能结合kubernetes的资源配额机制,限定不同租户能占用的资源,例如CPU使用量、内存使用量等等,来实现租户可用资源的管理。


3.1.1 测试两个不同的名称空间之间的 Pod 是否连通性
elixir 复制代码
[root@k8s-master ~]# mkdir manifest
[root@k8s-master ~]# cd manifest
[root@k8s-master manifest]# pwd
/root/manifest
[root@k8s-master manifest]# cat nginx-pod.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: dev

---

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  namespace: dev
spec:
  containers:
  - name: nginx-containers
    image: busybox:latest
    command: ["/bin/sleep","6000"]

---

apiVersion: v1
kind: Pod
metadata:
  name: apache  # 不指定名称空间就是跑在默认的
spec:
  containers:
  - name: httpd
    image: busybox:latest
    command: ["/bin/sleep","6000"]
    
[root@k8s-master manifest]# kubectl  get -n default pod
NAME     READY   STATUS    RESTARTS   AGE
apache   1/1     Running   0          19s
[root@k8s-master manifest]# kubectl  get -n dev  pod
NAME        READY   STATUS    RESTARTS   AGE
nginx-pod   1/1     Running   0          25s    

# 进入 Pod 的 apache
[root@k8s-master manifest]# kubectl exec apache -it -- sh
/ # ls
bin    dev    etc    home   lib    lib64  proc   root   sys    tmp    usr    var
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue 
    link/ether 5e:19:37:e6:3e:5a brd ff:ff:ff:ff:ff:ff
    inet 10.244.2.12/24 brd 10.244.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::5c19:37ff:fee6:3e5a/64 scope link 
       valid_lft forever preferred_lft forever
/ #

# 进入 Pod 的nginx-pod
[root@k8s-master manifest]# kubectl exec nginx-pod -i -t -n dev -- sh
/ # 
/ # ls
bin    dev    etc    home   lib    lib64  proc   root   sys    tmp    usr    var
/ # ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0@if7: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue 
    link/ether 66:d3:72:81:17:00 brd ff:ff:ff:ff:ff:ff
    inet 10.244.1.16/24 brd 10.244.1.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::64d3:72ff:fe81:1700/64 scope link 
       valid_lft forever preferred_lft forever
/ # ping 10.244.2.12
PING 10.244.2.12 (10.244.2.12): 56 data bytes
64 bytes from 10.244.2.12: seq=0 ttl=62 time=1.170 ms
64 bytes from 10.244.2.12: seq=1 ttl=62 time=0.397 ms
64 bytes from 10.244.2.12: seq=2 ttl=62 time=0.743 ms

kubernetes在集群启动之后,会默认创建几个 namespace

shell 复制代码
[root@k8s-master ~]#  kubectl  get namespace
NAME              STATUS   AGE
default           Active   45h     #  所有未指定Namespace的对象都会被分配在default命名空间
kube-node-lease   Active   45h     #  集群节点之间的心跳维护,v1.13开始引入
kube-public       Active   45h     #  此命名空间下的资源可以被所有人访问(包括未认证用户)
kube-system       Active   45h     #  所有由Kubernetes系统创建的资源都处于这个命名空间

下面来看namespace资源的具体操作:

**查看 **

shell 复制代码
# 1 查看所有的ns  命令:kubectl get ns
[root@k8s-master ~]#  kubectl get ns
NAME              STATUS   AGE
default           Active   45h
kube-node-lease   Active   45h
kube-public       Active   45h     
kube-system       Active   45h     

# 2 查看指定的ns   命令:kubectl get ns ns名称
[root@k8s-master ~]#  kubectl get ns default
NAME      STATUS   AGE
default   Active   45h

# 3 指定输出格式  命令:kubectl get ns ns名称  -o 格式参数
# kubernetes支持的格式有很多,比较常见的是wide、json、yaml
[root@k8s-master ~]# kubectl get ns default -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2023-01-08T02:04:00Z"
  labels:
    kubernetes.io/metadata.name: default
  name: default
  resourceVersion: "191"
  uid: ed84973a-29b4-4286-ae46-d8df5c113334
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@k8s-master ~]# 
  
# 4 查看ns详情  命令:kubectl describe ns ns名称
[root@k8s-master ~]# kubectl describe ns default 或  kubectl describe pod apache
Name:         default
Labels:       kubernetes.io/metadata.name=default
Annotations:  <none>
Status:       Active  # Active 命名空间正在使用中  Terminating 正在删除命名空间
                       
No resource quota. # Resource Quota 针对namespace做的资源限制

No LimitRange resource.  # LimitRange针对namespace中的每个组件做的资源限制 


[root@k8s-master inventory]# pwd
/root/inventory
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl describe pod apache
Name:             apache  // Pod 名字
Namespace:        default  // 在那个名称空间运行
Priority:         0
Service Account:  default
Node:             k8s-node1/192.168.192.4  // 在那台node节点上运行
Start Time:       Fri, 28 Jul 2023 13:23:17 +0800  // 启动时间
Labels:           <none>
Annotations:      <none>
Status:           Running  //  现在的状态是Runing
IP:               10.244.1.15  // IP 地址
IPs:
  IP:  10.244.1.15
Containers:
  httpd:
    Container ID:   containerd://b7eeb63f0cb390657ad84dd42aa42acd74d56088e17a48b04b1633e1e12ab57a
    Image:          httpd  // 运行那个镜像名
    Image ID:  // 镜像ID     docker.io/library/httpd@sha256:33a91a69517f0642b3e8be5cc8d12f8c1ae245728a83947bfc098376be63c15e
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Fri, 28 Jul 2023 13:25:14 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-xmsjx (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-xmsjx:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:                      <none>
[root@k8s-master inventory]# 

创建

shell 复制代码
# 创建namespace(创建名称空间)
[root@k8s-master ~]#  kubectl create ns dev
namespace/dev created

删除

shell 复制代码
# 删除namespace(创建名称空间)
[root@k8s-master ~]#  kubectl delete ns dev
namespace "dev" deleted

配置方式

首先准备一个yaml文件:ns-dev.yaml

yaml 复制代码
# 创建一个最简单的名称空间
apiVersion: v1
kind: Namespace
metadata:
  name: dev

然后就可以执行对应的创建和删除命令了:

创建:kubectl create -f ns-dev.yaml

删除:kubectl delete -f ns-dev.yaml

3.2 Pod

Pod是kubernetes集群进行管理的最小单元,程序要运行必须部署在容器中,而容器必须存在于Pod中。

Pod可以认为是容器的封装,一个Pod中可以存在一个或者多个容器。


测试一个 Pod 跑多个容器

shell 复制代码
[root@k8s-master manifest]# cat testpodrun.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
spec:
  containers:
  - name: nginx-containers
    image: httpd:latest
  - name: nginx
    image: nginx:latest
    
[root@k8s-master inventory]# kubectl apply -f test_pod_run.yaml 
pod/nginx-pod created

[root@k8s-master ~]# kubectl get pod nginx-pod
NAME        READY   STATUS             RESTARTS        AGE
nginx-pod   1/2     CrashLoopBackOff   6 (3m49s ago)   10m
# 使用describe 命令查看nginx-pod 在做些什么事
[root@k8s-master manifest]# kubectl describe pod nginx-pod

kubernetes在集群启动之后,集群中的各个组件也都是以Pod方式运行的。可以通过下面命令查看:

shell 复制代码
[root@k8s-master ~]#  kubectl get pod -n kube-system
NAMESPACE     NAME                             READY   STATUS    RESTARTS   AGE
kube-system   coredns-6955765f44-68g6v         1/1     Running   0          2d1h
kube-system   coredns-6955765f44-cs5r8         1/1     Running   0          2d1h
kube-system   etcd-master                      1/1     Running   0          2d1h
kube-system   kube-apiserver-master            1/1     Running   0          2d1h
kube-system   kube-controller-manager-master   1/1     Running   0          2d1h
kube-system   kube-flannel-ds-amd64-47r25      1/1     Running   0          2d1h
kube-system   kube-flannel-ds-amd64-ls5lh      1/1     Running   0          2d1h
kube-system   kube-proxy-685tk                 1/1     Running   0          2d1h
kube-system   kube-proxy-87spt                 1/1     Running   0          2d1h
kube-system   kube-scheduler-master            1/1     Running   0          2d1h

创建并运行

kubernetes没有提供单独运行Pod的命令,都是通过Pod控制器来实现的

shell 复制代码
# 命令格式: kubectl run (pod控制器名称) [参数] 
# --image  指定Pod的镜像
# --port   指定端口
# --namespace  指定namespace
[root@k8s-master ~]# kubectl create namespace dev
namespace/dev created
[root@k8s-master ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   204d
dev               Active   7s
kube-flannel      Active   204d
kube-node-lease   Active   204d
kube-public       Active   204d
kube-system       Active   204d
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl run nginx --image=nginx:latest --port=80 --namespace dev
pod/nginx created

查看pod信息

shell 复制代码
# 查看Pod基本信息
[root@k8s-master ~]# kubectl get pods -n dev
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          29s


# 查看Pod的详细信息
[root@k8s-master ~]# kubectl describe pod nginx -n dev
Name:             nginx  // Pod 名字
Namespace:        dev  // 名称空间名字
Priority:         0
Service Account:  default
Node:             k8s-node1/192.168.192.4
Start Time:       Mon, 31 Jul 2023 15:21:53 +0800
Labels:           run=nginx
Annotations:      <none>
Status:           Running  // 表示在运行
IP:               10.244.1.18
IPs:
  IP:  10.244.1.18
Containers:
  nginx:
    Container ID:   containerd://a9607020f2f7170b104af0f35ec36f3b0f740a1abe9b5c543b114f145b6e0494
    Image:          nginx:latest
    Image ID:       docker.io/library/nginx@sha256:67f9a4f10d147a6e04629340e6493c9703300ca23a2f7f3aa56fe615d75d31ca
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Mon, 31 Jul 2023 15:21:56 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-726tm (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-726tm:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  2m    default-scheduler  Successfully assigned dev/nginx to k8s-node1
  Normal  Pulling    119s  kubelet            Pulling image "nginx:latest"
  Normal  Pulled     117s  kubelet            Successfully pulled image "nginx:latest" in 2.32545784s (2.325463331s including waiting)
  Normal  Created    117s  kubelet            Created container nginx
  Normal  Started    117s  kubelet            Started container nginx
[root@k8s-master ~]# 

访问Pod

shell 复制代码
# 获取podIP
[root@k8s-master ~]# kubectl get pods -n dev -o wide
NAME    READY   STATUS    RESTARTS   AGE     IP            NODE        NOMINATED NODE   READINESS GATES
nginx   1/1     Running   0          3m38s   10.244.1.18   k8s-node1   <none>           <none>
[root@k8s-master ~]#
#访问POD
[root@k8s-master ~]# curl 10.244.1.18
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@k8s-master ~]# 

删除指定Pod

shell 复制代码
[root@k8s-master ~]# kubectl delete pod nginx -n dev  // 删除Pod 
pod "nginx" deleted
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl get pods -n dev 
No resources found in dev namespace.
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   204d
dev               Active   6m12s
kube-flannel      Active   204d
kube-node-lease   Active   204d
kube-public       Active   204d
kube-system       Active   204d
[root@k8s-master ~]# 

[root@k8s-master ~]# kubectl delete namespace dev  // 删除名称空间
namespace "dev" deleted
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   204d
kube-flannel      Active   204d
kube-node-lease   Active   204d
kube-public       Active   204d
kube-system       Active   204d
[root@k8s-master ~]# 

配置操作

创建一个pod-nginx.yaml,内容如下:

yaml 复制代码
[root@k8s-master inventory]# pwd
/root/inventory
[root@k8s-master inventory]# cat pod-nginx.yaml 
apiVersion: v1
kind: Namespace
metadata:
  name: dev
---
apiVersion: v1
kind: Pod
metadata:
  name: nginx
  namespace: dev
spec:
  containers:
  - image: nginx:latest
    name: pod
    ports:
    - name: nginx-port
      containerPort: 80
      protocol: TCP
[root@k8s-master inventory]# 

[root@k8s-master inventory]# kubectl apply -f pod-nginx.yaml 
namespace/dev created
pod/nginx created
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl get pod -n dev
NAME    READY   STATUS    RESTARTS   AGE
nginx   1/1     Running   0          14s
[root@k8s-master inventory]# 

[root@k8s-master inventory]# kubectl get -f pod-nginx.yaml 
NAME            STATUS   AGE
namespace/dev   Active   6m47s

NAME        READY   STATUS    RESTARTS   AGE
pod/nginx   1/1     Running   0          6m47s
[root@k8s-master inventory]# 

然后就可以执行对应的创建和删除命令了:

创建:kubectl create -f pod-nginx.yaml

删除:kubectl delete -f pod-nginx.yaml

3.3 Label

Label是kubernetes系统中的一个重要概念。它的作用就是在资源上添加标识,用来对它们进行区分和选择。

Label的特点:

  • 一个Label会以key/value键值对的形式附加到各种对象上,如Node、Pod、Service等等
  • 一个资源对象可以定义任意数量的Label ,同一个Label也可以被添加到任意数量的资源对象上去
  • Label通常在资源对象定义时确定,当然也可以在对象创建后动态添加或者删除

可以通过Label实现资源的多维度分组,以便灵活、方便地进行资源分配、调度、配置、部署等管理工作。

一些常用的Label 示例如下:

  • 版本标签:"version":"release", "version":"stable"...
  • 环境标签:"environment":"dev","environment":"test","environment":"prod"
  • 架构标签:"tier":"frontend","tier":"backend"

标签定义完毕之后,还要考虑到标签的选择,这就要使用到Label Selector,即:

Label用于给某个资源对象定义标识

Label Selector用于查询和筛选拥有某些标签的资源对象

当前有两种Label Selector:

  • 基于等式的Label Selector

    name = slave: 选择所有包含Label中key="name"且value="slave"的对象

    env != production: 选择所有包括Label中的key="env"且value不等于"production"的对象

  • 基于集合的Label Selector

    name in (master, slave): 选择所有包含Label中的key="name"且value="master"或"slave"的对象

    name not in (frontend): 选择所有包含Label中的key="name"且value不等于"frontend"的对象

标签的选择条件可以使用多个,此时将多个Label Selector进行组合,使用逗号","进行分隔即可。例如:

name=slave,env!=production

name not in (frontend),env!=production

命令方式

shell 复制代码
[root@k8s-master ~]# kubectl get pods -n dev  // 查看名称空间dev中有哪些Pod
NAME    READY   STATUS    RESTARTS      AGE
nginx   1/1     Running   1 (39m ago)   4d17h
[root@k8s-master ~]# 

# 1.查看是否已有标签
[root@k8s-master ~]# kubectl describe -n dev pods nginx | grep -i labels
Labels:           <none>
[root@k8s-master ~]# 
# 2.查看是否已有标签
[root@k8s-master ~]# kubectl get pods nginx -n dev --show-labels
NAME    READY   STATUS    RESTARTS      AGE     LABELS
nginx   1/1     Running   1 (42m ago)   4d17h   <none>  // 标签
[root@k8s-master ~]# 


# 为pod资源打标签
[root@k8s-master ~]# kubectl label pod nginx app=test -n dev
pod/nginx labeled

[root@k8s-master ~]# kubectl describe -n dev pod nginx | grep -i labels
Labels:           app=test
[root@k8s-master ~]# 

[root@k8s-master ~]# kubectl label -n dev pod nginx app=test1
error: 'app' already has a value (test), and --overwrite is false
//  需要带 [--overwrite] 不然会报错

# 为pod资源更新标签
[root@k8s-master ~]# kubectl label pod nginx app=test1 -n dev --overwrite
pod/nginx labeled


# 查看标签
[root@k8s-master ~]# kubectl get -n dev pod nginx --show-labels
NAME    READY   STATUS    RESTARTS      AGE     LABELS
nginx   1/1     Running   1 (49m ago)   4d17h   app=test1
[root@k8s-master ~]# 


# 筛选标签
[root@k8s-master ~]# kubectl get -n dev pod  -l app=test1 --show-labels
NAME    READY   STATUS    RESTARTS      AGE     LABELS
nginx   1/1     Running   1 (52m ago)   4d17h   app=test1
[root@k8s-master ~]# 


# 取反
[root@k8s-master ~]# kubectl get pod -n dev -l app!=test1 --show-labels
No resources found in dev namespace.

#删除标签
[root@k8s-master ~]# kubectl label pod nginx -n dev app-
pod/nginx unlabeled
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl get pod nginx -n dev --show-labels
NAME    READY   STATUS    RESTARTS      AGE     LABELS
nginx   1/1     Running   1 (54m ago)   4d17h   <none>
[root@k8s-master ~]# 

配置方式

elixir 复制代码
[root@k8s-master manifest]# cat test.yaml 
apiVersion: v1
kind: Pod
metadata:
  labels:
    version: web
  name: httpd
  namespace: default
spec:
  containers:
  - image: httpd:latest
    imagePullPolicy: IfNotPresent
    name: httpd
    ports:
    - containerPort: 80
      name: httpd-port
      hostPort: 8080
      protocol: TCP

[root@k8s-master manifest]# kubectl apply -f test.yaml 
pod/httpd created
[root@k8s-master manifest]# kubectl get pod httpd --show-labels
NAME    READY   STATUS    RESTARTS   AGE    LABELS
httpd   1/1     Running   0          101s   version=web

然后就可以执行对应的更新命令了:kubectl apply -f pod-nginx.yaml

3.4 Deployment

在kubernetes中,Pod是最小的控制单元,但是kubernetes很少直接控制Pod,一般都是通过Pod控制器来完成的。Pod控制器用于pod的管理,确保pod资源符合预期的状态,当pod的资源出现故障时,会尝试进行重启或重建pod。

在kubernetes中Pod控制器的种类有很多,本章节只介绍一种:Deployment。

命令操作

shell 复制代码
# 命令格式: kubectl create deployment 名称  [参数] 
# --image  指定pod的镜像
# --port   指定端口
# --replicas  指定创建pod数量
# --namespace  指定namespace
[root@k8s-master ~]# kubectl get namespace
NAME              STATUS   AGE
default           Active   209d
dev               Active   4d21h
kube-flannel      Active   209d
kube-node-lease   Active   209d
kube-public       Active   209d
kube-system       Active   209d
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl create namespace test  // 创建一个名称空间
namespace/test created
[root@k8s-master ~]# kubectl get ns test  // 指定查看名称空间
NAME   STATUS   AGE
test   Active   18s
[root@k8s-master ~]# 

# 查看[名称空间test] namespace,以yaml格式展示结果
[root@k8s-master ~]# kubectl get ns test -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2023-08-05T05:34:26Z"
  labels:
    kubernetes.io/metadata.name: test
  name: test
  resourceVersion: "1093635"
  uid: f9ddabdc-d52f-4952-ae39-4fa93cc2751c
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@k8s-master ~]# kubectl get ns test --show-labels
NAME   STATUS   AGE   LABELS
test   Active   23m   kubernetes.io/metadata.name=test
[root@k8s-master ~]# 


[root@k8s-master ~]# kubectl create deployment nginx --image=nginx:latest --port=80 --replicas=4 -n test
deployment.apps/nginx created


# 查看创建的Pod
[root@k8s-master ~]# kubectl get -n test pods
NAME                         READY   STATUS    RESTARTS   AGE
my-deploy-6648745bcc-7ttcf   1/1     Running   0          3m3s
my-deploy-6648745bcc-vm4vg   1/1     Running   0          3m3s
my-deploy-6648745bcc-x87ng   1/1     Running   0          3m3s
[root@k8s-master ~]# 
[root@k8s-master ~]# kubectl get -n test pods -o wide
NAME                         READY   STATUS    RESTARTS   AGE     IP            NODE        NOMINATED NODE   READINESS GATES
my-deploy-6648745bcc-7ttcf   1/1     Running   0          3m38s   10.244.1.22   k8s-node1   <none>           <none>
my-deploy-6648745bcc-vm4vg   1/1     Running   0          3m38s   10.244.2.16   k8s-node2   <none>           <none>
my-deploy-6648745bcc-x87ng   1/1     Running   0          3m38s   10.244.2.15   k8s-node2   <none>           <none>
[root@k8s-master ~]#


# 查看deployment的信息
[root@k8s-master ~]# kubectl get deploy -n test -o wide
NAME        READY   UP-TO-DATE   AVAILABLE   AGE     CONTAINERS   IMAGES         SELECTOR
my-deploy   3/3     3            3           4m38s   nginx        nginx:latest   app=my-deploy
[root@k8s-master ~]# 

# UP-TO-DATE:成功升级的副本数量
# AVAILABLE:可用副本的数量

# 加参数 --show-labels 查看标签
[root@k8s-master ~]# kubectl get deploy -n test --show-labels
NAME        READY   UP-TO-DATE   AVAILABLE   AGE     LABELS
my-deploy   3/3     3            3           5m53s   app=my-deploy

[root@k8s-master ~]# kubectl get pods -n test --show-labels
NAME                         READY   STATUS    RESTARTS   AGE     LABELS
my-deploy-6648745bcc-7ttcf   1/1     Running   0          6m33s   app=my-deploy,pod-template-hash=6648745bcc
my-deploy-6648745bcc-vm4vg   1/1     Running   0          6m33s   app=my-deploy,pod-template-hash=6648745bcc
my-deploy-6648745bcc-x87ng   1/1     Running   0          6m33s   app=my-deploy,pod-template-hash=6648745bcc
[root@k8s-master ~]# 


# 查看deployment的详细信息
[root@k8s-master ~]# kubectl describe deployment my-deploy -n test
Name:                   my-deploy
Namespace:              test
CreationTimestamp:      Sat, 05 Aug 2023 13:42:53 +0800
Labels:                 app=my-deploy
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=my-deploy
Replicas:               3 desired | 3 updated | 3 total | 3 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=my-deploy
  Containers:
   nginx:
    Image:        nginx:latest
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   my-deploy-6648745bcc (3/3 replicas created)
Events:
  Type    Reason             Age    From                   Message
  ----    ------             ----   ----                   -------
  Normal  ScalingReplicaSet  8m58s  deployment-controller  Scaled up replica set my-deploy-6648745bcc to 3
[root@k8s-master ~]# 

# 查看deployment,以yaml 格式展示结果  查看某个pod,以yaml格式展示结果
[root@k8s-master ~]# kubectl get deployment my-deploy -o yaml -n test
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "1"
  creationTimestamp: "2023-08-05T05:42:53Z"
  generation: 1
  labels:
    app: my-deploy
  name: my-deploy
  namespace: test
  resourceVersion: "1094451"
  uid: cf361c04-0c57-46f1-be24-4fc93680c493
spec:
  progressDeadlineSeconds: 600
  replicas: 3
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: my-deploy
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: my-deploy
    spec:
      containers:
      - image: nginx:latest
        imagePullPolicy: Always
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 3
  conditions:
  - lastTransitionTime: "2023-08-05T05:43:00Z"
    lastUpdateTime: "2023-08-05T05:43:00Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2023-08-05T05:42:53Z"
    lastUpdateTime: "2023-08-05T05:43:00Z"
    message: ReplicaSet "my-deploy-6648745bcc" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 1
  readyReplicas: 3
  replicas: 3
  updatedReplicas: 3
[root@k8s-master ~]# 
//  如果要写yaml格式的创建名称空间[namespace]或者是deployment、pod的都是可以手动先创建出来然后执行[kubectl get pod pod_name -o yaml]展示出来后,可以照着展示出来的内容写。

# 删除 
[root@k8s-master ~]# kubectl delete -n test deployment my-deploy
deployment.apps "my-deploy" deleted
[root@k8s-master ~]# 

配置操作

创建一个deploy-nginx.yaml,内容如下:

shell 复制代码
[root@k8s-master ~]# cd inventory/
[root@k8s-master inventory]# 
[root@k8s-master inventory]# cat deploy-nginx.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: my-deploy-nginx
  name: my-deploy-nginx  // Pod 名字叫做:my-deploy-nginx
  namespace: test
spec:
  replicas: 4  // 在这个Pod下运行4个容器
  selector:
    matchLabels:
      app: my-deploy
  template:
    metadata:
      labels:
        app: my-deploy
    spec:
      containers:
      - image: nginx:latest
        imagePullPolicy: IfNotPresent  // 如果镜像存在本地,不拉取,如果没有存在本地着拉取
        name: nginx-containers  // Pod 中容器的名称
        ports:
        - containerPort: 80
          protocol: TCP
[root@k8s-master inventory]#
[root@k8s-master inventory]# kubectl apply -f deploy-nginx.yaml 
deployment.apps/my-deploy-nginx created
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl get -f deploy-nginx.yaml 
NAME              READY   UP-TO-DATE   AVAILABLE   AGE
my-deploy-nginx   4/4     4            4           17m
[root@k8s-master inventory]# kubectl get -f deploy-nginx.yaml -o wide
NAME              READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS         IMAGES         SELECTOR
my-deploy-nginx   4/4     4            4           17m   nginx-containers   nginx:latest   app=my-deploy
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl get pods -n test
NAME                               READY   STATUS    RESTARTS   AGE
my-deploy-nginx-6bdd87fd6d-c5sxz   1/1     Running   0          18m
my-deploy-nginx-6bdd87fd6d-cnjrd   1/1     Running   0          18m
my-deploy-nginx-6bdd87fd6d-v8b8z   1/1     Running   0          18m
my-deploy-nginx-6bdd87fd6d-wd25q   1/1     Running   0          18m
[root@k8s-master inventory]# 


# 查看deployment的标签[--show-labels]
[root@k8s-master inventory]# kubectl get deploy -n test --show-labels
NAME              READY   UP-TO-DATE   AVAILABLE   AGE   LABELS
my-deploy-nginx   4/4     4            4           19m   app=my-deploy-nginx
[root@k8s-master inventory]# 

# 查看Pod的标签[--show-labels]
[root@k8s-master inventory]# kubectl get pods -n test --show-labels
NAME                               READY   STATUS    RESTARTS   AGE   LABELS
my-deploy-nginx-6bdd87fd6d-c5sxz   1/1     Running   0          20m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-cnjrd   1/1     Running   0          20m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-v8b8z   1/1     Running   0          20m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-wd25q   1/1     Running   0          20m   app=my-deploy,pod-template-hash=6bdd87fd6d
[root@k8s-master inventory]# 

[root@k8s-master ~]# kubectl get -n test pods -o wide
NAME                               READY   STATUS    RESTARTS   AGE   IP            NODE        NOMINATED NODE   READINESS GATES
my-deploy-nginx-6bdd87fd6d-c5sxz   1/1     Running   0          29m   10.244.1.24   k8s-node1   <none>           <none>
my-deploy-nginx-6bdd87fd6d-cnjrd   1/1     Running   0          29m   10.244.2.18   k8s-node2   <none>           <none>
my-deploy-nginx-6bdd87fd6d-v8b8z   1/1     Running   0          29m   10.244.2.17   k8s-node2   <none>           <none>
my-deploy-nginx-6bdd87fd6d-wd25q   1/1     Running   0          29m   10.244.1.23   k8s-node1   <none>           <none>
[root@k8s-master ~]# 
[root@k8s-master ~]# curl 10.244.2.17  // 只能在内部访问
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@k8s-master ~]# 

可以执行对应的创建和删除命令了:

创建:kubectl create -f deploy-nginx.yaml

删除:kubectl delete -f deploy-nginx.yaml

3.5 Service

通过上一章节的学习,已经能够利用Deployment创建一组Pod来提供具有高可用性的服务。

虽然每个Pod都会分配一个单独的Pod IP,然而却存在如下两问题:

  • Pod IP 会随着Pod的重建产生变化
  • Pod IP 仅仅是集群内可见的虚拟IP,外部无法访问

这样对于访问这个服务带来了难度。因此,kubernetes设计了Service来解决这个问题。

Service可以看作是一组同类Pod对外的访问接口。借助Service,应用可以方便地实现服务发现和负载均衡。

操作一:创建集群内部可访问的Service

shell 复制代码
# 在上面已经使用yaml格式创建了4个容器,使用deployment
[root@k8s-master ~]# kubectl get pods -n test
NAME                               READY   STATUS    RESTARTS   AGE
my-deploy-nginx-6bdd87fd6d-c5sxz   1/1     Running   0          87m
my-deploy-nginx-6bdd87fd6d-cnjrd   1/1     Running   0          87m
my-deploy-nginx-6bdd87fd6d-v8b8z   1/1     Running   0          87m
my-deploy-nginx-6bdd87fd6d-wd25q   1/1     Running   0          87m
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get deployment -n test  // deployment名为:my-deploy-nginx
NAME              READY   UP-TO-DATE   AVAILABLE   AGE
my-deploy-nginx   4/4     4            4           90m
[root@k8s-master ~]# 

# 默认的名称空间[default]
[root@k8s-master ~]# kubectl get service  // 查看当前有那些service服务
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   209d // 系统自带的
[root@k8s-master ~]#

# 查看指定的名称空间[-n 指定查看那个的名称空间]
[root@k8s-master ~]# kubectl get -n test service
No resources found in dev namespace.
[root@k8s-master ~]# 


# 暴露Service
[root@k8s-master ~]# kubectl expose deployment my-deploy-nginx --name=svc-my-deploy-nginx --port=80 --target-port=80 --type=ClusterIP -n test
service/svc-my-deploy-nginx exposed
[root@k8s-master ~]#

# 查看service
[root@k8s-master ~]# kubectl get -n test service
NAME                  TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE
svc-my-deploy-nginx   ClusterIP   10.103.51.241   <none>        80/TCP    3m24s
[root@k8s-master ~]# 

# 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的
# 可以通过这个IP访问当前service对应的POD
[root@k8s-master ~]# curl 10.103.51.241:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>  # 欢迎使用nginx!
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@k8s-master ~]#

操作二:创建集群外部也可访问的Service

shell 复制代码
# 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问
# 如果需要创建外部也可以访问的Service,需要修改type为NodePort
[root@k8s-master ~]# kubectl expose deployment my-deploy-nginx --name=svc-nginx --port=80 --target-port=80 --type=NodePort -n test
service/svc-nginx exposed
[root@k8s-master ~]# 

# 此时查看,会发现出现了NodePort类型的Service,而且有一对Port(80:30044/TC)
[root@k8s-master ~]# kubectl get -n test service
NAME                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
svc-my-deploy-nginx   ClusterIP   10.103.51.241    <none>        80/TCP         14m
svc-nginx             NodePort    10.103.113.161   <none>        80:30044/TCP   9s
[root@k8s-master ~]# 

# 接下来就可以通过集群外的主机访问 节点IP:30044 访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址
http://192.168.192.4:30044/  或者 http://192.168.192.5:30044/ 

删除Service

shell 复制代码
[root@k8s-master ~]# kubectl delete -n test service svc-my-deploy-nginx svc-nginx 
service "svc-my-deploy-nginx" deleted
service "svc-nginx" deleted
[root@k8s-master ~]# kubectl get -n test service
No resources found in test namespace.
[root@k8s-master ~]# 

配置方式

创建一个svc-nginx.yaml,内容如下:

shell 复制代码
[root@k8s-master inventory]# kubectl get pods -n test --show-labels
NAME                               READY   STATUS    RESTARTS   AGE    LABELS
my-deploy-nginx-6bdd87fd6d-c5sxz   1/1     Running   0          3h1m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-cnjrd   1/1     Running   0          3h1m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-v8b8z   1/1     Running   0          3h1m   app=my-deploy,pod-template-hash=6bdd87fd6d
my-deploy-nginx-6bdd87fd6d-wd25q   1/1     Running   0          3h1m   app=my-deploy,pod-template-hash=6bdd87fd6d
[root@k8s-master inventory]# 

[root@k8s-master ~]# cd inventory/
[root@k8s-master inventory]# 
[root@k8s-master inventory]# cat svc-nginx.yaml 
apiVersion: v1
kind: Service
metadata:
  name: svc-nginx
  namespace: test
spec:
  clusterIP: 10.109.179.231  # 固定service的内网IP。也可以不写它自动创建一个IP出来
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: my-deploy  # 指定容器标签my-deploy
  type: NodePort
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl apply -f svc-nginx.yaml 
service/svc-nginx created
[root@k8s-master inventory]# 
[root@k8s-master inventory]# kubectl get svc -n test
NAME                  TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
svc-nginx             NodePort    10.109.179.231   <none>        80:30726/TCP   9s
[root@k8s-master inventory]#
[root@k8s-master inventory]# curl 10.109.179.231
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@k8s-master inventory]#

# 接下来就可以通过集群外的主机访问 节点IP:30726 访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址
http://192.168.192.4:30726

可以执行对应的创建和删除命令了:

创建:kubectl create -f svc-nginx.yaml

删除:kubectl delete -f svc-nginx.yaml


yaml 复制代码
apiVersion: v1
kind: Service
metadata:
  name: svc-nginx
  namespace: test
spec:
  clusterIP: 10.109.179.231
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: my-deploy
  type: ClusterIP   

小结

至此,已经掌握了Namespace、Pod、Deployment、Service资源的基本操作,有了这些操作,就可以在kubernetes集群中实现一个服务的简单部署和访问了,但是如果想要更好的使用kubernetes,就需要深入学习这几种资源的细节和原理。

相关推荐
胖毁青春,瘦解百病1 小时前
Docker镜像源设置不生效问题排查
docker·容器
CloudPilotAI1 小时前
15条 Karpenter 最佳实践,轻松掌握弹性伸缩
kubernetes·弹性伸缩·karpenter
会飞的土拨鼠呀1 小时前
Flannel是什么,如何安装Flannel
运维·云原生·kubernetes
ether-lin2 小时前
DevOps实战:用Kubernetes和Argo打造自动化CI/CD流程(1)
ci/cd·kubernetes·devops
Carry_NJ3 小时前
docker-compose样例
运维·docker·容器
勇-子4 小时前
K8s 常用资源介绍
云原生·容器·kubernetes
大G哥4 小时前
k8s创建单例redis设置密码
数据库·redis·云原生·容器·kubernetes
勇-子6 小时前
K8s DaemonSet的介绍
云原生·容器·kubernetes
孟里啥都有.6 小时前
12.24 k8s yaml文件类型和介绍
云原生·容器·kubernetes
花晓木6 小时前
最新版本 - 二进制安装k8s1.29.2 集群
云原生·容器·kubernetes