华子目录
- 1.Kubernetes中的资源
- `基本命令`示例
- `运行和调试`命令示例
- `高级命令`示例
- `其他命令`示例
- `create`和`apply`区别案例
- 显示`命名空间`
- 查看`命名空间`中的`pod`
- 如何对外`暴露端口`
- 查看`某一个pod`的详细信息
1.Kubernetes中的资源
1.1资源管理介绍
- 在
kubernetes
中,所有的内容
都抽象为资源
,用户需要通过操作资源
来管理kubernetes
kubernetes
本质上
就是一个集群系统
,用户可以在集群
中部署各种服务
- 所谓的
部署服务
,其实就是在kubernetes
集群中运行
一个个的容器
,并将指定的程序
跑在容器
中 kubernetes
的最小管理单元
是pod
而不是容器
,只能
将容器
放在pod
中kubernetes
一般也不会
直接管理pod
,而是通过pod控制器
来管理pod
的pod
中容器服务
的访问
是由kubernetes
提供的service资源
来实现的。pod
中的容器
不能直接被访问
,需要通过service微服务
对端口
进行暴露
,最终我们通过微服务
来访问pod
中的容器
pod
中程序的数据
需要持久化
是由kubernetes
提供的各种存储系统
来实现的
1.2资源管理方式
命令式
对象管理:直接使用命令
去操作kubernetes资源
bash
[root@k8s-master ~]# kubectl run nginx-pod --image=nginx:latest --port=80
#nginx-pod是pod名
命令式
对象配置:通过命令配置
和配置文件
去操作kubernetes
资源- 不能对
yaml
中的内容做更新
(k8s
不允许对create
创建的yaml
文件进行修改
)
- 不能对
bash
[root@k8s-master ~]# kubectl create/patch -f nginx-pod.yml
声明式
对象配置:通过apply
命令和配置文件去操作kubernetes
资源- 可以对
yaml
中的内容做更新
(修改完yaml
文件的内容后,可以使用apply
对其进行应用
)
- 可以对
bash
[root@k8s-master ~]# kubectl apply -f nginx-pod.yml
类型 | 适用环境 | 优点 | 缺点 |
---|---|---|---|
命令式对象管理 | 测试 | 简单 | 只能操作活动对象,无法审计,跟踪 |
命令式对象配置 | 开发 | 可以审计,跟踪 | 项目大时,配置文件多,操作麻烦 |
声明式对象配置 | 开发 | 支持目录操作 | 意外情况下难以调试 |
1.2.1命令式对象管理
kubectl
是kubernetes
集群的命令行工具
,通过它能够对集群本身
进行管理,并能够在集群
上进行容器化应用的安装部署
kubectl
命令的语法如下:
bash
[root@k8s-master ~]# kubectl [command] [type] [name] [flags]
command
:指定要对资源
执行的操作
,例如create
、get
、delete
type
:指定资源类型
,比如deployment
、pod
、service
name
:指定资源名称
,名称大小写敏感
flags
:指定额外
的可选参数
查看所有pod
bash
[root@k8s-master ~]# kubectl get pods
查看某一个pod
bash
[root@k8s-master ~]# kubectl get pods pod名
查看某个pod
,以yaml格式
显示
bash
[root@k8s-master ~]# kubectl get pods pod名 -o yaml
创建两个名为webserver1
和webserver2
的pod
- 其中
myapp
是一个nginx服务
bash
[root@k8s-master ~]# kubectl run webserver1 --image myapp:v1
pod/webserver1 created
[root@k8s-master ~]# kubectl run webserver2 --image myapp:v2
pod/webserver2 created
[root@k8s-master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
webserver1 1/1 Running 0 8m27s
webserver2 1/1 Running 0 6m37s
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webserver1 1/1 Running 0 2m 10.244.1.2 k8s-node1.org <none> <none>
webserver2 1/1 Running 0 10s 10.244.2.6 k8s-node2.org <none> <none>
[root@k8s-master ~]# kubectl get pods -o name
pod/webserver1
pod/webserver2
1.2.2kubectl
常见command
命令
命令分类 | 命令 | 翻译 | 命令作用 |
---|---|---|---|
基本命令 |
create |
创建 |
创建 一个资源 |
edit |
编辑 |
编辑 一个资源 |
|
get |
获取 |
获取 一个资源 |
|
patch |
补丁更新 |
更新 一个资源 |
|
delete |
删除 |
删除 一个资源 |
|
explain |
解释 |
展示资源文档 |
|
运行和调试 |
run |
运行 |
在集群 中运行 一个指定的镜像 |
expose |
暴露 |
暴露 资源为service |
|
describe |
描述 |
显示资源内部信息 |
|
logs |
日志 |
输出容器 在pod 中的日志 |
|
attach |
缠绕 |
进入运行中的容器 |
|
exec |
执行 |
执行 容器中的一个命令 |
|
cp |
复制 |
在pod 内外复制文件 |
|
rollout |
首次展示 |
管理资源的发布 |
|
scale |
规模 |
扩(缩)容 pod的数量 |
|
autoscale |
自动调整 |
自动 调整pod 的数量 |
|
高级命令 |
apply |
应用 |
通过文件 对资源 进行配置 |
label |
标签 |
更新资源 上的标签 |
|
其他命令 |
cluster-info |
集群 信息 |
显示集群信息 |
version |
版本 |
显示 当前server 和client 的版本 |
1.2.3资源类型
kubernetes
中所有的内容
都抽象为资源
- 查看
所有资源类型
bash
[root@k8s-master ~]# kubectl api-resources
NAME SHORTNAMES APIVERSION NAMESPACED KIND
bindings v1 true Binding
componentstatuses cs v1 false ComponentStatus
configmaps cm v1 true ConfigMap
endpoints ep v1 true Endpoints
events ev v1 true Event
limitranges limits v1 true LimitRange
namespaces ns v1 false Namespace
nodes no v1 false Node
persistentvolumeclaims pvc v1 true PersistentVolumeClaim
persistentvolumes pv v1 false PersistentVolume
pods po v1 true Pod
podtemplates v1 true PodTemplate
replicationcontrollers rc v1 true ReplicationController
resourcequotas quota v1 true ResourceQuota
secrets v1 true Secret
serviceaccounts sa v1 true ServiceAccount
services svc v1 true Service
mutatingwebhookconfigurations admissionregistration.k8s.io/v1 false MutatingWebhookConfiguration
validatingadmissionpolicies admissionregistration.k8s.io/v1 false ValidatingAdmissionPolicy
validatingadmissionpolicybindings admissionregistration.k8s.io/v1 false ValidatingAdmissionPolicyBinding
validatingwebhookconfigurations admissionregistration.k8s.io/v1 false ValidatingWebhookConfiguration
customresourcedefinitions crd,crds apiextensions.k8s.io/v1 false CustomResourceDefinition
apiservices apiregistration.k8s.io/v1 false APIService
controllerrevisions apps/v1 true ControllerRevision
daemonsets ds apps/v1 true DaemonSet
deployments deploy apps/v1 true Deployment
replicasets rs apps/v1 true ReplicaSet
statefulsets sts apps/v1 true StatefulSet
selfsubjectreviews authentication.k8s.io/v1 false SelfSubjectReview
tokenreviews authentication.k8s.io/v1 false TokenReview
localsubjectaccessreviews authorization.k8s.io/v1 true LocalSubjectAccessReview
selfsubjectaccessreviews authorization.k8s.io/v1 false SelfSubjectAccessReview
selfsubjectrulesreviews authorization.k8s.io/v1 false SelfSubjectRulesReview
subjectaccessreviews authorization.k8s.io/v1 false SubjectAccessReview
horizontalpodautoscalers hpa autoscaling/v2 true HorizontalPodAutoscaler
cronjobs cj batch/v1 true CronJob
jobs batch/v1 true Job
certificatesigningrequests csr certificates.k8s.io/v1 false CertificateSigningRequest
leases coordination.k8s.io/v1 true Lease
endpointslices discovery.k8s.io/v1 true EndpointSlice
events ev events.k8s.io/v1 true Event
flowschemas flowcontrol.apiserver.k8s.io/v1 false FlowSchema
prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1 false PriorityLevelConfiguration
ingressclasses networking.k8s.io/v1 false IngressClass
ingresses ing networking.k8s.io/v1 true Ingress
networkpolicies netpol networking.k8s.io/v1 true NetworkPolicy
runtimeclasses node.k8s.io/v1 false RuntimeClass
poddisruptionbudgets pdb policy/v1 true PodDisruptionBudget
clusterrolebindings rbac.authorization.k8s.io/v1 false ClusterRoleBinding
clusterroles rbac.authorization.k8s.io/v1 false ClusterRole
rolebindings rbac.authorization.k8s.io/v1 true RoleBinding
roles rbac.authorization.k8s.io/v1 true Role
priorityclasses pc scheduling.k8s.io/v1 false PriorityClass
csidrivers storage.k8s.io/v1 false CSIDriver
csinodes storage.k8s.io/v1 false CSINode
csistoragecapacities storage.k8s.io/v1 true CSIStorageCapacity
storageclasses sc storage.k8s.io/v1 false StorageClass
volumeattachments storage.k8s.io/v1 false VolumeAttachment
1.2.4常用资源类型
资源分类 | 资源名称 | 缩写 | 资源作用 |
---|---|---|---|
集群级别资源 |
nodes |
no |
集群组成部分 |
namespaces |
ns |
隔离pod |
|
pod 资源 |
pods |
po |
装载容器 |
pod资源 控制器 |
replicationcontrollers |
rc |
控制pod资源 |
replicasets |
rs |
控制pod资源 |
|
deployments |
deploy |
控制pod资源 |
|
daemonsets |
ds |
控制pod资源 |
|
jobs |
控制pod资源 |
||
cronjobs |
cj |
控制pod资源 |
|
horizontalpodautoscalers |
hpa |
控制pod资源 |
|
statefulsets |
sts |
控制pod资源 |
|
服务发现资源 |
services |
svc |
统一pod对外接口 |
ingress |
ing |
统一pod对外接口 |
|
存储资源 |
volumeattachments |
存储 |
|
persistentvolumes |
pv |
存储 |
|
persistentvolumeclaims |
pvc |
存储 |
|
配置资源 |
configmaps |
cm |
配置 |
secrets |
配置 |
基本命令
示例
kubectl
的详细说明地址:https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
- 显示集群版本
bash
[root@k8s-master ~]# kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0
- 显示集群信息
bash
[root@k8s-master ~]# kubectl cluster-info
Kubernetes control plane is running at https://172.25.254.100:6443
CoreDNS is running at https://172.25.254.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
- 创建一个名为
webcluster
的deployment
控制器,控制器中pod
数量为2
bash
#先删除之前的pod
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATE
webserver1 1/1 Running 0 16h 10.244.1.2 k8s-node1.org <none>
webserver2 1/1 Running 0 16h 10.244.2.6 k8s-node2.org <none>
[root@k8s-master ~]# kubectl delete pods webserver1 --force
[root@k8s-master ~]# kubectl delete pods webserver2 --force
[root@k8s-master ~]# kubectl get pods
No resources found in default namespace.
bash
#创建一个名为`webcluster`的`deployment`控制器,控制器中`pod`数量为`2`
[root@k8s-master ~]# kubectl create deployment webcluster --image nginx --replicas 2
deployment.apps/webcluster created
[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webcluster-7c584f774b-9b67l 1/1 Running 0 79s 10.244.2.7 k8s-node2.org <none> <none>
webcluster-7c584f774b-d8xws 1/1 Running 0 79s 10.244.1.3 k8s-node1.org <none> <none>
#查看deployment控制器
[root@k8s-master ~]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
webcluster 2/2 2 2 50s
- 查看资源帮助
explain
bash
#等级式查看
[root@k8s-master ~]# kubectl explain deployment
GROUP: apps
KIND: Deployment
VERSION: v1
DESCRIPTION:
Deployment enables declarative updates for Pods and ReplicaSets.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an object.
Servers should convert recognized schemas to the latest internal value, and
may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
kind <string>
Kind is a string value representing the REST resource this object
represents. Servers may infer this from the endpoint the client submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
metadata <ObjectMeta>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <DeploymentSpec>
Specification of the desired behavior of the Deployment.
status <DeploymentStatus>
Most recently observed status of the Deployment.
[root@k8s-master ~]# kubectl explain deployment.metadata
[root@k8s-master ~]# kubectl explain deployment.spec
- 编辑名为
webcluster
的deployment
控制器,将pod
数量改为3
bash
#编辑名为webcluster的deployment控制器
[root@k8s-master ~]# kubectl edit deployments.apps webcluster
#会进入编辑状态
apiVersion: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2024-10-05T03:47:39Z"
generation: 1
labels:
app: webcluster
name: webcluster
namespace: default
resourceVersion: "27001"
uid: a8bf27c5-c6bb-46d4-b4f7-4accfbb60e71
spec:
progressDeadlineSeconds: 600
replicas: 3 #将原来的2个pod改为3个pod
......
......
......
:wq
- 发现改完
立即生效
bash
[root@k8s-master ~]# kubectl get deployments.apps webcluster
NAME READY UP-TO-DATE AVAILABLE AGE
webcluster 3/3 3 3 18m
[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws
pod/webcluster-7c584f774b-r48fd
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webcluster-7c584f774b-9b67l 1/1 Running 0 20m 10.244.2.7 k8s-node2.org <none> <none>
webcluster-7c584f774b-d8xws 1/1 Running 0 20m 10.244.1.3 k8s-node1.org <none> <none>
webcluster-7c584f774b-r48fd 1/1 Running 0 114s 10.244.2.8 k8s-node2.org <none> <none>
- 利用
补丁 patch
更改控制器配置
(编辑名为webcluster
的deployment
控制器,将pod
数量改为4
)
bash
[root@k8s-master ~]# kubectl patch deployments.apps webcluster -p '{"spec":{"replicas":4}}'
deployment.apps/webcluster patched
[root@k8s-master ~]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
webcluster 4/4 4 4 26m
[root@k8s-master ~]# kubectl get pods -o name
pod/webcluster-7c584f774b-9b67l
pod/webcluster-7c584f774b-d8xws
pod/webcluster-7c584f774b-r48fd
pod/webcluster-7c584f774b-swst6
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webcluster-7c584f774b-9b67l 1/1 Running 0 27m 10.244.2.7 k8s-node2.org <none> <none>
webcluster-7c584f774b-d8xws 1/1 Running 0 27m 10.244.1.3 k8s-node1.org <none> <none>
webcluster-7c584f774b-r48fd 1/1 Running 0 9m7s 10.244.2.8 k8s-node2.org <none> <none>
webcluster-7c584f774b-swst6 1/1 Running 0 92s 10.244.1.4 k8s-node1.org <none> <none>
- 在
控制器
中删除pod
在控制器
中删除
一个pod
后,k8s
会根据数量
再开一个pod
bash
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webcluster-7c584f774b-9b67l 1/1 Running 0 27m 10.244.2.7 k8s-node2.org <none> <none>
webcluster-7c584f774b-d8xws 1/1 Running 0 27m 10.244.1.3 k8s-node1.org <none> <none>
webcluster-7c584f774b-r48fd 1/1 Running 0 9m7s 10.244.2.8 k8s-node2.org <none> <none>
webcluster-7c584f774b-swst6 1/1 Running 0 92s 10.244.1.4 k8s-node1.org <none> <none>
[root@k8s-master ~]# kubectl delete pods webcluster-7c584f774b-9b67l
pod "webcluster-7c584f774b-9b67l" deleted
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webcluster-7c584f774b-d8xws 1/1 Running 0 31m 10.244.1.3 k8s-node1.org <none> <none>
webcluster-7c584f774b-r48fd 1/1 Running 0 13m 10.244.2.8 k8s-node2.org <none> <none>
webcluster-7c584f774b-swst6 1/1 Running 0 5m25s 10.244.1.4 k8s-node1.org <none> <none>
webcluster-7c584f774b-tx55p 1/1 Running 0 5s 10.244.2.9 k8s-node2.org <none> <none>
- 直接删除
控制器
,控制器
控制的所有pod
都会被删除
bash
[root@k8s-master ~]# kubectl delete deployments.apps webcluster
deployment.apps "webcluster" deleted
[root@k8s-master ~]# kubectl get deployments.apps
No resources found in default namespace.
[root@k8s-master ~]# kubectl get pods -o wide
No resources found in default namespace.
运行和调试
命令示例
- 首先要保证一个
纯净的实验环境
bash
#发现没有pod
[root@k8s-master ~]# kubectl get pods
No resources found in default namespace.
- 运行一个名为
testpod
的pod
,该pod
不属于任何控制器
bash
[root@k8s-master ~]# kubectl run testpod --image nginx
pod/testpod created
[root@k8s-master ~]# kubectl get pods -o name
pod/testpod
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod 1/1 Running 0 9s 10.244.2.10 k8s-node2.org <none> <none>
端口暴露
bash
[root@k8s-master ~]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 18h
#--port指定pod中的端口,--target-port指定容器中的服务端口
[root@k8s-master ~]# kubectl expose pod testpod --port 8080 --target-port 80
service/testpod exposed
[root@k8s-master ~]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 18h
testpod ClusterIP 10.99.119.189 <none> 8080/TCP 8s
bash
#访问10.244.2.12
[root@k8s-master ~]# curl 10.244.2.12
<!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>
#访问10.99.119.189:8080
[root@k8s-master ~]# curl 10.99.119.189:8080
<!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>
- 查看
运行中pod
的详细信息
bash
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod 1/1 Running 0 10m 10.244.2.12 k8s-node2.org <none> <none>
[root@k8s-master ~]# kubectl describe pods testpod
Name: testpod
Namespace: default
Priority: 0
Service Account: default
Node: k8s-node2.org/172.25.254.20
Start Time: Sat, 05 Oct 2024 00:45:53 -0400
Labels: run=testpod
Annotations: <none>
Status: Running
IP: 10.244.2.12
IPs:
IP: 10.244.2.12
Containers:
testpod:
Container ID: docker://13361a3a29b394fa0049c28405a76a686a26a7c9a1e1fddbcdc4312f2698156a
Image: nginx
Image ID: docker-pullable://nginx@sha256:127262f8c4c716652d0e7863bba3b8c45bc9214a57d13786c854272102f7c945
Port: <none>
Host Port: <none>
State: Running
Started: Sat, 05 Oct 2024 00:45:54 -0400
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-tzfw6 (ro)
Conditions:
Type Status
PodReadyToStartContainers True
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-tzfw6:
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 10m default-scheduler Successfully assigned default/testpod to k8s-node2.org
Normal Pulling 10m kubelet Pulling image "nginx"
Normal Pulled 10m kubelet Successfully pulled image "nginx" in 281ms (281ms including waiting). Image size: 187694648 bytes.
Normal Created 10m kubelet Created container testpod
Normal Started 10m kubelet Started container testpod
- 查看资源
日志
bash
[root@k8s-master ~]# kubectl logs
daemonsets/ pods/ services/
deployments/ replicasets/ statefulsets/
jobs/ replicationcontrollers/ testpod
[root@k8s-master ~]# kubectl logs pods/testpod
......
......
......
- 运行交互
pod
bash
[root@k8s-master ~]# kubectl run -it testpod1 --image busybox
If you don't see a command prompt, try pressing enter.
/ #
/ #
/ # ls
bin dev etc home lib lib64 proc root sys tmp usr var
/ # exit #退出交互式,不停止pod
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod 1/1 Running 0 20m 10.244.2.12 k8s-node2.org <none> <none>
testpod1 1/1 Running 1 (24s ago) 36s 10.244.1.6 k8s-node1.org <none> <none>
#再次进入容器
[root@k8s-master ~]# kubectl attach -it pods/testpod1
If you don't see a command prompt, try pressing enter.
/ #
/ #
/ # ls
bin dev etc home lib lib64 proc root sys tmp usr var
/ # exit 或 ctrl+p+q退出不停止pod
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod 1/1 Running 0 24m 10.244.2.12 k8s-node2.org <none> <none>
testpod1 1/1 Running 2 (3m9s ago) 4m30s 10.244.1.6 k8s-node1.org <none> <none>
- 在已经运行的
pod
中运行容器中的指定命令
bash
[root@k8s-master ~]# kubectl exec -it pods/testpod1 ifconfig
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
eth0 Link encap:Ethernet HWaddr 12:C1:23:80:08:BA
inet addr:10.244.1.6 Bcast:10.244.1.255 Mask:255.255.255.0
inet6 addr: fe80::10c1:23ff:fe80:8ba/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1450 Metric:1
RX packets:15 errors:0 dropped:0 overruns:0 frame:0
TX packets:13 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:2148 (2.0 KiB) TX bytes:962 (962.0 B)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
- 复制
master宿主机文
件到pod中的容器中
bash
[root@k8s-master ~]# kubectl cp anaconda-ks.cfg testpod1:/
[root@k8s-master ~]# kubectl exec -it pods/testpod1 /bin/sh
/ # ls
anaconda-ks.cfg home root var
bin lib sys
dev lib64 tmp
etc proc usr
/ # touch file1
/ # ls
anaconda-ks.cfg file1 proc usr
bin home root var
dev lib sys
etc lib64 tmp
/ # echo hello world > file1
/ # cat file1
hello world111
- 复制
pod容器中的文件
到master宿主机中
bash
[root@k8s-master ~]# kubectl cp testpod1:/file1 /mnt/file
tar: removing leading '/' from member names
[root@k8s-master ~]# cd /mnt/
[root@k8s-master mnt]# ls
file
[root@k8s-master mnt]# cat file
hello world111
scale
应用
bash
#建立控制器并在控制器中自动运行一个pod
[root@k8s-master ~]# kubectl create deployment huazi --image nginx
deployment.apps/huazi created
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
huazi-79f7fdf69-4wksw 1/1 Running 0 22s 10.244.1.13 k8s-node1.org <none> <none>
#为huazi控制器扩容:扩容到3个pod
[root@k8s-master ~]# kubectl scale deployment huazi --replicas 3
deployment.apps/huazi scaled
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
huazi-79f7fdf69-4wksw 1/1 Running 0 3m4s 10.244.1.13 k8s-node1.org <none> <none>
huazi-79f7fdf69-9qtg9 1/1 Running 0 23s 10.244.1.14 k8s-node1.org <none> <none>
huazi-79f7fdf69-mkfnq 1/1 Running 0 23s 10.244.2.19 k8s-node2.org <none> <none>
#为huazi控制器缩容:缩容到2个pod
[root@k8s-master ~]# kubectl scale deployment huazi --replicas 2
deployment.apps/huazi scaled
[root@k8s-master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
huazi-79f7fdf69-4wksw 1/1 Running 0 4m58s 10.244.1.13 k8s-node1.org <none> <none>
huazi-79f7fdf69-mkfnq 1/1 Running 0 2m17s 10.244.2.19 k8s-node2.org <none> <none>
高级命令
示例
- 利用
命令
生成yaml格式
的文件
bash
[root@k8s-master ~]# mkdir huazi
[root@k8s-master ~]# cd huazi/
[root@k8s-master huazi]#
首先要确保一个纯净的实验环境
bash
[root@k8s-master huazi]# kubectl get pods
NAME READY STATUS RESTARTS AGE
testpod 1/1 Running 0 43m
testpod1 1/1 Running 2 (22m ago) 23m
[root@k8s-master huazi]# kubectl delete pods testpod
pod "testpod" deleted
[root@k8s-master huazi]# kubectl delete pods testpod1 --force
pod "testpod1" deleted
--drg-run=client
仅尝试不运行,是一个固定写法
bash
#仅尝试,不运行
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
app: webserver
name: webserver
spec:
replicas: 1
selector:
matchLabels:
app: webserver
strategy: {}
template:
metadata:
creationTimestamp: null
labels:
app: webserver
spec:
containers:
- image: nginx
name: nginx
resources: {}
status: {}
导入文件
bash
#创建一个控制器文件
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml > webserver.yml
[root@k8s-master huazi]# ls
webserver.yml
bash
#对文件进行简单的修改
[root@k8s-master huazi]# vim webserver.yml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: webserver
name: webserver
spec:
replicas: 2 #修改为2个pod
selector:
matchLabels:
app: webserver
template:
metadata:
labels:
app: webserver
spec:
containers:
- image: nginx
name: nginx
应用文件
bash
#这个文件是一个控制器文件
[root@k8s-master huazi]# kubectl apply -f webserver.yml
deployment.apps/webserver created
[root@k8s-master huazi]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
webserver 2/2 2 2 27s
[root@k8s-master huazi]# kubectl get pods -o name
pod/webserver-7bc769cd4c-mg9kl
pod/webserver-7bc769cd4c-nl7q2
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webserver-7bc769cd4c-mg9kl 1/1 Running 0 2m10s 10.244.2.13 k8s-node2.org <none> <none>
webserver-7bc769cd4c-nl7q2 1/1 Running 0 2m10s 10.244.1.7 k8s-node1.org <none> <none>
- 删除
控制器文件
bash
[root@k8s-master huazi]# kubectl delete -f webserver.yml
deployment.apps "webserver" deleted
[root@k8s-master huazi]# kubectl get deployments.apps
No resources found in default namespace.
[root@k8s-master huazi]# kubectl get pods -o wide
No resources found in default namespace.
- 管理资源
标签
bash
#这个是没有控制的pod
[root@k8s-master huazi]# kubectl run webserver --image nginx
pod/webserver created
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
webserver 1/1 Running 0 12s 10.244.2.15 k8s-node2.org <none> <none>
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver 1/1 Running 0 50s run=webserver
- 更改标签
--overwrite
覆盖
bash
[root@k8s-master huazi]# kubectl label pods webserver run=web --overwrite
pod/webserver labeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver 1/1 Running 0 3m48s run=web
- 添加标签
- 通过
键值对
添加即可
bash
[root@k8s-master huazi]# kubectl label pods webserver app=web1
pod/webserver labeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver 1/1 Running 0 5m33s app=web1,run=web
删除标签
bash
[root@k8s-master huazi]# kubectl label pods webserver app-
pod/webserver unlabeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver 1/1 Running 0 6m48s run=web
- 创建一个
控制器pod
bash
#先删除之前的pod
[root@k8s-master huazi]# kubectl delete pods webserver
pod "webserver" deleted
[root@k8s-master huazi]# kubectl get pods
No resources found in default namespace.
bash
[root@k8s-master huazi]# kubectl create deployment webserver --image nginx --dry-run=client -o yaml > web-label.yaml
[root@k8s-master huazi]# ls
web-label.yaml webserver.yml
[root@k8s-master huazi]# vim web-label.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: webserver
name: webserver
spec:
replicas: 2 #修改为2个pod
selector:
matchLabels:
app: webserver
template:
metadata:
labels:
app: webserver
spec:
containers:
- image: nginx
name: nginx
bash
[root@k8s-master huazi]# kubectl apply -f web-label.yaml
deployment.apps/webserver created
[root@k8s-master huazi]# kubectl get deployments.apps
NAME READY UP-TO-DATE AVAILABLE AGE
webserver 2/2 2 2 7s
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver-7bc769cd4c-bnklx 1/1 Running 0 44s app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f 1/1 Running 0 44s app=webserver,pod-template-hash=7bc769cd4c
修改一个控制器pod
上的一个标签
bash
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver-7bc769cd4c-bnklx 1/1 Running 0 44s app=webserver,pod-tem plate-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f 1/1 Running 0 44s app=webserver,pod-tem plate-hash=7bc769cd4c
[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-bnklx app=lee --over write
pod/webserver-7bc769cd4c-bnklx labeled
[root@k8s-master huazi]# kubectl get pods --show-labels NAME READY STATUS RESTARTS AGE LABELS
webserver-7bc769cd4c-bnklx 1/1 Running 0 3m14s app=lee,pod-templat e-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f 1/1 Running 0 3m14s app=webserver,pod-t emplate-hash=7bc769cd4c
webserver-7bc769cd4c-cgzcq 1/1 Running 0 3s app=webserver,pod-t emplate-hash=7bc769cd4c
我们发现k8s
又起了一个新的pod
当我们删除另一个标签
后,k8s
又起了一个新的pod
bash
[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-cdj8f pod-template-hash-
pod/webserver-7bc769cd4c-cdj8f unlabeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver-7bc769cd4c-bnklx 1/1 Running 0 5m22s app=lee,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-cdj8f 1/1 Running 0 5m22s app=webserver
webserver-7bc769cd4c-cgzcq 1/1 Running 0 2m11s app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-zq5mw 1/1 Running 0 5s app=webserver,pod-template-hash=7bc769cd4c
当我们修改回来原来的标签
后,k8s
又把之前新的pod删除
了
bash
[root@k8s-master huazi]# kubectl label pods webserver-7bc769cd4c-bnklx app=webserver --overwrite
pod/webserver-7bc769cd4c-bnklx labeled
[root@k8s-master huazi]# kubectl get pods --show-labels
NAME READY STATUS RESTARTS AGE LABELS
webserver-7bc769cd4c-cdj8f 1/1 Running 0 8m45s app=webserver
webserver-7bc769cd4c-cgzcq 1/1 Running 0 5m34s app=webserver,pod-template-hash=7bc769cd4c
webserver-7bc769cd4c-zq5mw 1/1 Running 0 3m28s app=webserver,pod-template-hash=7bc769cd4c
总结
所以我们发现,k8s
是通过标签
去记录pod的数量
,如果有多个标签
,且多个标签必须一致
。如果不一致
,则k8s
会根据pod
的数量重新
启动相应
个pod
其他命令
示例
bash
[root@k8s-master huazi]# kubectl cluster-info
Kubernetes control plane is running at https://172.25.254.100:6443
CoreDNS is running at https://172.25.254.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
bash
[root@k8s-master huazi]# kubectl version
Client Version: v1.30.0
Kustomize Version: v5.0.4-0.20230601165947-6ce0bf390ce3
Server Version: v1.30.0
create
和apply
区别案例
bash
[root@k8s-master huazi]# kubectl run testpod1 --image myapp:v1 --dry-run=client -o yaml > testpod1.yml
[root@k8s-master huazi]# ls
testpod1.yml
[root@k8s-master huazi]# vim testpod1.yml
apiVersion: v1
kind: Pod
metadata:
labels:
run: testpod1
name: testpod1
spec:
containers:
- image: myapp:v1
name: testpod1
[root@k8s-master huazi]# kubectl create -f testpod1.yml
pod/testpod1 created
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod1 1/1 Running 0 8s 10.244.1.10 k8s-node1.org <none> <none>
[root@k8s-master huazi]# curl 10.244.1.10
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
[root@k8s-master huazi]# vim testpod1.yml
apiVersion: v1
kind: Pod
metadata:
labels:
run: testpod1
name: testpod1
spec:
containers:
- image: myapp:v2 #将版本改为v2
name: testpod1
#发现使用create更新不了
[root@k8s-master huazi]# kubectl create -f testpod1.yml
Error from server (AlreadyExists): error when creating "testpod1.yml": pods "testpod1" already exists
#使用apply可以更新
[root@k8s-master huazi]# kubectl apply -f testpod1.yml
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
testpod1 1/1 Running 1 (23s ago) 3m13s 10.244.1.10 k8s-node1.org <none> <none>
[root@k8s-master huazi]# curl 10.244.1.10
Hello MyApp | Version: v2 | <a href="hostname.html">Pod Name</a>
- 所以
create
只能建立,不能更新
,apply
可以更新
显示命名空间
bash
[root@k8s-master huazi]# kubectl -n
default kube-node-lease kube-system
kube-flannel kube-public
查看命名空间
中的pod
- 查看
所有命名空间
中的pod
--all-namespaces
bash
[root@k8s-master huazi]# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
default testpod1 1/1 Running 1 (4m54s ago) 7m44s
kube-flannel kube-flannel-ds-m7ksl 1/1 Running 0 22h
kube-flannel kube-flannel-ds-q55gr 1/1 Running 0 22h
kube-flannel kube-flannel-ds-twvv4 1/1 Running 1 (21h ago) 22h
kube-system coredns-6c7f6478d8-gplcq 1/1 Running 0 23h
kube-system coredns-6c7f6478d8-vcqg9 1/1 Running 0 23h
kube-system etcd-k8s-master.org 1/1 Running 0 23h
kube-system kube-apiserver-k8s-master.org 1/1 Running 0 23h
kube-system kube-controller-manager-k8s-master.org 1/1 Running 0 23h
kube-system kube-proxy-2dbz2 1/1 Running 1 (21h ago) 22h
kube-system kube-proxy-fcnpc 1/1 Running 0 23h
kube-system kube-proxy-jwn8w 1/1 Running 0 22h
kube-system kube-scheduler-k8s-master.org 1/1 Running 0 23h
- 查看
默认命名空间
中的pod
bash
[root@k8s-master huazi]# kubectl get pods
NAME READY STATUS RESTARTS AGE
testpod1 1/1 Running 1 (7m4s ago) 9m54s
bash
[root@k8s-master huazi]# kubectl -n
default kube-node-lease kube-system
kube-flannel kube-public
[root@k8s-master huazi]# kubectl -n default get pods
NAME READY STATUS RESTARTS AGE
testpod1 1/1 Running 1 (7m58s ago) 10m
如何对外暴露端口
bash
[root@k8s-master huazi]# kubectl run web --image myapp:v1
pod/web created
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
web 1/1 Running 0 32s 10.244.1.11 k8s-node1.org <none> <none>
#10.244.1.11是pod的ip地址
[root@k8s-master huazi]# curl 10.244.1.11
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
bash
[root@k8s-master huazi]# kubectl expose pod web --port 8080 --target-port 80
service/web exposed
#--port指定pod中的端口,
#--target-port指定容器中的服务端口
[root@k8s-master huazi]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 23h
web ClusterIP 10.108.123.93 <none> 8080/TCP 19s
#10.108.123.93这个ip是service的ip地址
#当访问10.108.123.93:8080端口时,转到10.244.1.11的80端口
[root@k8s-master huazi]# curl 10.108.123.93:8080
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
bash
[root@k8s-master huazi]# kubectl edit services web
apiVersion: v1
kind: Service
metadata:
creationTimestamp: "2024-10-05T09:21:02Z"
labels:
run: web
name: web
namespace: default
resourceVersion: "57432"
uid: 33ea0201-e8b2-42ea-874d-2aa2b8e20455
spec:
clusterIP: 10.108.123.93
clusterIPs:
- 10.108.123.93
internalTrafficPolicy: Cluster
ipFamilies:
- IPv4
ipFamilyPolicy: SingleStack
ports:
- port: 8080
protocol: TCP
targetPort: 80
selector:
run: web
sessionAffinity: None
type: NodePort #修改类型为NodePort
status:
loadBalancer: {}
[root@k8s-master huazi]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 23h
web NodePort 10.108.123.93 <none> 8080:31340/TCP 9m51s
[root@k8s-master huazi]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
web 1/1 Running 0 14m 10.244.1.11 k8s-node1.org <none> <none>
[root@k8s-master huazi]# curl k8s-node1.org:31340
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
[root@k8s-master huazi]# curl 172.25.254.10:31340
Hello MyApp | Version: v1 | <a href="hostname.html">Pod Name</a>
发现可以对外访问
bash
[root@k8s-master huazi]# kubectl explain service.spec
......
......
......
Possible enum values:
- `"ClusterIP"` means a service will only be accessible inside the cluster,
via the cluster IP.
- `"ExternalName"` means a service consists of only a reference to an
external name that kubedns or equivalent will return as a CNAME record, with
no exposing or proxying of any pods involved.
- `"LoadBalancer"` means a service will be exposed via an external load
balancer (if the cloud provider supports it), in addition to 'NodePort'
type.
- `"NodePort"` means a service will be exposed on one port of every node,
in addition to 'ClusterIP' type.
查看某一个pod
的详细信息
bash
[root@k8s-master huazi]# kubectl get pods
NAME READY STATUS RESTARTS AGE
web 1/1 Running 0 20m
[root@k8s-master huazi]# kubectl describe pods web
Name: web
Namespace: default
Priority: 0
Service Account: default
Node: k8s-node1.org/172.25.254.10
Start Time: Sat, 05 Oct 2024 05:17:53 -0400
Labels: run=web
Annotations: <none>
Status: Running
IP: 10.244.1.11
IPs:
IP: 10.244.1.11
Containers:
web:
Container ID: docker://d1f4ea79ffe996f292f2b0af787afdf7e235496b4b4a89878005a3fed662426f
Image: myapp:v1
Image ID: docker-pullable://myapp@sha256:9eeca44ba2d410e54fccc54cbe9c021802aa8b9836a0bcf3d3229354e4c8870e
Port: <none>
Host Port: <none>
State: Running
Started: Sat, 05 Oct 2024 05:17:54 -0400
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-mv6b4 (ro)
Conditions:
Type Status
PodReadyToStartContainers True
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-mv6b4:
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 20m default-scheduler Successfully assigned default/web to k8s-node1.org
Normal Pulled 20m kubelet Container image "myapp:v1" already present on machine
Normal Created 20m kubelet Created container web
Normal Started 20m kubelet Started container web