3. 实战入门
文章目录
- 3. 实战入门
- 3.1 Namespace
- 3.1.1测试两个不同的名称空间之间的 Pod 是否连通性
- 3.2 Pod
- 3.3 Label
- 3.4 Deployment
- 3.5 Service
本章节将介绍如何在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 ~]# cd inventory/
[root@k8s-master inventory]# ls
nginx.yaml
[root@k8s-master inventory]# cat nginx.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 inventory]# kubectl create -f nginx.yaml
namespace/dev created
pod/nginx-pod created
pod/apache created
[root@k8s-master inventory]# kubectl get -n default pod
NAME READY STATUS RESTARTS AGE
apache 1/1 Running 0 22s
[root@k8s-master inventory]# kubectl get -n dev pod
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 28s
[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 inventory]# kubectl exec apache -it -- sh
/ #
/ # 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 12:fb:7c:8e:06:7a brd ff:ff:ff:ff:ff:ff
inet 10.244.2.5/24 brd 10.244.2.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::10fb:7cff:fe8e:67a/64 scope link
valid_lft forever preferred_lft forever
/ # exit
// 进入 Pod 的nginx-pod
[root@k8s-master inventory]# kubectl exec nginx-pod -i -t -n dev -- sh
/ #
/ # 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@if6: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1450 qdisc noqueue
link/ether 82:58:66:7d:37:1c brd ff:ff:ff:ff:ff:ff
inet 10.244.1.6/24 brd 10.244.1.255 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::8058:66ff:fe7d:371c/64 scope link
valid_lft forever preferred_lft forever
/ # ping 10.244.2.5
PING 10.244.2.5 (10.244.2.5): 56 data bytes
64 bytes from 10.244.2.5: seq=0 ttl=62 time=1.385 ms
64 bytes from 10.244.2.5: seq=1 ttl=62 time=0.758 ms
64 bytes from 10.244.2.5: seq=2 ttl=62 time=0.422 ms
kubernetes在集群启动之后,会默认创建几个namespac
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 78d // 所有未指定Namespace的对象都会被分配在default命名空间
kube-flannel Active 78d //Kubernetes集群中的一个网络插件
kube-node-lease Active 78d //集群节点之间的心跳维护,v1.13开始引入
kube-public Active 78d //此命名空间下的资源可以被所有人访问(包括未认证用户)
kube-system Active 78d //所有由Kubernetes系统创建的资源都处于这个命名空间
下面来看namespace资源的具体操作:
查看
# 1 查看所有的ns 命令:kubectl get ns
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 78d
kube-flannel Active 78d
kube-node-lease Active 78d
kube-public Active 78d
kube-system Active 78d
# 2 查看指定的ns 命令:kubectl get ns ns名称
[root@k8s-master ~]# kubectl get ns default
NAME STATUS AGE
default Active 78d
# 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-07-25T12:13:50Z"
labels:
kubernetes.io/metadata.name: default
name: default
resourceVersion: "41"
uid: 5f18dc89-4e23-4dda-86ed-8df93e06a375
spec:
finalizers:
- kubernetes
status:
phase: Active
# 4 查看ns详情 命令:kubectl describe ns ns名称
[root@k8s-master ~]# kubectl describe ns default
Name: default
Labels: kubernetes.io/metadata.name=default
Annotations: <none>
Status: Active # Active 命名空间正在使用中 Terminating 正在删除命名空间
# ResourceQuota 针对namespace做的资源限制
# LimitRange针对namespace中的每个组件做的资源限制
No resource quota.
No LimitRange resource.
# 创建
[root@k8s-master ~]# kubectl create ns dev
namespace/dev created
# 删除
[root@k8s-master ~]# kubectl delete ns dev
namespace "dev" deleted
# 配置方式
首先准备一个yaml文件:ns-dev.yaml
[root@k8s-master ~]# cd inventory/
[root@k8s-master inventory]# vi ns-dev.yaml
[root@k8s-master inventory]# cat ns-dev.yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
[root@k8s-master inventory]# kubectl create -f ns-dev.yaml
namespace/dev created
[root@k8s-master inventory]# kubectl delete -f ns-dev.yaml
namespace "dev" deleted
3.2 Pod
Pod是kubernetes集群进行管理的最小单元,程序要运行必须部署在容器中,而容器必须存在于Pod中。
Pod可以认为是容器的封装,一个Pod中可以存在一个或者多个容器。
kubernetes在集群启动之后,集群中的各个组件也都是以Pod方式运行的。可以通过下面命令查看:
测试一个 Pod 跑多个容器
[root@k8s-master inventory]# vi testpodrun.yaml
[root@k8s-master inventory]# 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 testpodrun.yaml
pod/nginx-pod created
[root@k8s-master inventory]# kubectl get pod nginx-pod
NAME READY STATUS RESTARTS AGE
nginx-pod 0/2 ContainerCreating 0 13s
[root@k8s-master inventory]# kubectl describe pod nginx-pod
Name: nginx-pod # pod名字叫nginx-pod
Namespace: default # 在default名称空间
Priority: 0
Service Account: default
Node: k8s-node2/192.168.207.12
Start Time: Thu, 12 Oct 2023 17:34:31 +0800
Labels: <none>
Annotations: <none>
Status: Running # 状态是running
IP: 10.244.2.6
IPs:
IP: 10.244.2.6
Containers: # 下面显示运行那些容器
nginx-containers:
Container ID: containerd://4ebd82c6d1fcd527bac7ff416a2dadd7ff4c8abe406eaf87e78a06cf62ac0f9b
Image: httpd:latest
Image ID: docker.io/library/httpd@sha256:c4606f32d871643396c571e1d453e679c42137dec7dfef58869d10cf056524cb
Port: <none>
Host Port: <none>
State: Running # 容器httpd是运行的
Started: Thu, 12 Oct 2023 17:34:46 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-phk8x (ro)
nginx:
Container ID: containerd://a5156d54de554106e657e20213d240be5b443ca715a5c017bbc5470ca59bb5fe
Image: nginx:latest
Image ID: docker.io/library/nginx@sha256:ee95754109927fbf510f008ee0a24620dff190f4d550b5787d1eaaddb9fd5ffd
Port: <none>
Host Port: <none>
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated # nginx是挂掉的
Reason: Error
Exit Code: 1
Started: Thu, 12 Oct 2023 17:35:25 +0800
Finished: Thu, 12 Oct 2023 17:35:27 +0800
Ready: False
Restart Count: 1
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-phk8x (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
kube-api-access-phk8x:
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 70s default-scheduler Successfully assigned default/nginx-pod to k8s-node2
Normal Pulling 70s kubelet Pulling image "httpd:latest"
Normal Pulled 56s kubelet Successfully pulled image "httpd:latest" in 14.319506799s (14.319513932s including waiting)
Normal Created 56s kubelet Created container nginx-containers
Normal Started 55s kubelet Started container nginx-containers
Normal Pulled 41s kubelet Successfully pulled image "nginx:latest" in 14.395431138s (14.395448401s including waiting)
Normal Created 17s (x2 over 41s) kubelet Created container nginx
Normal Pulled 17s kubelet Successfully pulled image "nginx:latest" in 2.534800827s (2.53481747s including waiting)
Normal Started 16s (x2 over 41s) kubelet Started container nginx
Warning BackOff 13s kubelet Back-off restarting failed container nginx in pod nginx-pod_default(ee8b9e68-1dd0-4594-84a8-ba684a38b31d)
Normal Pulling 2s (x3 over 55s) kubelet Pulling image "nginx:latest"
kubernetes在集群启动之后,集群中的各个组件也都是以Pod方式运行的。可以通过下面命令查看:
[root@k8s-master ~]# kubectl get pod -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-7bdc4cb885-pdfd6 1/1 Running 3805 (7d17h ago) 79d
coredns-7bdc4cb885-wkg7z 1/1 Running 3797 (7d17h ago) 79d
etcd-k8s-master 1/1 Running 1 (7d17h ago) 79d
kube-apiserver-k8s-master 1/1 Running 1 (7d17h ago) 79d
kube-controller-manager-k8s-master 1/1 Running 1 (7d17h ago) 79d
kube-proxy-hphsp 1/1 Running 1 (7d17h ago) 79d
kube-proxy-pgbld 1/1 Running 2 (7d16h ago) 79d
kube-proxy-sp6cn 1/1 Running 1 (7d17h ago) 79d
kube-scheduler-k8s-master 1/1 Running 1 (7d17h ago) 79d
创建并运行
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 ns
NAME STATUS AGE
default Active 79d
dev Active 8s
kube-flannel Active 79d
kube-node-lease Active 79d
kube-public Active 79d
kube-system Active 79d
[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 31s
# 查看Pod的详细信息
[root@k8s-master ~]# kubectl describe pod nginx -n dev
Name: nginx
Namespace: dev
Priority: 0
Service Account: default
Node: k8s-node1/192.168.207.11
Start Time: Fri, 13 Oct 2023 09:20:27 +0800
Labels: run=nginx
Annotations: <none>
Status: Running
IP: 10.244.1.7
IPs:
IP: 10.244.1.7
Containers:
nginx:
Container ID: containerd://c7b08e8aa841a9d313e57d374a1eaeeb86ebbddbfb0fc4bde1c138b062a14c1d
Image: nginx:latest
Image ID: docker.io/library/nginx@sha256:b4af4f8b6470febf45dc10f564551af682a802eda1743055a7dfc8332dffa595
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Fri, 13 Oct 2023 09:20:41 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-5zqw8 (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-5zqw8:
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 62s default-scheduler Successfully assigned dev/nginx to k8s-node1
Normal Pulling 62s kubelet Pulling image "nginx:latest"
Normal Pulled 48s kubelet Successfully pulled image "nginx:latest" in 14.054289468s (14.054294771s including waiting)
Normal Created 48s kubelet Created container nginx
Normal Started 48s kubelet Started container nginx
访问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 112s 10.244.1.7 k8s-node1 <none> <none>
#访问POD
[root@k8s-master ~]# curl http://10.244.1.7
<!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>
删除指定Pod
# 删除指定Pod
[root@k8s-master ~]# kubectl delete pod nginx -n dev
pod "nginx" deleted
[root@k8s-master ~]# kubectl get pods -n dev
No resources found in dev namespace.
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 79d
dev Active 43m
kube-flannel Active 79d
kube-node-lease Active 79d
kube-public Active 79d
kube-system Active 79d
[root@k8s-master ~]# kubectl delete namespace dev // 删除名称空间
namespace "dev" deleted
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 79d
kube-flannel Active 79d
kube-node-lease Active 79d
kube-public Active 79d
kube-system Active 79d
配置操作
创建一个nginx.yaml,内容如下:
[root@k8s-master inventory]# cat nginx.yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
namespace: dev
spec:
containers:
- image: nginx:latest
name: pod
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
[root@k8s-master inventory]# kubectl apply -f nginx.yaml
namespace/dev created
pod/nginx-pod created
[root@k8s-master inventory]# kubectl get pod -n dev
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 18s
[root@k8s-master inventory]# kubectl get -f nginx.yaml
NAME STATUS AGE
namespace/dev Active 29s
NAME READY STATUS RESTARTS AGE
pod/nginx-pod 1/1 Running 0 29s
然后就可以执行对应的创建和删除命令了:
创建:kubectl create -f nginx.yaml
删除:kubectl delete -f 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”:“pro”
- 架构标签:“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 inventory]# kubectl get ns # 查看名称空间
NAME STATUS AGE
default Active 79d
dev Active 6h10m
kube-flannel Active 79d
kube-node-lease Active 79d
kube-public Active 79d
kube-system Active 79d
[root@k8s-master inventory]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 6h10m
[root@k8s-master inventory]# kubectl describe -n dev pods nginx | grep -i labels # 查看有没有标签
Labels: <none>
[root@k8s-master inventory]# kubectl get pods -n dev --show-labels # 查看有没有标签
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod 1/1 Running 0 6h12m <none>
[root@k8s-master inventory]# kubectl label pod nginx-pod app=test -n dev # 为pod资源打标签
pod/nginx-pod labeled
[root@k8s-master inventory]# kubectl describe -n dev pods nginx | grep -i labels
Labels: app=test
[root@k8s-master inventory]# kubectl label -n dev pod nginx-pod app=test1 --overwrite #为pod更新资源打标签
pod/nginx-pod labeled
[root@k8s-master inventory]# kubectl describe -n dev pods nginx | grep -i labels
Labels: app=test1
[root@k8s-master inventory]# kubectl get -n dev pod nginx-pod --show-labels # 查看标签
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod 1/1 Running 0 6h15m app=test1
[root@k8s-master inventory]# kubectl get -n dev pod -l app=test1 --show-labels # 筛选标签
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod 1/1 Running 0 6h15m app=test1
[root@k8s-master inventory]# kubectl get -n dev pod -l app!=test1 --show-labels # 取反
No resources found in dev namespace.
[root@k8s-master inventory]# kubectl label pod nginx-pod -n dev app- # 删除标签
pod/nginx-pod unlabeled
[root@k8s-master inventory]# kubectl get -n dev pod nginx-pod --show-labels
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod 1/1 Running 0 6h16m <none>
配置方式
[root@k8s-master inventory]# cat nginx.yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: v1
kind: Pod
metadata:
labels:
version: web
name: nginx-pod
namespace: dev
spec:
containers:
- image: nginx:latest
imagePullPolicy: IfNotPresent #镜像拉取方式选择这里用的是本地有则使用本地镜像,不拉取
name: pod
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
Always 总是拉取镜像
IfNotPresent 本地有则使用本地镜像,不拉取
Never 只使用本地镜像,从不拉取,即使本地没有
如果省略imagePullPolicy, 策略为always
[root@k8s-master inventory]# kubectl apply -f nginx.yaml
namespace/dev created
pod/nginx-pod created
[root@k8s-master inventory]# kubectl get pods -n dev --show-labels
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod 1/1 Running 0 71s version=web
然后就可以执行对应的更新命令了:kubectl apply -f pod-nginx.yaml
3.4 Deployment
在kubernetes中,Pod是最小的控制单元,但是kubernetes很少直接控制Pod,一般都是通过Pod控制器来完成的。Pod控制器用于pod的管理,确保pod资源符合预期的状态,当pod的资源出现故障时,会尝试进行重启或重建pod。
在kubernetes中Pod控制器的种类有很多,本章节只介绍一种:Deployment。
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 82d
dev Active 2d16h
kube-flannel Active 82d
kube-node-lease Active 82d
kube-public Active 82d
kube-system Active 82d
[root@k8s-master ~]# kubectl create ns test # 创建名称空间
namespace/test created
[root@k8s-master ~]# kubectl get ns
NAME STATUS AGE
default Active 82d
dev Active 2d16h
kube-flannel Active 82d
kube-node-lease Active 82d
kube-public Active 82d
kube-system Active 82d
test Active 6s
[root@k8s-master ~]# kubectl get ns test # 指定查看名称空间
NAME STATUS AGE
test Active 23s
# 查看[名称空间test] namespace,以yaml格式展示结果
[root@k8s-master ~]# kubectl get ns test -o yaml
apiVersion: v1
kind: Namespace
metadata:
creationTimestamp: "2023-10-16T01:36:33Z"
labels:
kubernetes.io/metadata.name: test
name: test
resourceVersion: "2925088"
uid: a14972b2-7789-455d-bcc8-8c3b4508bff8
spec:
finalizers:
- kubernetes
status:
phase: Active
[root@k8s-master ~]# kubectl get ns test --show-labels
NAME STATUS AGE LABELS
test Active 31m kubernetes.io/metadata.name=test
# 命令格式: kubectl create deployment 名称 [参数]
# --image 指定pod的镜像
# --port 指定端口
# --replicas 指定创建pod数量
# --namespace 指定namespace
[root@k8s-master ~]# kubectl create deployment nginx --image=nginx:latest --port=80 --replicas=4 -n test
deployment.apps/nginx created
[root@k8s-master ~]# kubectl get -n test pods # 查看创建的pod
NAME READY STATUS RESTARTS AGE
nginx-57d84f57dc-4w96b 1/1 Running 0 6m16s
nginx-57d84f57dc-hvvr4 1/1 Running 0 6m16s
nginx-57d84f57dc-qlz2k 1/1 Running 0 6m16s
nginx-57d84f57dc-wx576 1/1 Running 0 6m16s
[root@k8s-master ~]# kubectl get -n test pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-57d84f57dc-4w96b 1/1 Running 0 4h8m 10.244.1.10 k8s-node1 <none> <none>
nginx-57d84f57dc-hvvr4 1/1 Running 0 4h8m 10.244.2.10 k8s-node2 <none> <none>
nginx-57d84f57dc-qlz2k 1/1 Running 0 4h8m 10.244.1.11 k8s-node1 <none> <none>
nginx-57d84f57dc-wx576 1/1 Running 0 4h8m 10.244.2.9 k8s-node2 <none> <none>
[root@k8s-master ~]# kubectl get deploy -n test -o wide #查看deployment的信息
NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR
nginx 4/4 4 4 4h12m nginx nginx:latest app=nginx
# UP-TO-DATE:成功升级的副本数量
# AVAILABLE:可用副本的数量
# 加参数 --show-labels 查看标签
[root@k8s-master ~]# kubectl get deploy -n test --show-labels
NAME READY UP-TO-DATE AVAILABLE AGE LABELS
nginx 4/4 4 4 5h44m app=nginx
[root@k8s-master ~]# kubectl get pods -n test --show-labels
NAME READY STATUS RESTARTS AGE LABELS
nginx-57d84f57dc-4w96b 1/1 Running 0 5h44m app=nginx,pod-template-hash=57d84f57dc
nginx-57d84f57dc-hvvr4 1/1 Running 0 5h44m app=nginx,pod-template-hash=57d84f57dc
nginx-57d84f57dc-qlz2k 1/1 Running 0 5h44m app=nginx,pod-template-hash=57d84f57dc
nginx-57d84f57dc-wx576 1/1 Running 0 5h44m app=nginx,pod-template-hash=57d84f57dc
# 查看deployment的详细信息
[root@k8s-master ~]# kubectl describe deployment nginx -n test
Name: nginx
Namespace: test
CreationTimestamp: Mon, 16 Oct 2023 11:08:24 +0800
Labels: app=nginx
Annotations: deployment.kubernetes.io/revision: 1
Selector: app=nginx
Replicas: 4 desired | 4 updated | 4 total | 4 available | 0 unavailable
StrategyType: RollingUpdate
MinReadySeconds: 0
RollingUpdateStrategy: 25% max unavailable, 25% max surge
Pod Template:
Labels: app=nginx
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: nginx-57d84f57dc (4/4 replicas created)
Events: <none>
# 查看deployment,以yaml 格式展示结果 查看某个pod,以yaml格式展示结果
[root@k8s-master ~]# kubectl get deployment nginx -o yaml -n test
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2023-10-16T03:08:24Z"
generation: 1
labels:
app: nginx
name: nginx
namespace: test
resourceVersion: "2933423"
uid: 41f0a6e5-1901-4964-b00a-693c51b7e1e2
spec:
progressDeadlineSeconds: 600
replicas: 4
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: nginx
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: 4
conditions:
- lastTransitionTime: "2023-10-16T03:08:30Z"
lastUpdateTime: "2023-10-16T03:08:30Z"
message: Deployment has minimum availability.
reason: MinimumReplicasAvailable
status: "True"
type: Available
- lastTransitionTime: "2023-10-16T03:08:24Z"
lastUpdateTime: "2023-10-16T03:08:30Z"
message: ReplicaSet "nginx-57d84f57dc" has successfully progressed.
reason: NewReplicaSetAvailable
status: "True"
type: Progressing
observedGeneration: 1
readyReplicas: 4
replicas: 4
updatedReplicas: 4
# 如果要写yaml格式的创建名称空间[namespace]或者是deployment、pod的都是可以手动先创建出来然后执行[kubectl get pod pod_name -o yaml]展示出来后,可以照着展示出来的内容写。
# 删除
[root@k8s-master ~]# kubectl delete -n test deployment nginx
deployment.apps "nginx" deleted
[root@k8s-master ~]# kubectl get deploy -n test -o wide
No resources found in test namespace.
配置操作
创建一个nginx.yaml,内容如下:
[root@k8s-master ~]# cd inventory/
[root@k8s-master inventory]# cat nginx.yaml
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: my-deploy-nginx
name: nginx-pod
namespace: dev
spec:
replicas: 4 # 在这个Pod下运行4个容器
selector:
matchLabels:
app: my-deploy
template:
metadata:
labels:
app: my-deploy
spec:
containers:
- image: nginx:latest
imagePullPolicy: IfNotPresent
name: pod
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
[root@k8s-master inventory]# kubectl apply -f nginx.yaml
namespace/dev created
deployment.apps/nginx-pod created
[root@k8s-master inventory]# kubectl get -f nginx.yaml
NAME STATUS AGE
namespace/dev Active 18s
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/nginx-pod 4/4 4 4 18s
[root@k8s-master inventory]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
nginx-pod-7d4bfdd476-6fgx8 1/1 Running 0 37s
nginx-pod-7d4bfdd476-c9djr 1/1 Running 0 37s
nginx-pod-7d4bfdd476-fzrhc 1/1 Running 0 37s
nginx-pod-7d4bfdd476-qh78b 1/1 Running 0 37s
[root@k8s-master inventory]# kubectl get pods -n dev --show-labels
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod-7d4bfdd476-6fgx8 1/1 Running 0 60s app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-c9djr 1/1 Running 0 60s app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-fzrhc 1/1 Running 0 60s app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-qh78b 1/1 Running 0 60s app=my-deploy,pod-template-hash=7d4bfdd476
[root@k8s-master inventory]# kubectl get pods -n dev pods -o wide
Error from server (NotFound): pods "pods" not found
[root@k8s-master inventory]# kubectl get -n dev pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-pod-7d4bfdd476-6fgx8 1/1 Running 0 2m6s 10.244.1.13 k8s-node1 <none> <none>
nginx-pod-7d4bfdd476-c9djr 1/1 Running 0 2m6s 10.244.2.11 k8s-node2 <none> <none>
nginx-pod-7d4bfdd476-fzrhc 1/1 Running 0 2m6s 10.244.1.12 k8s-node1 <none> <none>
nginx-pod-7d4bfdd476-qh78b 1/1 Running 0 2m6s 10.244.2.12 k8s-node2 <none> <none>
[root@k8s-master inventory]# curl 10.244.1.13
<!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>
然后就可以执行对应的创建和删除命令了:
创建: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 -n dev pods
NAME READY STATUS RESTARTS AGE
nginx-pod-7d4bfdd476-cz2t5 1/1 Running 1 (2m5s ago) 82m
nginx-pod-7d4bfdd476-fbw5f 1/1 Running 1 (2m16s ago) 82m
nginx-pod-7d4bfdd476-fw2kg 1/1 Running 1 (2m5s ago) 82m
nginx-pod-7d4bfdd476-nxw45 1/1 Running 1 (2m16s ago) 82m
[root@k8s-master inventory]# kubectl get deployment -n dev
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-pod 4/4 4 4 117m
# 默认的名称空间[default]
[root@k8s-master inventory]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 84d
# 查看指定的名称空间[-n 指定查看那个的名称空间]
[root@k8s-master ~]# kubectl get -n dev service
No resources found in dev namespace.
# 暴露Service
[root@k8s-master inventory]# kubectl expose deployment nginx-pod --name=svc-nginx-pod --port=80 --target-port=80 --type=ClusterIP -n dev
service/svc-nginx-pod exposed
# 查看service
[root@k8s-master inventory]# kubectl get -n dev svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
svc-nginx-pod ClusterIP 10.98.187.71 <none> 80/TCP 27s
# 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的
# 可以通过这个IP访问当前service对应的POD
[root@k8s-master inventory]# curl 10.98.187.71: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>
<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>
操作二:创建集群外部也可访问的Service
# 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问
# 如果需要创建外部也可以访问的Service,需要修改type为NodePort
[root@k8s-master inventory]# kubectl expose deployment nginx-pod --name=svc-nginx-pod --port=80 --target-port=80 --type=NodePort -n dev
service/svc-nginx-pod exposed
[root@k8s-master inventory]# kubectl get -n dev svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
svc-nginx-pod NodePort 10.104.240.190 <none> 80:31091/TCP 8s
# 接下来就可以通过集群外的主机访问 节点IP:31091 访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址 我这两个k8s-node的ip是192.168.207.11/192.168.207.12
http://192.168.207.11:30044/ 或者 http://192.168.207.12:30044/
删除Service
[root@k8s-master inventory]# kubectl delete -n dev svc svc-nginx-pod
service "svc-nginx-pod" deleted
[root@k8s-master inventory]# kubectl get -n dev svc
No resources found in dev namespace.
配置方式
创建一个svc-nginx.yaml,内容如下:
[root@k8s-master inventory]# kubectl get -n dev pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
nginx-pod-7d4bfdd476-cz2t5 1/1 Running 1 (4h56m ago) 6h16m app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-fbw5f 1/1 Running 1 (4h56m ago) 6h16m app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-fw2kg 1/1 Running 1 (4h56m ago) 6h16m app=my-deploy,pod-template-hash=7d4bfdd476
nginx-pod-7d4bfdd476-nxw45 1/1 Running 1 (4h56m ago) 6h16m app=my-deploy,pod-template-hash=7d4bfdd476
[root@k8s-master inventory]# kubectl get ns
NAME STATUS AGE
default Active 84d
dev Active 7h46m
kube-flannel Active 84d
kube-node-lease Active 84d
kube-public Active 84d
kube-system Active 84d
[root@k8s-master inventory]# cat svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:
name: svc-nginx
namespace: dev
spec:
clusterIP: 10.109.123.231 # 固定service的内网IP。也可以不写它自动创建一个IP出来
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
app: my-deploy # 指定容器标签my-deploy
type: NodePort
[root@k8s-master inventory]# kubectl get -n dev svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
svc-nginx NodePort 10.109.123.231 <none> 80:31596/TCP 11s
[root@k8s-master inventory]# curl 10.109.123.231: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>
<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>
# 查看端口没有发现有31596端口,因为这个端口在iptables规则里
[root@k8s-master inventory]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 127.0.0.1:33189 0.0.0.0:*
LISTEN 0 128 127.0.0.1:10248 0.0.0.0:*
LISTEN 0 128 127.0.0.1:10249 0.0.0.0:*
LISTEN 0 128 192.168.207.10:2379 0.0.0.0:*
LISTEN 0 128 127.0.0.1:2379 0.0.0.0:*
LISTEN 0 128 192.168.207.10:2380 0.0.0.0:*
LISTEN 0 128 127.0.0.1:2381 0.0.0.0:*
LISTEN 0 128 127.0.0.1:10257 0.0.0.0:*
LISTEN 0 128 127.0.0.1:10259 0.0.0.0:*
LISTEN 0 128 [::]:22 [::]:*
LISTEN 0 128 *:10250 *:*
LISTEN 0 128 *:6443 *:*
LISTEN 0 128 *:10256 *:*
[root@k8s-master inventory]# iptables -t nat -nvL | grep 31596
0 0 KUBE-EXT-I56NG7TRBIZKVDMS tcp -- * * 0.0.0.0/0 0.0.0.0/0 /* dev/svc-nginx */ tcp dpt:31596
# 接下来就可以通过集群外的主机访问 节点IP: 31596访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址
删除Service
[root@master ~]# kubectl delete svc svc-nginx-1 -n dev
service "svc-nginx-1" deleted
配置方式
创建一个svc-nginx.yaml,内容如下:
apiVersion: v1
kind: Service
metadata:
name: svc-nginx
namespace: dev
spec:
clusterIP: 10.109.179.231 #固定svc的内网ip
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
run: nginx
type: ClusterIP
然后就可以执行对应的创建和删除命令了:
创建:kubectl create -f svc-nginx.yaml
删除:kubectl delete -f svc-nginx.yaml
小结
至此,已经掌握了Namespace、Pod、Deployment、Service资源的基本操作,有了这些操作,就可以在kubernetes集群中实现一个服务的简单部署和访问了,但是如果想要更好的使用kubernetes,就需要深入学习这几种资源的细节和原理