Kubernetes常用命令
1.k8s常用命令总结
kubectl是Kubernetes的命令行工具,可以让用户通过命令行的方式对Kubernetes集群进行操作,通过它与Kubernetes进行交互。通过kubectl能够对集群本身进行管理,并能够在集群上进行容器化应用的安装部署。
kubectl命令行的语法如下
$ kubectl [command] [TYPE] [NAME] [flags]\
- command:子命令,用于操作Kubernetes集群资源对象的命令,例如create、delete、describe、get、apply等。
- TYPE:资源对象的类型,区分大小写,能以单数形式、复数形式或者简写形式表示。例如以下3种TYPE是等价的 (1) kubectl get pod pod1 ,(2)kubectl get pods pod1,(3)kubectl get po pod1。
- NAME:资源对象的名称,区分大小写。如果不指定名称,则系统将返回属于TYPE的全部对象的列表,例如$ kubectl get pods将返回所有Pod的列表。
- flags:kubectl子命令的可选参数,例如使用“-s”指定apiserver的URL地址而不用默认值。
2. 常用命令
2.1 create
[root@master ~]# kubectl create deployment myapp --image nginx
deployment.apps/myapp created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-6d8d776547-m5hhl 0/1 Pending 0 11s
//replicas 创建指定数量的pod
[root@master ~]# kubectl create deployment web --image nginx --replicas 3
deployment.apps/web created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-6d8d776547-m5hhl 0/1 Pending 0 2m33s
nginx-6799fc88d8-zlsx5 1/1 Running 0 23h
web-96d5df5c8-5g8tr 0/1 Pending 0 2s
web-96d5df5c8-k74rn 0/1 Pending 0 2s
web-96d5df5c8-tt46f 0/1 Pending 0 2s
//port 暴露端口
[root@master ~]# kubectl create deployment test --image nginx --port 80
deployment.apps/test created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-6d8d776547-m5hhl 0/1 Pending 0 4m30s
nginx-6799fc88d8-zlsx5 1/1 Running 0 23h
test-7968d6985c-b5kj5 0/1 Pending 0 2s
web-96d5df5c8-5g8tr 0/1 Pending 0 119s
web-96d5df5c8-k74rn 0/1 Pending 0 119s
web-96d5df5c8-tt46f 0/1 Pending 0 119s
2.2 get
//查看初始化文件
[root@master ~]# kubectl get ns
NAME STATUS AGE
default Active 23h
kube-node-lease Active 23h
kube-public Active 23h
kube-system Active 23h
//查看所有pod
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
myapp-6d8d776547-m5hhl 0/1 Pending 0 8m50s
nginx-6799fc88d8-zlsx5 1/1 Running 0 23h
test-7968d6985c-b5kj5 0/1 Pending 0 4m22s
web-96d5df5c8-5g8tr 0/1 Pending 0 6m19s
web-96d5df5c8-k74rn 0/1 Pending 0 6m19s
web-96d5df5c8-tt46f 0/1 Pending 0 6m19s
//查看所有pod提供更多信息
[root@master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
myapp-6d8d776547-m5hhl 0/1 Pending 0 9m5s <none> <none> <none> <none>
nginx-6799fc88d8-zlsx5 1/1 Running 0 23h 10.244.1.2 node1 <none> <none>
test-7968d6985c-b5kj5 0/1 Pending 0 4m37s <none> <none> <none> <none>
web-96d5df5c8-5g8tr 0/1 Pending 0 6m34s <none> <none> <none> <none>
web-96d5df5c8-k74rn 0/1 Pending 0 6m34s <none> <none> <none> <none>
web-96d5df5c8-tt46f 0/1 Pending 0 6m34s <none> <none> <none> <none>
//查看service
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 23h
nginx NodePort 10.105.173.129 <none> 80:31332/TCP 23h
//查看指定模式的pod
[root@master ~]# kubectl get deployment
NAME READY UP-TO-DATE AVAILABLE AGE
myapp 0/1 1 0 12m
nginx 0/1 1 0 23h
test 0/1 1 0 8m17s
web 0/3 3 0 10m
//查看所有的pod和service
[root@master ~]# kubectl get pods,svc
NAME READY STATUS RESTARTS AGE
pod/myapp-6d8d776547-m5hhl 0/1 Pending 0 13m
pod/nginx-6799fc88d8-zlsx5 1/1 Running 0 23h
pod/test-7968d6985c-b5kj5 0/1 Pending 0 9m8s
pod/web-96d5df5c8-5g8tr 0/1 Pending 0 11m
pod/web-96d5df5c8-k74rn 0/1 Pending 0 11m
pod/web-96d5df5c8-tt46f 0/1 Pending 0 11m
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 23h
service/nginx NodePort 10.105.173.129 <none> 80:31332/TCP 23h
//以JSON输出格式列出单个pod
[root@master ~]# kubectl get -o json pod nginx-6799fc88d8-zlsx5
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"creationTimestamp": "2021-12-18T10:29:16Z",
"generateName": "nginx-6799fc88d8-",
"labels": {
"app": "nginx",
"pod-template-hash": "6799fc88d8"
},
"managedFields": [
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:status": {
"f:conditions": {
"k:{\"type\":\"ContainersReady\"}": {
".": {},
"f:lastProbeTime": {},
"f:lastTransitionTime": {},
"f:status": {},
"f:type": {}
},
"k:{\"type\":\"Initialized\"}": {
".": {},
"f:lastProbeTime": {},
"f:lastTransitionTime": {},
"f:status": {},
"f:type": {}
},
"k:{\"type\":\"Ready\"}": {
".": {},
"f:lastProbeTime": {},
"f:type": {}
}
},
"f:containerStatuses": {},
"f:hostIP": {},
"f:phase": {},
"f:podIP": {},
"f:podIPs": {
".": {},
"k:{\"ip\":\"10.244.1.2\"}": {
".": {},
"f:ip": {}
}
},
"f:startTime": {}
}
},
"manager": "kubelet",
"operation": "Update",
"time": "2021-12-18T10:30:58Z"
},
{
"apiVersion": "v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:generateName": {},
"f:labels": {
".": {},
"f:app": {},
"f:pod-template-hash": {}
},
"f:ownerReferences": {
".": {},
"k:{\"uid\":\"9729ba9f-4650-4a2b-b1b2-5f1576d3d924\"}": {
".": {},
"f:apiVersion": {},
"f:blockOwnerDeletion": {},
"f:controller": {},
"f:kind": {},
"f:name": {},
"f:uid": {}
}
}
},
"f:spec": {
"f:containers": {
"k:{\"name\":\"nginx\"}": {
".": {},
"f:image": {},
"f:imagePullPolicy": {},
"f:name": {},
"f:resources": {},
"f:terminationMessagePath": {},
"f:terminationMessagePolicy": {}
}
},
"f:dnsPolicy": {},
"f:enableServiceLinks": {},
"f:restartPolicy": {},
"f:schedulerName": {},
"f:securityContext": {},
"f:terminationGracePeriodSeconds": {}
},
"f:status": {
"f:conditions": {
"k:{\"type\":\"Ready\"}": {
"f:lastTransitionTime": {},
"f:status": {}
}
}
}
},
"manager": "kube-controller-manager",
"operation": "Update",
"time": "2021-12-19T08:57:04Z"
}
],
"name": "nginx-6799fc88d8-zlsx5",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "apps/v1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "nginx-6799fc88d8",
"uid": "9729ba9f-4650-4a2b-b1b2-5f1576d3d924"
}
],
"resourceVersion": "2220",
"uid": "dbff5bf8-eaa4-4d2e-ba9d-f931a6880dce"
},
"spec": {
"containers": [
{
"image": "nginx",
"imagePullPolicy": "Always",
"name": "nginx",
"resources": {},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-4xgsw",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"enableServiceLinks": true,
"nodeName": "node1",
"preemptionPolicy": "PreemptLowerPriority",
"priority": 0,
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-4xgsw",
"secret": {
"defaultMode": 420,
"secretName": "default-token-4xgsw"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2021-12-18T10:29:16Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-12-19T08:57:04Z",
"status": "False",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-12-18T10:30:58Z",
"status": "True",
"type": "ContainersReady"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2021-12-18T10:29:16Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://9fc7645f79606f763290d68256649af9025cbcd63e6890ecb848bf46ae157661",
"image": "nginx:latest",
"imageID": "docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603",
"lastState": {},
"name": "nginx",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2021-12-18T10:30:57Z"
}
}
}
],
"hostIP": "192.168.200.147",
"phase": "Running",
"podIP": "10.244.1.2",
"podIPs": [
{
"ip": "10.244.1.2"
}
],
"qosClass": "BestEffort",
"startTime": "2021-12-18T10:29:16Z"
}
}
//以YML输出格式列出单个pod
[root@master ~]# kubectl get -o yaml pod nginx-6799fc88d8-zlsx5
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2021-12-18T10:29:16Z"
generateName: nginx-6799fc88d8-
labels:
app: nginx
pod-template-hash: 6799fc88d8
managedFields:
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:status:
f:conditions:
k:{"type":"ContainersReady"}:
.: {}
f:lastProbeTime: {}
f:lastTransitionTime: {}
f:status: {}
f:type: {}
k:{"type":"Initialized"}:
.: {}
f:lastProbeTime: {}
f:lastTransitionTime: {}
f:status: {}
f:type: {}
k:{"type":"Ready"}:
.: {}
f:lastProbeTime: {}
f:type: {}
f:containerStatuses: {}
f:hostIP: {}
f:phase: {}
f:podIP: {}
f:podIPs:
.: {}
k:{"ip":"10.244.1.2"}:
.: {}
f:ip: {}
f:startTime: {}
manager: kubelet
operation: Update
time: "2021-12-18T10:30:58Z"
- apiVersion: v1
fieldsType: FieldsV1
fieldsV1:
f:metadata:
f:generateName: {}
f:labels:
.: {}
f:app: {}
f:pod-template-hash: {}
f:ownerReferences:
.: {}
k:{"uid":"9729ba9f-4650-4a2b-b1b2-5f1576d3d924"}:
.: {}
f:apiVersion: {}
f:blockOwnerDeletion: {}
f:controller: {}
f:kind: {}
f:name: {}
f:uid: {}
f:spec:
f:containers:
k:{"name":"nginx"}:
.: {}
f:image: {}
f:imagePullPolicy: {}
f:name: {}
f:resources: {}
f:terminationMessagePath: {}
f:terminationMessagePolicy: {}
f:dnsPolicy: {}
f:enableServiceLinks: {}
f:restartPolicy: {}
f:schedulerName: {}
f:securityContext: {}
f:terminationGracePeriodSeconds: {}
f:status:
f:conditions:
k:{"type":"Ready"}:
f:lastTransitionTime: {}
f:status: {}
manager: kube-controller-manager
operation: Update
time: "2021-12-19T08:57:04Z"
name: nginx-6799fc88d8-zlsx5
namespace: default
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: nginx-6799fc88d8
uid: 9729ba9f-4650-4a2b-b1b2-5f1576d3d924
resourceVersion: "2220"
uid: dbff5bf8-eaa4-4d2e-ba9d-f931a6880dce
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-4xgsw
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node1
preemptionPolicy: PreemptLowerPriority
priority: 0
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
serviceAccount: default
serviceAccountName: default
terminationGracePeriodSeconds: 30
tolerations:
- effect: NoExecute
key: node.kubernetes.io/not-ready
operator: Exists
tolerationSeconds: 300
- effect: NoExecute
key: node.kubernetes.io/unreachable
operator: Exists
tolerationSeconds: 300
volumes:
- name: default-token-4xgsw
secret:
defaultMode: 420
secretName: default-token-4xgsw
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2021-12-18T10:29:16Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2021-12-19T08:57:04Z"
status: "False"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2021-12-18T10:30:58Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2021-12-18T10:29:16Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://9fc7645f79606f763290d68256649af9025cbcd63e6890ecb848bf46ae157661
image: nginx:latest
imageID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
lastState: {}
name: nginx
ready: true
restartCount: 0
started: true
state:
running:
startedAt: "2021-12-18T10:30:57Z"
hostIP: 192.168.200.147
phase: Running
podIP: 10.244.1.2
podIPs:
- ip: 10.244.1.2
qosClass: BestEffort
startTime: "2021-12-18T10:29:16Z"
2.3 expose
//target-port 映射给那个容器端口
//port 要映射的宿主机端口
[root@master ~]# kubectl expose deployment web --port 8080 --target-port 80
service/web exposed
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 23h
nginx NodePort 10.105.173.129 <none> 80:31332/TCP 23h
web ClusterIP 10.97.167.83 <none> 8080/TCP 25s
//访问
[root@master ~]# curl http://10.97.167.83: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>
<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>
2.4 run
//运行一个nginx pod
[root@master ~]# kubectl run nginx --image nginx
pod/nginx created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 Pending 0 7s
//labels 指定标签
[root@master ~]# kubectl run nginx --image nginx --labels "app=web"
pod/nginx created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 Pending 0 3s
[root@master ~]# kubectl describe pod nginx
Name: nginx
Namespace: default
Priority: 0
Node: <none>
Labels: app=web
Annotations: <none>
Status: Pending
IP:
IPs: <none>
Containers:
nginx:
Image: nginx
Port: <none>
Host Port: <none>
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-4xgsw (ro)
Conditions:
Type Status
PodScheduled False
Volumes:
default-token-4xgsw:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-4xgsw
Optional: false
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
---- ------ ---- ---- -------
Warning FailedScheduling 31s default-scheduler 0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 node(s) had taint {node.kubernetes.io/unreachable: }, that the pod didn't tolerate.
Warning FailedScheduling 31s default-scheduler 0/3 nodes are available: 1 node(s) had taint {node-role.kubernetes.io/master: }, that the pod didn't tolerate, 2 node(s) had taint {node.kubernetes.io/unreachable: }, that the pod didn't tolerate.
//试运行;打印相应的 API 对象而不创建它们
[root@master ~]# kubectl run apache --image httpd --dry-run=client
pod/apache created (dry run)
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 0/1 Pending 0 3m11s
nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
web-96d5df5c8-llklz 0/1 Pending 0 5m38s
//-it 交互模式
[root@master ~]# kubectl run -it apache --image httpd --restart=Never
If you don't see a command prompt, try pressing enter.
/ # ls
bin etc proc sys usr
dev home root tmp var
2.5 delete
//单个删除
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
apache 0/1 Pending 0 18m
nginx 0/1 Pending 0 22m
nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
web-96d5df5c8-llklz 0/1 Pending 0 24m
[root@master ~]# kubectl delete deployment web
deployment.apps "web" deleted
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
apache 0/1 Pending 0 19m
nginx 0/1 Pending 0 23m
nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
//多个删除
[root@master ~]# kubectl get pods,svc
NAME READY STATUS RESTARTS AGE
pod/apache 0/1 Pending 0 20m
pod/nginx 0/1 Pending 0 24m
pod/nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
pod/web-96d5df5c8-ccmc8 0/1 Pending 0 2s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 24h
service/web ClusterIP 10.108.217.3 <none> 8080/TCP 30m
[root@master ~]# kubectl delete deployment,svc web
deployment.apps "web" deleted
service "web" deleted
[root@master ~]# kubectl get pods,svc
NAME READY STATUS RESTARTS AGE
pod/apache 0/1 Pending 0 20m
pod/nginx 0/1 Pending 0 24m
pod/nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 24h
//删除所有
[root@master ~]# kubectl delete pod --all
pod "apache" deleted
pod "nginx" deleted
pod "nginx-6799fc88d8-zlsx5" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace.
//-l 指定标签删除
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-zlsx5 1/1 Terminating 0 24h
test 0/1 Pending 0 47s
[root@master ~]# kubectl delete pod -l "app=nginx"
pod "nginx-6799fc88d8-zlsx5" deleted
pod "test" deleted
[root@master ~]# kubectl get pods
No resources found in default namespace
2.6 edit
编辑
[root@master ~]# kubectl run nginx --image nginx --labels "app=amu"
pod/nginx created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 11s
[root@master ~]# kubectl edit pods/nginx
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2021-12-20T09:59:44Z"
labels:
app: v0.1 //修改为v0.1
name: nginx
namespace: default
resourceVersion: "15514"
uid: d2a3d1da-dab6-441c-bbb6-7a2758d2f71a
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: default-token-4xgsw
readOnly: true
:wq
[root@master ~]# kubectl edit pods/nginx
pod/nginx edited
2.7 explain
说明
//查看定义文件
[root@master ~]# kubectl explain deployment
KIND: Deployment
VERSION: apps/v1
DESCRIPTION:
Deployment enables declarative updates for Pods and ReplicaSts.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representatin of an
object. Servers should convert recognized schemas to the latst internal
value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecure/api-conventions.md#resources
kind <string>
Kind is a string value representing the REST resource this oject
represents. Servers may infer this from the endpoint the clint submits
requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecure/api-conventions.md#types-kinds
metadata <Object>
Standard object metadata.
spec <Object>
Specification of the desired behavior of the Deployment.
status <Object>
Most recently observed status of the Deployment.
2.8 rollout
回滚
有效的资源类型的:
- deployments
- daemonsets
- statefulsets
[root@master ~]# kubectl create deployment nginx --image nginx
deployment.apps/nginx created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 11m
nginx-6799fc88d8-cvwhq 0/1 ContainerCreating 0 13s
[root@master ~]# kubectl rollout status deployment/nginx
Waiting for deployment "nginx" rollout to finish: 0 of 1 updated replicas are available...
deployment "nginx" successfully rolled out
//注意:rollout不能回本 pod 和 svc 类型
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 17m
nginx-6799fc88d8-cvwhq 1/1 Running 0 6m16s
[root@master ~]# kubectl rollout status pod/nginx
error: no status viewer has been implemented for Pod
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 2d
nginx NodePort 10.109.148.173 <none> 80:30362/TCP 5s
[root@master ~]# kubectl rollout status svc/nginx
error: no status viewer has been implemented for Service
2.9 scale
扩展
//扩展
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25m
nginx-6799fc88d8-cvwhq 1/1 Running 0 13m
[root@master ~]# kubectl scale --replicas 5 deploy/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 25m
nginx-6799fc88d8-2gxvq 0/1 ContainerCreating 0 2s
nginx-6799fc88d8-bmjnl 0/1 ContainerCreating 0 2s
nginx-6799fc88d8-cvwhq 1/1 Running 0 14m
nginx-6799fc88d8-fdln5 0/1 ContainerCreating 0 2s
nginx-6799fc88d8-hdlgb 0/1 ContainerCreating 0 2s
//缩小
[root@master ~]# kubectl scale --replicas 3 deploy/nginx
deployment.apps/nginx scaled
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 27m
nginx-6799fc88d8-2gxvq 1/1 Running 0 2m3s
nginx-6799fc88d8-cvwhq 1/1 Running 0 16m
nginx-6799fc88d8-hdlgb 1/1 Running 0 2m3s
2.10 autoscale
自动扩展
- min:最少扩展
- max:最大扩展
- percent:百分比
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 28m
nginx-6799fc88d8-2gxvq 1/1 Running 0 3m21s
nginx-6799fc88d8-cvwhq 1/1 Running 0 17m
nginx-6799fc88d8-hdlgb 1/1 Running 0 3m21s
[root@master ~]# kubectl autoscale --min 1 --max 5 --cpu-percent 50 deploy/nginx
horizontalpodautoscaler.autoscaling/nginx autoscaled
[root@master ~]# kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
nginx Deployment/nginx <unknown>/50% 1 5 0 9s
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 29m
nginx-6799fc88d8-2gxvq 1/1 Running 0 4m22s
nginx-6799fc88d8-cvwhq 1/1 Running 0 18m
nginx-6799fc88d8-hdlgb 1/1 Running 0 4m22s
2.11 top
查看资源使用率
[root@master ~]# kubectl top node
2.12 describe
描述
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 37m
nginx-6799fc88d8-2gxvq 1/1 Running 0 12m
nginx-6799fc88d8-cvwhq 1/1 Running 0 26m
nginx-6799fc88d8-hdlgb 1/1 Running 0 12m
[root@master ~]# kubectl describe pod/nginx
Name: nginx
Namespace: default
Priority: 0
Node: node1/192.168.200.147
Start Time: Mon, 20 Dec 2021 04:59:44 -0500
Labels: app=v0.1
Annotations: <none>
Status: Running
IP: 10.244.1.3
IPs:
IP: 10.244.1.3
Containers:
nginx:
Container ID: docker://73856fde0c8aff5fb093053c334d41cf280a7ec532b6962505dcbde12ffe7623
Image: nginx
Image ID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 20 Dec 2021 04:59:46 -0500
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-4xgsw (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-4xgsw:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-4xgsw
Optional: false
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 38m default-scheduler Successfully assigned default/nginx to node1
Normal Pulling 38m kubelet Pulling image "nginx"
Normal Pulled 38m kubelet Successfully pulled image "nginx" in 1.144840659s
Normal Created 38m kubelet Created container nginx
Normal Started 38m kubelet Started container nginx
2.13 logs
查看日志
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 39m
nginx-6799fc88d8-2gxvq 1/1 Running 0 13m
nginx-6799fc88d8-cvwhq 1/1 Running 0 27m
nginx-6799fc88d8-hdlgb 1/1 Running 0 13m
[root@master ~]# kubectl logs nginx
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/12/20 09:59:47 [notice] 1#1: using the "epoll" event method
2021/12/20 09:59:47 [notice] 1#1: nginx/1.21.4
2021/12/20 09:59:47 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2021/12/20 09:59:47 [notice] 1#1: OS: Linux 4.18.0-193.el8.x86_64
2021/12/20 09:59:47 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 09:59:47 [notice] 1#1: start worker processes
2021/12/20 09:59:47 [notice] 1#1: start worker process 31
2021/12/20 09:59:47 [notice] 1#1: start worker process 32
2.14 attach
附加到pod内的一个容器
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 40m
nginx-6799fc88d8-2gxvq 1/1 Running 0 15m
nginx-6799fc88d8-cvwhq 1/1 Running 0 29m
nginx-6799fc88d8-hdlgb 1/1 Running 0 15m
[root@master ~]# kubectl attach nginx
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.
2.15 exec
// 从 pod 运行“date”命令获取输出,默认使用第一个容器
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 45m
nginx-6799fc88d8-2gxvq 1/1 Running 0 19m
nginx-6799fc88d8-cvwhq 1/1 Running 0 33m
nginx-6799fc88d8-hdlgb 1/1 Running 0 19m
[root@master ~]# kubectl exec nginx -- date
Mon Dec 20 10:45:14 UTC 2021
// 使用交互模式进入
[root@master ~]# kubectl exec -it nginx -- /bin/bash
root@nginx:/# ls
bin docker-entrypoint.d home media proc sbin tmp
boot docker-entrypoint.sh lib mnt root srv usr
dev etc lib64 opt run sys var
// svc
[root@master ~]# kubectl exec svc/nginx -- date
Mon Dec 20 10:46:49 UTC 2021
[root@master ~]# kubectl exec -it svc/nginx -- /bin/bash
root@nginx:/# ls
bin docker-entrypoint.d home media proc sbin tmp
boot docker-entrypoint.sh lib mnt root srv usr
dev etc lib64 opt run sys var
2.16 port-forward
转发端口
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 49m
nginx-6799fc88d8-2gxvq 1/1 Running 0 24m
nginx-6799fc88d8-cvwhq 1/1 Running 0 38m
nginx-6799fc88d8-hdlgb 1/1 Running 0 24m
[root@master ~]# kubectl port-forward deploy/nginx 80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80
//访问
[root@master ~]# curl 127.0.0.1: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>
// 监听所有地址的80端口,转发到 pod 中的80
[root@master ~]# kubectl port-forward --address 0.0.0.0 pod/nginx 80
Forwarding from 0.0.0.0:80 -> 80
[root@master ~]# ss -antl
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 128 0.0.0.0:30362 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.200.150:2379 0.0.0.0:*
LISTEN 0 128 127.0.0.1:2379 0.0.0.0:*
LISTEN 0 128 192.168.200.150:2380 0.0.0.0:*
LISTEN 0 128 127.0.0.1:2381 0.0.0.0:*
LISTEN 0 128 127.0.0.1:43245 0.0.0.0:*
LISTEN 0 128 0.0.0.0:80 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 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 *:10250 *:*
LISTEN 0 128 *:6443 *:*
LISTEN 0 128 *:10256 *:*
LISTEN 0 128 [::]:22 [::]:*
2.17 cp
复制
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx 1/1 Running 0 74m
nginx-6799fc88d8-2gxvq 1/1 Running 0 49m
nginx-6799fc88d8-cvwhq 1/1 Running 0 63m
nginx-6799fc88d8-hdlgb 1/1 Running 0 49m
[root@master ~]# kubectl exec nginx -- ls /tmp
[root@master ~]# kubectl cp /root/anaconda-ks.cfg nginx:/tmp
[root@master ~]# kubectl exec nginx -- ls /tmp
anaconda-ks.cfg
2.18 overwrite
覆盖
[root@master ~]# kubectl run nginx --image nginx --labels "app=test"
pod/nginx created
[root@master ~]# kubectl describe pod nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2/192.168.200.145
Start Time: Mon, 20 Dec 2021 06:25:06 -0500
Labels: app=test
Annotations: <none>
Status: Pending
IP:
IPs: <none>
Containers:
nginx:
Container ID:
Image: nginx
Image ID:
Port: <none>
Host Port: <none>
State: Waiting
Reason: ContainerCreating
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-4xgsw (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
default-token-4xgsw:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-4xgsw
Optional: false
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 8s default-scheduler Successfully assigned default/nginx to node2
Normal Pulling 7s kubelet Pulling image "nginx"
// 使用 app=test 覆盖掉原有的 app=nginx 标签
[root@master ~]# kubectl label pod nginx --overwrite app=amu
pod/nginx labeled
[root@master ~]# kubectl describe pod nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2/192.168.200.145
Start Time: Mon, 20 Dec 2021 06:25:06 -0500
Labels: app=amu
Annotations: <none>
Status: Running
IP: 10.244.2.5
IPs:
IP: 10.244.2.5
Containers:
nginx:
Container ID: docker://159a79200ed955e8d618aa5b38f46f5eea5cc41386208b5f8e4287e043f3be87
Image: nginx
Image ID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 20 Dec 2021 06:25:22 -0500
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-4xgsw (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-4xgsw:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-4xgsw
Optional: false
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 52s default-scheduler Successfully assigned default/nginx to node2
Normal Pulling 51s kubelet Pulling image "nginx"
Normal Pulled 36s kubelet Successfully pulled image "nginx" in 15.422883922s
Normal Created 36s kubelet Created container nginx
Normal Started 36s kubelet Started container nginx
2.19 label
标签
//添加标签
[root@master ~]# kubectl label pod nginx test1=zbc
pod/nginx labeled
[root@master ~]# kubectl describe pod nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2/192.168.200.145
Start Time: Mon, 20 Dec 2021 06:25:06 -0500
Labels: app=amu
test1=zbc
........
2.20 api-resources
查看api资源详细信息
[root@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
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
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/v1 true HorizontalPodAutoscaler
cronjobs cj batch/v1beta1 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/v1beta1 true EndpointSlice
events ev events.k8s.io/v1 true Event
ingresses ing extensions/v1beta1 true Ingress
flowschemas flowcontrol.apiserver.k8s.io/v1beta1 false FlowSchema
prioritylevelconfigurations flowcontrol.apiserver.k8s.io/v1beta1 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/v1beta1 true PodDisruptionBudget
podsecuritypolicies psp policy/v1beta1 false PodSecurityPolicy
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
storageclasses sc storage.k8s.io/v1 false StorageClass
volumeattachments storage.k8s.io/v1 false VolumeAttachment
2.21 api-versions
打印支持api的版本
[root@master ~]# kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1
coordination.k8s.io/v1beta1
discovery.k8s.io/v1beta1
events.k8s.io/v1
events.k8s.io/v1beta1
extensions/v1beta1
flowcontrol.apiserver.k8s.io/v1beta1
networking.k8s.io/v1
networking.k8s.io/v1beta1
node.k8s.io/v1
node.k8s.io/v1beta1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1