文章目录
- 3. 实战入门
- 3.1 Namespace
- 3.1.1 测试两个不同的名称空间之间的 Pod 是否连通性
- 3.2 Pod
- 3.3 Label
- 3.4 Deployment
- 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 是否连通性
[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-podnamespace: dev
spec:containers:- name: nginx-containersimage: busybox:latestcommand: ["/bin/sleep","6000"]---apiVersion: v1
kind: Pod
metadata:name: apache # 不指定名称空间就是跑在默认的
spec:containers:- name: httpdimage: busybox:latestcommand: ["/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 [root@k8s-master ~]# kubectl exec --help // 查看帮助命令
# kubectl exec pod-name -c container-name -it -n namespace-name -- /bin/sh
exec 在容器中执行命令
pod-name 指定那个Pod
-c 指定容器名字
-it 交互模式
-n 指定名称空间
-- 固定写法
/bin/sh 进入容器后执行的命令# 进入 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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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:ffinet 10.244.2.12/24 brd 10.244.2.255 scope global eth0valid_lft forever preferred_lft foreverinet6 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 1000link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00inet 127.0.0.1/8 scope host lovalid_lft forever preferred_lft foreverinet6 ::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:ffinet 10.244.1.16/24 brd 10.244.1.255 scope global eth0valid_lft forever preferred_lft foreverinet6 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
[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资源的具体操作:
**查看 **
# 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: defaultname: defaultresourceVersion: "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://b7eeb63f0cb390657ad84dd42aa42acd74d56088e17a48b04b1633e1e12ab57aImage: httpd // 运行那个镜像名Image ID: // 镜像ID docker.io/library/httpd@sha256:33a91a69517f0642b3e8be5cc8d12f8c1ae245728a83947bfc098376be63c15ePort: <none>Host Port: <none>State: RunningStarted: Fri, 28 Jul 2023 13:25:14 +0800Ready: TrueRestart Count: 0Environment: <none>Mounts:/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-xmsjx (ro)
Conditions:Type StatusInitialized True Ready True ContainersReady True PodScheduled True
Volumes:kube-api-access-xmsjx:Type: Projected (a volume that contains injected data from multiple sources)TokenExpirationSeconds: 3607ConfigMapName: kube-root-ca.crtConfigMapOptional: <nil>DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300snode.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events: <none>
[root@k8s-master inventory]#
创建
# 创建namespace(创建名称空间)
[root@k8s-master ~]# kubectl create ns dev
namespace/dev created
删除
# 删除namespace(创建名称空间)
[root@k8s-master ~]# kubectl delete ns dev
namespace "dev" deleted
配置方式
首先准备一个yaml文件:ns-dev.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 跑多个容器
[root@k8s-master manifest]# cat testpodrun.yaml
apiVersion: v1
kind: Pod
metadata:name: nginx-pod
spec:containers:- name: nginx-containersimage: httpd:latest- name: nginximage: 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方式运行的。可以通过下面命令查看:
[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控制器来实现的
# 命令格式: 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信息
# 查看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://a9607020f2f7170b104af0f35ec36f3b0f740a1abe9b5c543b114f145b6e0494Image: nginx:latestImage ID: docker.io/library/nginx@sha256:67f9a4f10d147a6e04629340e6493c9703300ca23a2f7f3aa56fe615d75d31caPort: 80/TCPHost Port: 0/TCPState: RunningStarted: Mon, 31 Jul 2023 15:21:56 +0800Ready: TrueRestart Count: 0Environment: <none>Mounts:/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-726tm (ro)
Conditions:Type StatusInitialized True Ready True ContainersReady True PodScheduled True
Volumes:kube-api-access-726tm:Type: Projected (a volume that contains injected data from multiple sources)TokenExpirationSeconds: 3607ConfigMapName: kube-root-ca.crtConfigMapOptional: <nil>DownwardAPI: true
QoS Class: BestEffort
Node-Selectors: <none>
Tolerations: node.kubernetes.io/not-ready:NoExecute op=Exists for 300snode.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-node1Normal 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 nginxNormal Started 117s kubelet Started container nginx
[root@k8s-master ~]#
访问Pod
# 获取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
[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,内容如下:
[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: nginxnamespace: dev
spec:containers:- image: nginx:latestname: podports:- name: nginx-portcontainerPort: 80protocol: 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 6m47sNAME 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
命令方式
[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 ~]#
配置方式
[root@k8s-master manifest]# cat test.yaml
apiVersion: v1
kind: Pod
metadata:labels:version: webname: httpdnamespace: default
spec:containers:- image: httpd:latestimagePullPolicy: IfNotPresentname: httpdports:- containerPort: 80name: httpd-porthostPort: 8080protocol: 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。
命令操作
# 命令格式: 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: testname: testresourceVersion: "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-deployContainers:nginx:Image: nginx:latestPort: 80/TCPHost Port: 0/TCPEnvironment: <none>Mounts: <none>Volumes: <none>
Conditions:Type Status Reason---- ------ ------Available True MinimumReplicasAvailableProgressing 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: 1labels:app: my-deployname: my-deploynamespace: testresourceVersion: "1094451"uid: cf361c04-0c57-46f1-be24-4fc93680c493
spec:progressDeadlineSeconds: 600replicas: 3revisionHistoryLimit: 10selector:matchLabels:app: my-deploystrategy:rollingUpdate:maxSurge: 25%maxUnavailable: 25%type: RollingUpdatetemplate:metadata:creationTimestamp: nulllabels:app: my-deployspec:containers:- image: nginx:latestimagePullPolicy: Alwaysname: nginxports:- containerPort: 80protocol: TCPresources: {}terminationMessagePath: /dev/termination-logterminationMessagePolicy: FilednsPolicy: ClusterFirstrestartPolicy: AlwaysschedulerName: default-schedulersecurityContext: {}terminationGracePeriodSeconds: 30
status:availableReplicas: 3conditions:- lastTransitionTime: "2023-08-05T05:43:00Z"lastUpdateTime: "2023-08-05T05:43:00Z"message: Deployment has minimum availability.reason: MinimumReplicasAvailablestatus: "True"type: Available- lastTransitionTime: "2023-08-05T05:42:53Z"lastUpdateTime: "2023-08-05T05:43:00Z"message: ReplicaSet "my-deploy-6648745bcc" has successfully progressed.reason: NewReplicaSetAvailablestatus: "True"type: ProgressingobservedGeneration: 1readyReplicas: 3replicas: 3updatedReplicas: 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,内容如下:
[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-nginxname: my-deploy-nginx // Pod 名字叫做:my-deploy-nginxnamespace: test
spec:replicas: 4 // 在这个Pod下运行4个容器selector:matchLabels:app: my-deploytemplate:metadata:labels:app: my-deployspec:containers:- image: nginx:latestimagePullPolicy: IfNotPresent // 如果镜像存在本地,不拉取,如果没有存在本地着拉取name: nginx-containers // Pod 中容器的名称ports:- containerPort: 80protocol: 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
# 在上面已经使用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
# 上面创建的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
[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,内容如下:
[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-nginxnamespace: test
spec:clusterIP: 10.109.179.231 # 固定service的内网IP。也可以不写它自动创建一个IP出来ports:- port: 80protocol: TCPtargetPort: 80selector:app: my-deploy # 指定容器标签my-deploytype: 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]#
# 查看端口没有发现有30726端口,因为这个端口在iptables规则里
[root@k8s-master inventory]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 127.0.0.1:10248 *:*
LISTEN 0 128 127.0.0.1:10249 *:*
LISTEN 0 128 192.168.192.3:2379 *:*
LISTEN 0 128 127.0.0.1:2379 *:*
LISTEN 0 128 192.168.192.3:2380 *:*
LISTEN 0 128 127.0.0.1:2381 *:*
LISTEN 0 128 127.0.0.1:10257 *:*
LISTEN 0 128 127.0.0.1:10259 *:*
LISTEN 0 128 *:22 *:*
LISTEN 0 100 127.0.0.1:25 *:*
LISTEN 0 128 127.0.0.1:43905 *:*
LISTEN 0 128 [::]:10250 [::]:*
LISTEN 0 128 [::]:6443 [::]:*
LISTEN 0 128 [::]:10256 [::]:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 100 [::1]:25 [::]:*
[root@k8s-master inventory]#
[root@k8s-master ~]# iptables -t nat -nvL | grep 30726 // 查看iptables规则 0 0 KUBE-EXT-WUUAWPAQCWK2NLSB tcp -- * * 0.0.0.0/0 0.0.0.0/0 /* test/svc-nginx */ tcp dpt:30726
[root@k8s-master ~]# # 接下来就可以通过集群外的主机访问 节点IP:30726 访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址
http://192.168.192.4:30726
可以执行对应的创建和删除命令了:
创建:kubectl create -f svc-nginx.yaml
删除:kubectl delete -f svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:name: svc-nginxnamespace: test
spec:clusterIP: 10.109.179.231ports:- port: 80protocol: TCPtargetPort: 80selector:app: my-deploytype: ClusterIP
小结
至此,已经掌握了Namespace、Pod、Deployment、Service资源的基本操作,有了这些操作,就可以在kubernetes集群中实现一个服务的简单部署和访问了,但是如果想要更好的使用kubernetes,就需要深入学习这几种资源的细节和原理。