Article directory
Getting Started
This chapter will introduce how to deploy an nginx service in a kubernetes cluster and be able to access it.
1. Namespace
Namespace is a very important resource in the kubernetes system. Its main function is to realize resource isolation of multiple environments or resource isolation of multi-tenants.
By default, in the kubernetes cluster 所有的Pod都是可以相互访问的
. But in practice, you may not want to allow two Pods to access each other, 那此时就可以将两个Pod划分到不同的namespace下
. Kubernetes can form logical "groups" by allocating resources within the cluster to different Namespaces, so as to facilitate the isolated use and management of resources in different groups.
Through the kubernetes authorization mechanism, different namespaces can be handed over to different tenants for management, thus realizing multi-tenant resource isolation. At this time, the resource quota mechanism of kubernetes can also be combined to limit the resources that different tenants can occupy, such as CPU usage, memory usage, etc., to realize the management of tenants' available resources.
That is, resources are isolated from each other.
After the cluster is started, kubernetes will create several namespaces by default
[root@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系统创建的资源都处于这个命名空间
Let's look at the specific operations of namespace resources:
View
1. View all ns commands: kubectl get ns
[root@master ~]# kubectl get ns
NAME STATUS AGE
default Active 45h
kube-node-lease Active 45h
kube-public Active 45h
kube-system Active 45h
2. View the specified ns command: kubectl get ns ns name
[root@master ~]# kubectl get ns default
NAME STATUS AGE
default Active 45h
3. Specify the output format command: kubectl get ns ns name -o format parameter
There are many formats supported by kubernetes, the more common ones are wide, json, yaml
[root@master ~]# kubectl get ns default -o yaml
apiVersion: v1 //显示版本
kind: Namespace //对命名空间操作
metadata:
creationTimestamp: "2022-11-17T04:27:00Z" //创建的时间
labels: //标签
kubernetes.io/metadata.name: default
name: default //在那操作
resourceVersion: "191"
uid: 3debe6c9-f2ed-483a-b938-c363d5755036
spec:
finalizers:
- Kubernetes //对谁操作
status: //状态
phase: Active
4. You can use explain to read standard documents to obtain parameters - generally used when writing yaml files
[root@master ~]# kubectl explain ns
KIND: Namespace
VERSION: v1
DESCRIPTION:
Namespace provides a scope for Names. Use of multiple namespaces is
optional.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object. Servers should convert recognized schemas to the latest int
5. View ns details command: kubectl describe ns ns name
[root@master ~]# kubectl describe ns default
Name: default
Labels: kubernetes.io/metadata.name=default
Annotations: <none>
Status: Active # Active 命名空间正在使用中 Terminating 正在删除命名空间
No resource quota. # ResourceQuota 针对namespace做的资源限制
No LimitRange resource. # LimitRange针对namespace中的每个组件做的资源限制
6. Create a namespace
[root@master ~]# kubectl create ns dev
namespace/dev created
删除
# 删除namespace
[root@master ~]# kubectl delete ns dev
namespace "dev" deleted
配置方式
首先准备一个yaml文件:ns-dev.yaml
//只用于简单的命名空间话只需这几步
[root@master ~]# cat ns-hh.yaml
apiVersion: v1
kind: Namespace
metadata:
name: ll
然后就可以执行对应的创建和删除命令了:
创建:
[root@master ~]# kubectl create -f ns-hh.yaml
namespace/ll created
[root@master ~]# kubectl get ns ll
NAME STATUS AGE
ll Active 78s
删除:kubectl delete -f ns-dev.yaml
[root@master ~]# kubectl delete -f ns-hh.yaml
namespace "ll" deleted
[root@master ~]# kubectl get ns ll
Error from server (NotFound): namespaces "ll" not found
2. Pods
Pod is the smallest unit of kubernetes cluster management. To run a program, it must be deployed in a container, and the container must exist in the Pod.
Pod can be regarded as the package of containers, and one or more containers can exist in a Pod.
After the kubernetes cluster is started, each component in the cluster also runs as a Pod. You can view it with the following command:
[root@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隔离空间
//用自主管理的nginx服务保存在/dev隔离区
[root@master ~]# kubectl run hhnginx --image nginx --port 80 -n lty
pod/hhnginx created
查看pod信息
# 查看Pod基本信息
[root@master ~]# kubectl get pod -n lty
NAME READY STATUS RESTARTS AGE
hhnginx 1/1 Running 0 17s
# 以yaml形式查看Pod的详细信息
[root@master ~]# kubectl describe pod hhnginx -n lty
Name: hhnginx
Namespace: lty
Priority: 0
Service Account: default
Node: node1/192.168.47.20 //在那个节点
Start Time: Mon, 28 Nov 2022 16:33:17 +0800
Labels: run=hhnginx
Annotations: <none>
Status: Running
IP: 10.244.1.6
IPs:
IP: 10.244.1.6
Containers: //容器
hhnginx:
Container ID: containerd://0b4e7f5261f810d3fc0bf2a3d766414771d2bc959264dd6116f6589f916e0e75
Image: nginx
Image ID: docker.io/library/nginx@sha256:e209ac2f37c70c1e0e9873a5f7231e91dcd83fdf1178d8ed36c2ec09974210ba
Port: 80/TCP //端口
Host Port: 0/TCP
State: Running
Started: Mon, 28 Nov 2022 16:33:20 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-dzkv7 (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-dzkv7:
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 6m8s default-scheduler Successfully assigned lty/hhnginx to node1
Normal Pulling 6m7s kubelet Pulling image "nginx"
Normal Pulled 6m5s kubelet Successfully pulled image "nginx" in 2.472160753s
Normal Created 6m5s kubelet Created container hhnginx
Normal Started 6m5s kubelet Started container hhnginx访问Pod
Get the IP of the pod
[root@master ~]# kubectl get pod -n lty -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
hhnginx 1/1 Running 0 13m 10.244.1.6 node1 <none> <none>
pod1 1/1 Running 0 9d 10.244.1.4 node1 <none> <none>
#访问POD,10.244.1.6只受限于内网访问
[root@master ~]# curl http://10.244.1.6
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
Pod网络一直使用的是flannel插件来使用的
删除指定Pod
# 删除指定Pod
[root@master ~]# kubectl delete pod hhnginx -n lty
pod "hhnginx" deleted
If create, it shows that the Pod was successfully deleted, but after querying again, it is found that a new one has been generated
Kubectl create deployment nginx --image nginx --port 80 -n dev //The current pod is managed by the pod controller
Kubectl run nginx --image nginx --port 80 -n dev //Autonomous management pod
Deployment uses this to create a container and it will still run after it is deleted
//created with a pod manager
[root@master ~]# kubectl create deployment nginx --image nginx --port 80 -n lty
deployment.apps/nginx created
[root@master ~]# kubectl get pods -n lty
NAME READY STATUS RESTARTS AGE
nginx-ff6774dc6-crq6t 1/1 Running 0 33s
pod1 1/1 Running 0 9d
[root@master ~]# kubectl delete pod nginx-ff6774dc6-crq6t -n lty
pod "nginx-ff6774dc6-crq6t" deleted
//可见又运行了
[root@master ~]# kubectl get pods -n lty
NAME READY STATUS RESTARTS AGE
nginx-ff6774dc6-75zwf 1/1 Running 0 3s
# 这是因为当前Pod是由Pod控制器创建的,控制器会监控Pod状况,一旦发现Pod死亡,会立即重建# 此时要想删除Pod,必须删除Pod控制器
# 先来查询一下当前namespace下的Pod控制器
[root@master ~]# kubectl get pods -n lty
NAME READY STATUS RESTARTS AGE
nginx-ff6774dc6-75zwf 1/1 Running 0 3s
# 接下来,删除此Pod控制器pod资源吃能删完
[root@master ~]# kubectl delete deploy nginx -n lty
deployment.apps "nginx" deleted
# 稍等片刻,再查询Pod,发现Pod被删除了
[root@master ~]# kubectl get pods -n lty
No resources found in dev namespace.
Configuration operation
This kind of variable writing can also be done by viewing the operation of the next version
[root@master ~]# kubectl explain pod.spec
KIND: Pod
VERSION: v1
RESOURCE: spec <Object>
DESCRIPTION:
Specification of the desired behavior of the pod. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
PodSpec is a description of a pod.
创建一个pod-nginx.yaml,内容如下:
[root@master ~]# cat pod-nginx.yaml
apiVersion: v1
kind: Pod
metadata:
name: llnginx
namespace: lty
spec:
containers:
- image: nginx:latest
name: pod
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
[root@master ~]# kubectl create -f pod-nginx.yaml
pod/llnginx created
[root@master ~]# kubectl get pod -n lty
NAME READY STATUS RESTARTS AGE
llnginx 1/1 Running 0 23s
Then you can execute the corresponding creation and deletion commands:
Create: kubectl create -f pod-nginx.yaml
Delete: kubectl delete -f pod-nginx.yaml
3. Label
Label is an important concept in the kubernetes system. Its role is to add identification to resources to distinguish and select them.
Features of Label:
• A Label will be attached to various objects in the form of key/value pairs, such as Node, Pod, Service, etc. •
A resource object can define any number of Labels, and the same Label can also be added Go to any number of resource objects
• Label is usually determined when the resource object is defined, of course, it can also be dynamically added or deleted after the object is created.
Multi-dimensional grouping of resources can be realized through Label, so as to flexibly and conveniently allocate, schedule, and configure resources , deployment and other management work.
Some commonly used Label examples are as follows:
• Version label: "version": "release", "version": "stable"...
• Environment label: "environment": "dev", "environment": "test", "environment" :"pro"
• Schema tags: "tier":"frontend", "tier":"backend"
After the label is defined, the selection of the label must also be considered, which requires the use of the Label Selector,
namely:
Label is used to define an identifier for a resource object
Label Selector is used to query and filter resource objects with certain labels
There are currently two Label Selectors:
Equation-based Label Selector
- name = slave: Select all objects containing key="name" and value="slave" in Label
- env !=production: Select all objects that include the key="env" in the Label and the value is not equal to "production"
Set-based Label Selector
-
name in (master, slave):
Select all objects containing key="name" and value="master" or "slave" in Label -
name not in (frontend):
Select all objects that contain the key="name" in the Label and the value is not equal to "frontend"
Multiple label selection criteria can be used. In this case, multiple Label Selectors can be combined and separated by commas ",". For example:
name=slave, env!=production
name not in (frontend), env!=production
command mode
Label pod resources
[root@master ~]# kubectl label pod llnginx version=1.0 -n lty
pod/llnginx labeled
# 为pod资源更新标签
[root@master ~]# kubectl label pod llnginx version=2.0 -n lty --overwritepod/llnginx labeled
# 查看标签
[root@master ~]# kubectl get pod llnginx -n lty --show-labels
NAME READY STATUS RESTARTS AGE LABELS
llnginx 1/1 Running 0 25m version=2.0
# 筛选标签 ——只筛选2.0版本
[root@master ~]# kubectl get pod -n lty -l version=2.0 --show-labels
NAME READY STATUS RESTARTS AGE LABELS
llnginx 1/1 Running 0 27m version=2.0
#删除标签
[root@master ~]# kubectl label pod llnginx version- -n lty
pod/llnginx unlabeled
[root@master ~]# kubectl get pod llnginx -n lty --show-labels
NAME READY STATUS RESTARTS AGE LABELS
llnginx 1/1 Running 0 29m <none> //可见标签已备删除
configuration method
[root@master ~]# cat pod-nginx.yaml
apiVersion: v1
kind: Pod
metadata:
name: llnginx
namespace: lty
labels:
version: "5.0"
env: "test"
spec:
containers:
- image: nginx:latest
name: pod
ports:
- name: nginx-port
containerPort: 80
protocol: TCP
[root@master ~]# kubectl apply -f pod-nginx.yaml
pod/llnginx configured
[root@master ~]# kubectl get pod llnginx -n lty --show-labels
NAME READY STATUS RESTARTS AGE LABELS
llnginx 1/1 Running 0 31m env=test,version=5.0
然后就可以执行对应的更新命令了:kubectl apply -f pod-nginx.yaml
4. Deployment
In kubernetes, pod is the smallest control unit, but kubernetes seldom directly controls pods, usually through the pod controller. The pod controller is used for pod management to ensure that the pod resources meet the expected state. When the pod resources fail, it will try to restart or rebuild the pod.
There are many types of Pod controllers in kubernetes, and this chapter only introduces one: Deployment.
command operation
Command format: kubectl create deployment name [parameter]
–image specifies the image of the pod
–port specifies the port
–replicas specifies the number of created pods
–namespace specifies the namespace
[root@master ~]# kubectl create deploy nginx --image=nginx:latest --port=80 --replicas=3 -n dev
deployment.apps/nginx created
//查看创建的Pod,运行三个nginxpod资源库
[root@master ~]# kubectl get pods -n dev
NAME READY STATUS RESTARTS AGE
nginx-5ff7956ff6-6k8cb 1/1 Running 0 19s
nginx-5ff7956ff6-jxfjt 1/1 Running 0 19s
nginx-5ff7956ff6-v6jqw 1/1 Running 0 19s
//查看deployment的信息
[root@master ~]# kubectl get deploy -n dev
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 3/3 3 3 2m42s
//UP-TO-DATE:成功升级的副本数量
//AVAILABLE:可用副本的数量
[root@master ~]# kubectl get deploy -n dev -o wide
NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR
nginx 3/3 3 3 2m51s nginx nginx:latest run=nginx
//查看deployment的详细信息
[root@master ~]# kubectl describe deploy nginx -n dev
Name: nginx
Namespace: dev
CreationTimestamp: Wed, 08 May 2021 11:14:14 +0800
Labels: run=nginx
Annotations: deployment.kubernetes.io/revision: 1
Selector: run=nginx
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: run=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-5ff7956ff6 (3/3 replicas created)Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal ScalingReplicaSet 5m43s deployment-controller Scaled up replicaset nginx-5ff7956ff6 to 3
//直接删除pod资源才能完全删除
[root@master ~]# kubectl delete deploy nginx -n dev
deployment.apps "nginx" deleted
配置操作
创建一个deploy-nginx.yaml,内容如下:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
namespace: dev
spec:
replicas: 3
selector:
matchLabels:
run: nginx
template:
metadata:
labels:
run: nginx
spec:
containers:
- image: nginx:latest
name: nginx
ports:
- containerPort: 80
protocol: TCP
Then you can execute the corresponding creation and deletion commands:
Create: kubectl create -f deploy-nginx.yaml
Delete: kubectl delete -f deploy-nginx.yaml
5、Service
Through the study of the last lesson, you have been able to use Deployment to create a set of Pods to provide services with high availability.
Although each Pod will be assigned a separate Pod IP, there are two problems:
• The Pod IP will change as the Pod is rebuilt
• The Pod IP is only a virtual IP visible in the cluster and cannot be accessed externally
This makes it difficult to access the service. Therefore, kubernetes designed Service to solve this problem.
Service can be regarded as an external access interface for a group of Pods of the same type. With Service, applications can easily implement service discovery and load balancing.
Operation 1: Create a Service accessible within the cluster
# 暴露Service
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx1 --type=ClusterIP --port=80 --target-port=80 -n dev
service/svc-nginx1 exposed
# 查看service
[root@master ~]# kubectl get svc svc-nginx1 -n dev -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
svc-nginx1 ClusterIP 10.109.179.231 <none> 80/TCP 3m51s run=nginx
# 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的
# 可以通过这个IP访问当前service对应的POD
[root@master ~]# curl 10.109.179.231:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
</head>
<body>
<h1>Welcome to nginx!</h1>
.......
</body>
</html>
操作二:创建集群外部也可访问的Service
# 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问
# 如果需要创建外部也可以访问的Service,需要修改type为NodePort
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx2 --type=NodePort --port=80 --target-port=80 -n dev
service/svc-nginx2 exposed
# 此时查看,会发现出现了NodePort类型的Service,而且有一对Port(80:31928/TC)
[root@master ~]# kubectl get svc svc-nginx2 -n dev -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
svc-nginx2 NodePort 10.100.94.0 <none> 80:31928/TCP 9s run=nginx
# 接下来就可以通过集群外的主机访问 节点IP:31928访问服务了
# 例如在的电脑主机上通过浏览器访问下面的地址
http://192.168.5.4:31928/
删除Service
[root@master ~]# kubectl delete svc svc-nginx-1 -n dev
service "svc-nginx-1" deleted
configuration method
创建一个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
Then you can execute the corresponding creation and deletion commands:
Create: kubectl create -f svc-nginx.yaml
Delete: kubectl delete -f svc-nginx.yaml
Summary
So far, you have mastered the basic operations of Namespace, Pod, Deployment, and Service resources. With these operations, you can implement simple deployment and access of a service in a kubernetes cluster, but if you want to use kubernetes better, you can The details and principles of these resources need to be studied in depth.