kubectl命令的使用、滚动更新以及回滚操作
查看kubectl使用的命令,以及用法
[root@master ~]# kubectl --help
kubectl controls the Kubernetes cluster manager.
Find more information at: https://kubernetes.io/docs/reference/kubectl/overview/
Basic Commands (Beginner):
create Create a resource from a file or from stdin.
expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service
run Run a particular image on the cluster //在集群中运行一个指定的镜像
set Set specific features on objects // 为objects设置一个指定的特征
Basic Commands (Intermediate):
explain Documentation of resources
get Display one or many resources //显示一个或者更多的resources
edit Edit a resource on the server // 在服务器上编辑一个资源
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
Deploy Commands:
rollout Manage the rollout of a resource
scale Set a new size for a Deployment, ReplicaSet or Replication Controller
autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController
Cluster Management Commands:
certificate Modify certificate resources. // 修改certificate
cluster-info Display cluster info
top Display Resource (CPU/Memory/Storage) usage.
cordon Mark node as unschedulable //标记node为不可以调度的,比如设置node1为不可调度,那么控制器就不会把pod调度到node1上运行
uncordon Mark node as schedulable // 标记 node 为 可以调度的,同理
drain Drain node in preparation for maintenance
taint Update the taints on one or more nodes // 更新一个或者多个 node 上的 taints(污点),就类似于一个标准,比如控制器要将某一个pod调度到某一个node上那么就看这个pod能不能达到这个taints
Troubleshooting and Debugging Commands:
describe Show details of a specific resource or group of resources // 显示一个指定 resource(资源) 或者 group 的资源详情
logs Print the logs for a container in a pod // 输出容器在 pod 中的日志
attach Attach to a running container // 附加一个容器到一个运行中的容器中
exec Execute a command in a container // 进入容器执行命令,如果只使用exec那么执行一条命令就退出,若exec -it 加上一个shell,那么就可以进入容器执行多条命令
port-forward Forward one or more local ports to a pod
proxy Run a proxy to the Kubernetes API server
cp Copy files and directories to and from containers.
auth Inspect authorization
debug Create debugging sessions for troubleshooting workloads and nodes
Advanced Commands:
diff Diff live version against would-be applied version
apply Apply a configuration to a resource by filename or stdin
patch Update field(s) of a resource
replace Replace a resource by filename or stdin
wait Experimental: Wait for a specific condition on one or many resources.
kustomize Build a kustomization target from a directory or a remote url.
Settings Commands:
label Update the labels on a resource // 更新在当前pod资源上的标签
annotate Update the annotations on a resource //更新一个资源上的注解
completion Output shell completion code for the specified shell (bash or zsh)
Other Commands:
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config Modify kubeconfig files // 修改 kubeconfig 文件
plugin Provides utilities for interacting with plugins.
version Print the client and server version information // 输出客户端 和服务端的版本信息
Usage:
kubectl [flags] [options]
Use "kubectl <command> --help" for more information about a given command.
Use "kubectl options" for a list of global command-line options (applies to all commands).
以下命令都可以使用kubectl get 命令,如kubectl get pod可以查看pod个数
// Namespaces:命令空间,将对象逻辑上隔离,也利于权限控制
// Service:为一组Pod提供负载均衡,对外提供一访问入口,可使用缩写 “svc”
// Deployment:最常见的控制器,用于更高级别部署和管理Pod
// Label:标签,附加到某个资源上,用于关联对象、查询和筛
kubectl get namespace获取kubenetes的名称空间
[root@master ~]# kubectl get namespace
NAME STATUS AGE
default Active 3d4h //默认的名称空间
kube-node-lease Active 3d4h //k8s系统方面的命名空间
kube-public Active 3d4h // 公开的命名空间,谁都可以访问
kube-system Active 3d4h // k8s内部的命名空间
// 查看指定的名称空间
[root@master ~]# kubectl get namespace -n kube-node-lease //使用-n
NAME STATUS AGE
default Active 3d4h
kube-node-lease Active 3d4h
kube-public Active 3d4h
kube-system Active 3d4h
1. kubectl命令的使用
1.1 explain命令
// 作用类似于官方文档
// 获取指定资源及其字段的参考信息
[root@master ~]# kubectl explain pod
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
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 <Object>
Standard object's metadata. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
spec <Object>
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
status <Object>
Most recently observed status of the pod. This data may not be up to date.
Populated by the system. Read-only. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// 获取资源特定字段的参考信息
[root@master ~]# kubectl explain pod.spec
[root@master ~]# kubectl explain pods.spec.containers
KIND: Pod
VERSION: v1
RESOURCE: containers <[]Object>
DESCRIPTION:
List of containers belonging to the pod. Containers cannot currently be
added or removed. There must be at least one container in a Pod. Cannot be
updated.
A single application container that you want to run within a pod.
FIELDS:
args <[]string>
Arguments to the entrypoint. The docker image's CMD is used if this is not
provided. Variable references $(VAR_NAME) are expanded using the
container's environment. If a variable cannot be resolved, the reference in
the input string will be unchanged. The $(VAR_NAME) syntax can be escaped
with a double $$, ie: $$(VAR_NAME). Escaped references will never be
expanded, regardless of whether the variable exists or not. Cannot be
updated. More info:
省略N行
1.2 edit命令
[root@master ~]# kubectl create deploy nginx --image nginx //创建一个deploy类型的pod
deployment.apps/nginx created
[root@master ~]# kubectl describe deploy nginx //查看详细deploy类型的nginx的信息
Name: nginx
Namespace: default
CreationTimestamp: Mon, 20 Dec 2021 18:43:32 +0800
Labels: app=nginx
Annotations: deployment.kubernetes.io/revision: 1
Selector: app=nginx
Replicas: 1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType: RollingUpdate
MinReadySeconds: 0
RollingUpdateStrategy: 25% max unavailable, 25% max surge
Pod Template:
Labels: app=nginx
Containers:
nginx:
Image: nginx
Port: <none>
Host Port: <none>
Environment: <none>
Mounts: <none>
Volumes: <none>
Conditions:
Type Status Reason
---- ------ ------
Available True MinimumReplicasAvailable
Progressing True NewReplicaSetAvailable
OldReplicaSets: <none>
NewReplicaSet: nginx-6799fc88d8 (1/1 replicas created)
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal ScalingReplicaSet 2m42s deployment-controller Scaled up replica set nginx-6799fc88d8 to 1
// 用edit命令来编辑deploy类型的nginx,这个类似于vim编辑器,退出命令使用ZZ
[root@master ~]# kubectl edit deploy 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: apps/v1
kind: Deployment
metadata:
annotations:
deployment.kubernetes.io/revision: "1"
creationTimestamp: "2021-12-20T10:43:32Z"
generation: 1
labels:
app: nginx //将app:nginx改为test
name: nginx
namespace: default
resourceVersion: "53971"
uid: 22d6104d-1076-4bd6-8188-81fd26689e41
spec:
progressDeadlineSeconds: 600
replicas: 1
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
imagePullPolicy: Always
name: nginx
resources: {}
"/tmp/kubectl-edit-ck7k9.yaml" 66L, 1773C
[root@master ~]# kubectl edit deploy nginx
deployment.apps/nginx edited
[root@master ~]# kubectl describe deploy nginx // 发现nginx改为了test
Name: nginx
Namespace: default
CreationTimestamp: Mon, 20 Dec 2021 18:43:32 +0800
Labels: app=test //修改成功
省略N行
1.3 scale命令
// 设置deployment等类型的pod的多少
[root@master ~]# kubectl scale deploy/nginx --replicas 3 //启动三个pod
deployment.apps/nginx scaled
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-jb6w4 1/1 Running 0 66s
nginx-6799fc88d8-s8mjh 1/1 Running 0 30m
nginx-6799fc88d8-t546q 1/1 Running 0 66s
[root@master ~]# kubectl scale --replicas 2 deploy/nginx
deployment.apps/nginx scaled //改为两个,然后就会自动删除一个
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-jb6w4 0/1 Terminating 0 4m32s
nginx-6799fc88d8-s8mjh 1/1 Running 0 33m
nginx-6799fc88d8-t546q 1/1 Running 0 4m32s
1.4 autoscale命令
kubectl autoscale deployment foo --min=2 --max=10 //格式
[root@master ~]# kubectl autoscale deploy nginx --min 2 --max=6 //自动扩展deploy类型的pod最少两个,最多六个
horizontalpodautoscaler.autoscaling/nginx autoscaled
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-s8mjh 1/1 Running 0 42m
nginx-6799fc88d8-t546q 1/1 Running 0 12m
[root@master ~]# kubectl scale deploy nginx --replicas 7
deployment.apps/nginx scaled //这里我们扩展7个
[root@master ~]# kubectl get pod //因为设置了最大的扩展数位6个,而我们扩展了7个超过了最大的扩展数,那么他会自动删除一个。
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-dsts7 0/1 Terminating 0 59s
nginx-6799fc88d8-f7nf7 1/1 Running 0 59s
nginx-6799fc88d8-gb9vp 1/1 Running 0 59s
nginx-6799fc88d8-lrl85 1/1 Running 0 59s
nginx-6799fc88d8-s8mjh 1/1 Running 0 44m
nginx-6799fc88d8-t546q 1/1 Running 0 15m
nginx-6799fc88d8-wmkxr 1/1 Running 0 59s
1.5 replicas命令
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-f7nf7 1/1 Running 1 94m
nginx-6799fc88d8-gb9vp 1/1 Running 1 94m
nginx-6799fc88d8-lrl85 1/1 Running 1 94m
nginx-6799fc88d8-s8mjh 1/1 Running 1 138m
nginx-6799fc88d8-t546q 1/1 Running 1 109m
nginx-6799fc88d8-wmkxr 1/1 Running 1 94m
[root@master ~]# kubectl create deploy test --image nginx --replicas 3
deployment.apps/test created
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-f7nf7 1/1 Running 1 102m
nginx-6799fc88d8-gb9vp 1/1 Running 1 102m
nginx-6799fc88d8-lrl85 1/1 Running 1 102m
nginx-6799fc88d8-s8mjh 1/1 Running 1 146m
nginx-6799fc88d8-t546q 1/1 Running 1 117m
nginx-6799fc88d8-wmkxr 1/1 Running 1 102m
test-5f6778868d-5lcx5 1/1 Running 0 61s //我们可以看到随机替换了三个pod
test-5f6778868d-k6bwb 1/1 Running 0 61s
test-5f6778868d-lt9v2 1/1 Running 0 61s
1.6 cluster-info命令
// 显示集群信息
[root@master ~]# kubectl cluster-info
Kubernetes control plane is running at https://192.168.182.150:6443
KubeDNS is running at https://192.168.182.150:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy //DNS运行的地方
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
1.7 cordon命令
// 标记某个节点为不可调度,就只能调度到另一个节点
[root@master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
master.example.com Ready control-plane,master 3d2h v1.20.0
node1.example.com Ready <none> 3d1h v1.20.0
node2.example.com Ready <none> 3d1h v1.20.0
[root@master ~]# kubectl cordon node2.example.com //设置node2为不可调度
[root@master ~]# kubectl get node
NAME STATUS ROLES AGE VERSION
master.example.com Ready control-plane,master 3d2h v1.20.0
node1.example.com Ready <none> 3d1h v1.20.0
node2.example.com Ready,SchedulingDisabled <none> 3d1h v1.20.0 // 发现node2节点被关闭了
[root@master ~]# kubectl create deploy web --image nginx --replicas 3
deployment.apps/web created
[root@master ~]# kubectl get pod -o wide // 发现这三个pod只运行在node1上,不会影响之前创建的pod
web-96d5df5c8-5h54g 1/1 Running 0 74s 10.244.1.25 node1.example.com <none> <none>
web-96d5df5c8-bnl2d 1/1 Running 0 74s 10.244.1.24 node1.example.com <none> <none>
web-96d5df5c8-fzrld 1/1 Running 0 74s 10.244.1.26 node1.example.com <none> <none>
1.8 uncordon命令
// 设置为可以调度的
[root@master ~]# kubectl uncordon node2.example.com
node/node2.example.com uncordoned
[root@master ~]# kubectl get node // 恢复成为可以调度的
NAME STATUS ROLES AGE VERSION
master.example.com Ready control-plane,master 3d2h v1.20.0
node1.example.com Ready <none> 3d1h v1.20.0
node2.example.com Ready <none> 3d1h v1.20.0
// 以json格式显示输出内容
[root@master ~]# kubectl get deploy nginx -o json //将json换成yaml,就会以yaml文件格式输出
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"annotations": {
"deployment.kubernetes.io/revision": "1"
},
"creationTimestamp": "2021-12-20T10:43:32Z",
"generation": 5,
"labels": {
"app": "test"
},
"managedFields": [
{
"apiVersion": "apps/v1",
"fieldsType": "FieldsV1",
"fieldsV1": {
"f:metadata": {
"f:labels": {
".": {},
"f:app": {}
}
},
"f:spec": {
"f:progressDeadlineSeconds": {},
"f:replicas": {},
"f:revisionHistoryLimit": {},
"f:selector": {},
"f:strategy": {
"f:rollingUpdate": {
".": {},
"f:maxSurge": {},
"f:maxUnavailable": {}
},
"f:type": {}
省略N行
1.9 taint命令
// 这就是为什么master上没有pod的原因
[root@master ~]# kubectl describe node master.example.com | grep Taints //描述master节点的信息
Taints: node-role.kubernetes.io/master:NoSchedule // 发现master节点不允许被调度
kubectl taint nodes foo dedicated=special-user:NoSchedule //格式
[root@master ~]# kubectl taint --help //更多用法详见此命令
1.10 decribe命令
[root@master ~]# kubectl describe pod // 描述pod的信息
Name: nginx-6799fc88d8-f7nf7
Namespace: default
Priority: 0
Node: node1.example.com/192.168.182.151
Start Time: Mon, 20 Dec 2021 19:27:23 +0800
Labels: app=nginx
pod-template-hash=6799fc88d8
Annotations: <none>
Status: Running
IP: 10.244.1.19
IPs:
IP: 10.244.1.19
Controlled By: ReplicaSet/nginx-6799fc88d8
Containers:
nginx:
Container ID: docker://3f76599d9f3347b23b28a511eeb014b0a62ea6c39c6dc0366380a4bf32423efe
Image: nginx
Image ID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 20 Dec 2021 20:39:20 +0800
省略N行
[root@master ~]# kubectl get pod //描述pod下的某一个容器的信息
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-f7nf7 1/1 Running 1 160m
nginx-6799fc88d8-gb9vp 1/1 Running 1 160m
nginx-6799fc88d8-lrl85 1/1 Running 1 160m
nginx-6799fc88d8-s8mjh 1/1 Running 1 3h24m
nginx-6799fc88d8-t546q 1/1 Running 1 175m
nginx-6799fc88d8-wmkxr 1/1 Running 1 160m
[root@master ~]# kubectl describe pods/nginx-6799fc88d8-f7nf7
Name: nginx-6799fc88d8-f7nf7
Namespace: default
Priority: 0
Node: node1.example.com/192.168.182.151
Start Time: Mon, 20 Dec 2021 19:27:23 +0800
Labels: app=nginx
pod-template-hash=6799fc88d8
Annotations: <none>
Status: Running
IP: 10.244.1.19
IPs:
IP: 10.244.1.19
Controlled By: ReplicaSet/nginx-6799fc88d8
Containers:
nginx:
Container ID: docker://3f76599d9f3347b23b28a511eeb014b0a62ea6c39c6dc0366380a4bf32423efe
Image: nginx
Image ID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Port: <none>
Host Port: <none>
State: Running
Started: Mon, 20 Dec 2021 20:39:20 +0800
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Mon, 20 Dec 2021 19:27:47 +0800
Finished: Mon, 20 Dec 2021 19:30:12 +0800
省略N行
1.11 logs命令
[root@master ~]# kubectl logs deployment/nginx //查看deployment下的nginx的日志信息
Found 6 pods, using pod/nginx-6799fc88d8-wmkxr
/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 12:39:07 [notice] 1#1: using the "epoll" event method
2021/12/20 12:39:07 [notice] 1#1: nginx/1.21.4
2021/12/20 12:39:07 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2021/12/20 12:39:07 [notice] 1#1: OS: Linux 4.18.0-257.el8.x86_64
2021/12/20 12:39:07 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/20 12:39:07 [notice] 1#1: start worker processes
2021/12/20 12:39:07 [notice] 1#1: start worker process 31
2021/12/20 12:39:07 [notice] 1#1: start worker process 32
1.12 attach命令
[root@master ~]# kubectl get pod //进入容器,但是会占用前台
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-9vc8j 1/1 Running 0 86s
nginx-6799fc88d8-fzvsb 1/1 Running 0 88s
[root@master ~]# kubectl attach pod nginx-6799fc88d8-9vc8j
Defaulting container name to nginx.
Use 'kubectl describe pod/nginx-6799fc88d8-9vc8j -n default' to see all of the containers in this pod.
If you don't see a command prompt, try pressing enter.
[root@master ~]# kubectl get pod -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-6799fc88d8-9vc8j 1/1 Running 0 2m31s 10.244.1.30 node1.example.com <none> <none>
nginx-6799fc88d8-fzvsb 1/1 Running 0 2m33s 10.244.2.19 node2.example.com <none> <none>
[root@master ~]# curl 10.244.1.30 //访问容器
<!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>
1.13 exec命令
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-6799fc88d8-9vc8j 1/1 Running 0 4m41s
nginx-6799fc88d8-fzvsb 1/1 Running 0 4m43s
[root@master ~]# kubectl exec pods/nginx-6799fc88d8-9vc8j -- ls //不进入容器执行命令
bin
boot
dev
docker-entrypoint.d
docker-entrypoint.sh
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
[root@master ~]# kubectl exec -it pods/nginx-6799fc88d8-9vc8j -- /bin/sh //进入容器执行命令
# cd /lib
# ls
init lsb systemd terminfo udev x86_64-linux-gnu
1.14 port-forward命令
// 转发端口号
[root@master ~]# kubectl port-forward pod/nginx 80 //将pod下的nginx的80端口号转发,但是会一直占用前台
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80
[root@master ~]# ss -anlt | grep -w 80
LISTEN 0 128 127.0.0.1:80 0.0.0.0:*
LISTEN 0 128 [::1]:80 [::]:*
[root@master ~]# curl 127.0.0.1 //访问成功
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
[root@master ~]# kubectl port-forward --address 0.0.0.0 pod/nginx 80 //将80端口号转到所有主机上,这时我们就可以通过浏览器进行访问了
Forwarding from 0.0.0.0:80 -> 80
[root@master ~]# ss -anlt| grep -w 80
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
[root@master ~]# kubectl port-forward --address 0.0.0.0 pod/nginx :80 //将容器中的80端口号随机映射到宿主机上
Forwarding from 0.0.0.0:36663 -> 80 //随机成36663
[root@master ~]# kubectl port-forward --address 0.0.0.0 pod/nginx 666:80
Forwarding from 0.0.0.0:666 -> 80 //将容器中的80映射到宿主机上的666端口号
[root@master ~]# ss -anlt | grep -w 666
LISTEN 0 128 0.0.0.0:666 0.0.0.0:*
1.15 cp命令
// 让pod和宿主机之间可以相互传文件
[root@master ~]# kubectl exec nginx -- ls /tmp //在nginx的pod下是没有东西的
[root@master ~]# ls
anaconda-ks.cfg k8s kube-flannel.yml
[root@master ~]# kubectl cp k8s nginx:/tmp
[root@master ~]# kubectl exec nginx -- ls /tmp
k8s
1.16 label命令
// 为pod打标签
[root@master ~]# kubectl describe pods nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2.example.com/192.168.182.152
Start Time: Mon, 20 Dec 2021 22:48:29 +0800
Labels: run=nginx //可以看到我们现在只有一个标签
[root@master ~]# kubectl label pods nginx appp=nginx //为nginx这个pod添加一个标签
pod/nginx labeled
[root@master ~]# kubectl describe pods nginx //发现多了一个标签
Name: nginx
Namespace: default
Priority: 0
Node: node2.example.com/192.168.182.152
Start Time: Mon, 20 Dec 2021 22:48:29 +0800
Labels: appp=nginx
run=nginx
// 修改pod标签
[root@master ~]# kubectl label --overwrite pods nginx appp=test
pod/nginx labeled
[root@master ~]# kubectl label --overwrite pods nginx appp=test //修改成功
pod/nginx labeled
[root@master ~]# kubectl describe pods nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2.example.com/192.168.182.152
Start Time: Mon, 20 Dec 2021 22:48:29 +0800
Labels: appp=test
run=nginx
1.17 Annotations命令
[root@master ~]# kubectl describe pods nginx
Name: nginx
Namespace: default
Priority: 0
Node: node2.example.com/192.168.182.152
Start Time: Mon, 20 Dec 2021 22:48:29 +0800
Labels: appp=test
run=nginx
Annotations: <none> //用来修改此处
1.18 api-resources命令
[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 //可以看到service的简称为svc
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
1.19 api-versions命令
[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
1.20 version命令
[root@master ~]# kubectl version //查看kubernetes的版本信息
Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:59:43Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:51:19Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
1.21 rollout命令
// 用来回滚
// 首先使用docker创建一个容器
[root@master ~]# docker run -it busybox /bin/sh
// 创建一个dockerfile
[root@master ~]# mkdir web
[root@master ~]# cd web/
[root@master web]# vim Dockerfile
[root@master web]# cat Dockerfile //运行一个apache
FROM busybox
RUN mkdir /data && \
echo "the is test1" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master web]# docker build -t httpd:v1.0 .
Sending build context to Docker daemon 2.048kB
Step 1/3 : FROM busybox
---> ffe9d497c324
Step 2/3 : RUN mkdir /data && echo "the is test1" > /data/index.html
---> Running in 375f09dc938f
Removing intermediate container 375f09dc938f
---> 641265889cb7
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
---> Running in 18129bb02245
Removing intermediate container 18129bb02245
---> 0e094471efb7
Successfully built 0e094471efb7
Successfully tagged httpd:v1.0
[root@master web]# cat Dockerfile // 再写一个Dockerfile
FROM busybox
RUN mkdir /data && \
echo "the is test2" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master web]# docker tag httpd:v1.0 dockerimages123/httpd:v0.1 //修改镜像名称
[root@master web]# docker tag httpd:v2.0 dockerimages123/httpd:v2.0
[root@master web]# docker push dockerimages123/httpd:v0.1
[root@master web]# docker push dockerimages123/httpd:v2.0
[root@master web]# kubectl create deploy httpd --image dockerimages123/httpd:v0.1 --replicas 3
deployment.apps/httpd created
[root@master web]# kubectl expose deploy httpd --port 80 --type NodePort
service/httpd exposed
[root@master web]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
httpd NodePort 10.103.118.88 <none> 80:31967/TCP 25s
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d5h
nginx ClusterIP 10.105.50.111 <none> 8080/TCP 100m
[root@master web]# curl 10.103.118.88
the is test1
[root@master web]# kubectl set image deploy/httpd httpd=dockerimages123/httpd:v2.0
deployment.apps/httpd image updated
[root@master ~]# kubectl get pod //这时他就会创建一个新的删除一个旧的
NAME READY STATUS RESTARTS AGE
httpd-54c5b7b59d-249zk 1/1 Running 0 9m1s
httpd-54c5b7b59d-b2w4m 1/1 Running 0 9m1s
httpd-54c5b7b59d-xt6mw 1/1 Terminating 0 9m1s
httpd-56b8d65fff-6j5r5 1/1 Running 0 30s
httpd-56b8d65fff-hldgb 0/1 ContainerCreating 0 3s
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
httpd NodePort 10.103.118.88 <none> 80:31967/TCP 9m20s
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d5h
nginx ClusterIP 10.105.50.111 <none> 8080/TCP 109m
[root@master ~]# curl 10.103.118.88
the is test2
[root@master web]# kubectl set image deploy/httpd httpd=dockerimages123/httpd:v0.1
deployment.apps/httpd image updated
[root@master ~]# curl 10.103.118.88
the is test1
[root@master ~]# kubectl rollout undo deploy/httpd //回滚操作
deployment.apps/httpd rolled back
[root@master ~]# curl 10.103.118.88 //变成了test2
the is test2
// 回滚到指定版本
kubectl rollout undo daemonset/abc --to-revision=3 //因为这里是使用docker创建的容器做的测试所以无法指定版本,需要用kubectl创建的pod才可以