kubernetes常用命令
kubernetes常用命令查看类kubectl describe nodes <node-name> (容器名)显示Node的详细信息[root@master ~]# kubectl describe nodes node01Name:node01//nodemingziRoles:<none>Labels:beta.kubernetes.io/arch=amd64//标
kubernetes常用命令
帮助类
kubectl --help
查看帮助文档
[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 在集群中运行一个指定的镜像
set 为 objects 设置一个指定的特征
Basic Commands (Intermediate):
explain Get documentation for a resource
get 显示一个或更多 resources
edit 在服务器上编辑一个资源
delete Delete resources by file names, 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, replica set, or replication controller
autoscale Auto-scale a deployment, replica set, stateful set, or replication controller
Cluster Management Commands:
certificate 修改 certificate 资源.
cluster-info Display cluster information
top Display resource (CPU/memory) usage
cordon 标记 node 为 unschedulable
uncordon 标记 node 为 schedulable
drain Drain node in preparation for maintenance
taint 更新一个或者多个 node 上的 taints
Troubleshooting and Debugging Commands:
describe 显示一个指定 resource 或者 group 的 resources 详情
logs 输出容器在 pod 中的日志
attach Attach 到一个运行中的 container
exec 在一个 container 中执行一个命令
port-forward Forward one or more local ports to a pod
proxy 运行一个 proxy 到 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 the live version against a would-be applied version
apply Apply a configuration to a resource by file name or stdin
patch Update fields of a resource
replace Replace a resource by file name or stdin
wait Experimental: Wait for a specific condition on one or many resources
kustomize Build a kustomization target from a directory or URL.
Settings Commands:
label 更新在这个资源上的 labels
annotate 更新一个资源的注解
completion Output shell completion code for the specified shell (bash, zsh or fish)
Other Commands:
alpha Commands for features in alpha
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 修改 kubeconfig 文件
plugin Provides utilities for interacting with plugins
version 输出 client 和 server 的版本信息
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 describe nodes <node-name> (容器名)
显示Node的详细信息
[root@master ~]# kubectl describe nodes node01
Name: node01 //nodemingzi
Roles: <none>
Labels: beta.kubernetes.io/arch=amd64 //标签
beta.kubernetes.io/os=linux
kubernetes.io/arch=amd64
kubernetes.io/hostname=node01
kubernetes.io/os=linux
Annotations: flannel.alpha.coreos.com/backend-data: {"VNI":1,"VtepMAC":"c2:52:cd:d7:02:e6"} // 注释,node节点中的运行内容
flannel.alpha.coreos.com/backend-type: vxlan
flannel.alpha.coreos.com/kube-subnet-manager: true
flannel.alpha.coreos.com/public-ip: 192.168.58.111
kubeadm.alpha.kubernetes.io/cri-socket: /var/run/dockershim.sock
node.alpha.kubernetes.io/ttl: 0
volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp: Sun, 19 Dec 2021 11:45:19 +0800
Taints: <none>
Unschedulable: false
Lease:
HolderIdentity: node01
AcquireTime: <unset>
RenewTime: Sun, 19 Dec 2021 16:48:22 +0800
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
NetworkUnavailable False Sun, 19 Dec 2021 15:34:27 +0800 Sun, 19 Dec 2021 15:34:27 +0800 FlannelIsUp Flannel is running on this node
MemoryPressure False Sun, 19 Dec 2021 16:44:59 +0800 Sun, 19 Dec 2021 15:27:24 +0800 KubeletHasSufficientMemory kubelet has sufficient memory available
DiskPressure False Sun, 19 Dec 2021 16:44:59 +0800 Sun, 19 Dec 2021 15:27:24 +0800 KubeletHasNoDiskPressure kubelet has no disk pressure
PIDPressure False Sun, 19 Dec 2021 16:44:59 +0800 Sun, 19 Dec 2021 15:27:24 +0800 KubeletHasSufficientPID kubelet has sufficient PID available
Ready True Sun, 19 Dec 2021 16:44:59 +0800 Sun, 19 Dec 2021 15:27:34 +0800 KubeletReady kubelet is posting ready status
Addresses:
InternalIP: 192.168.58.111
Hostname: node01
Capacity:
cpu: 1
ephemeral-storage: 27245572Ki
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 7992312Ki
pods: 110
Allocatable:
cpu: 1
ephemeral-storage: 25109519114
hugepages-1Gi: 0
hugepages-2Mi: 0
memory: 7889912Ki
pods: 110
System Info:
Machine ID: e56ee742b69b4876a35bdc0651aee1d0
System UUID: 2D874D56-4EFA-F3D4-0583-ED563F229782
Boot ID: 7fd5b2a7-cdab-46fd-8374-bdbf2d68eb3b
Kernel Version: 3.10.0-862.el7.x86_64
OS Image: CentOS Linux 7 (Core)
Operating System: linux
Architecture: amd64
Container Runtime Version: docker://20.10.12
Kubelet Version: v1.23.1
Kube-Proxy Version: v1.23.1
PodCIDR: 10.244.1.0/24
PodCIDRs: 10.244.1.0/24
Non-terminated Pods: (3 in total)
Namespace Name CPU Requests CPU Limits Memory Requests Memory Limits Age
--------- ---- ------------ ---------- --------------- ------------- ---
default nginx-85b98978db-ztswj 0 (0%) 0 (0%) 0 (0%) 0 (0%) 4h56m
kube-system kube-flannel-ds-cml89 100m (10%) 100m (10%) 50Mi (0%) 50Mi (0%) 5h
kube-system kube-proxy-mdpqk 0 (0%) 0 (0%) 0 (0%) 0 (0%) 5h3m
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 100m (10%) 100m (10%)
memory 50Mi (0%) 50Mi (0%)
ephemeral-storage 0 (0%) 0 (0%)
hugepages-1Gi 0 (0%) 0 (0%)
hugepages-2Mi 0 (0%) 0 (0%)
Events: <none>
kubectl describe pods/<pod-name>
显示Pod的详细信息
[root@master ~]# kubectl describe pods
Name: nginx-85b98978db-ztswj // pod名
Namespace: default //命名空间,默认
Priority: 0
Node: node01/192.168.58.111 //在那个节点上
Start Time: Sun, 19 Dec 2021 11:52:02 +0800
Labels: app=nginx //标签
pod-template-hash=85b98978db
Annotations: <none>
Status: Running // 状态
IP: 10.244.1.3
IPs:
IP: 10.244.1.3
Controlled By: ReplicaSet/nginx-85b98978db
Containers:
nginx:
Container ID: docker://504255fdc82708cdcbab703f3b33aea1e361260616bb195d62a6311a40171b86
Image: nginx //镜像
Image ID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
Port: <none>
Host Port: <none>
State: Running
Started: Sun, 19 Dec 2021 15:34:37 +0800
Last State: Terminated
Reason: Completed
Exit Code: 0
Started: Sun, 19 Dec 2021 11:52:29 +0800
Finished: Sun, 19 Dec 2021 15:25:30 +0800
Ready: True
Restart Count: 1
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-4fbrd (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-4fbrd:
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: <none>
kubectl get pods -o wide
查看pods所在的运行节点
[root@master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-85b98978db-ztswj 1/1 Running 1 (91m ago) 5h5m 10.244.1.3 node01 <none> <none>
kubectl get pods --all-namespaces
查看所有namespace的pods运行情况
[root@master ~]# kubectl get pods --all-namespaces
NAMESPACE NAME READY STATUS RESTARTS AGE
default nginx-85b98978db-ztswj 1/1 Running 1 (92m ago) 5h6m
kube-system coredns-6d8c4cb4d-4hhmj 1/1 Running 2 (83m ago) 5h17m
kube-system coredns-6d8c4cb4d-zpcsl 1/1 Running 2 (83m ago) 5h17m
kube-system etcd-master 1/1 Running 2 (83m ago) 5h18m
kube-system kube-apiserver-master 1/1 Running 2 (83m ago) 5h18m
kube-system kube-controller-manager-master 1/1 Running 2 (83m ago) 5h18m
kube-system kube-flannel-ds-cml89 1/1 Running 6 (86m ago) 5h10m
kube-system kube-flannel-ds-s6rbl 1/1 Running 3 (83m ago) 5h10m
kube-system kube-flannel-ds-xmw4r 1/1 Running 1 (92m ago) 5h10m
kube-system kube-proxy-mdpqk 1/1 Running 1 (92m ago) 5h13m
kube-system kube-proxy-t7lm5 1/1 Running 2 (83m ago) 5h17m
kube-system kube-proxy-xkctb 1/1 Running 1 (92m ago) 5h13m
kube-system kube-scheduler-master 1/1 Running 2 (83m ago) 5h18m
kubectl get pods -o yaml
查看pods定义的详细信息
[root@master ~]# kubectl get pods -o yaml
apiVersion: v1
items:
- apiVersion: v1
kind: Pod
metadata:
creationTimestamp: "2021-12-19T03:52:02Z"
generateName: nginx-85b98978db-
labels:
app: nginx
pod-template-hash: 85b98978db
name: nginx-85b98978db-ztswj
namespace: default
ownerReferences:
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet
name: nginx-85b98978db
uid: 26b61a08-9f4b-4ae4-bd8c-e7a4c5ec6e23
resourceVersion: "4041"
uid: d0e29391-b1ae-4cab-8cdf-4450b923a095
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /var/run/secrets/kubernetes.io/serviceaccount
name: kube-api-access-4fbrd
readOnly: true
dnsPolicy: ClusterFirst
enableServiceLinks: true
nodeName: node01
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: kube-api-access-4fbrd
projected:
defaultMode: 420
sources:
- serviceAccountToken:
expirationSeconds: 3607
path: token
- configMap:
items:
- key: ca.crt
path: ca.crt
name: kube-root-ca.crt
- downwardAPI:
items:
- fieldRef:
apiVersion: v1
fieldPath: metadata.namespace
path: namespace
status:
conditions:
- lastProbeTime: null
lastTransitionTime: "2021-12-19T03:52:02Z"
status: "True"
type: Initialized
- lastProbeTime: null
lastTransitionTime: "2021-12-19T07:34:38Z"
status: "True"
type: Ready
- lastProbeTime: null
lastTransitionTime: "2021-12-19T07:34:38Z"
status: "True"
type: ContainersReady
- lastProbeTime: null
lastTransitionTime: "2021-12-19T03:52:02Z"
status: "True"
type: PodScheduled
containerStatuses:
- containerID: docker://504255fdc82708cdcbab703f3b33aea1e361260616bb195d62a6311a40171b86
image: nginx:latest
imageID: docker-pullable://nginx@sha256:9522864dd661dcadfd9958f9e0de192a1fdda2c162a35668ab6ac42b465f0603
lastState:
terminated:
containerID: docker://501a3c850653b2261c8c279db3ef86beef811a60b7f59e0ec9688af274ff758a
exitCode: 0
finishedAt: "2021-12-19T07:25:30Z"
reason: Completed
startedAt: "2021-12-19T03:52:29Z"
name: nginx
ready: true
restartCount: 1
started: true
state:
running:
startedAt: "2021-12-19T07:34:37Z"
hostIP: 192.168.58.111
phase: Running
podIP: 10.244.1.3
podIPs:
- ip: 10.244.1.3
qosClass: BestEffort
startTime: "2021-12-19T03:52:02Z"
kind: List
metadata:
resourceVersion: ""
selfLink: ""
kubectl get cs
查看集群健康状态
[root@master ~]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME STATUS MESSAGE ERROR
controller-manager Healthy ok
scheduler Healthy ok
etcd-0 Healthy {"health":"true","reason":""}
kubectl get rc,svc
查看rc和servers
[root@master ~]# kubectl get rc,svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5h20m
service/nginx NodePort 10.96.49.203 <none> 80:30617/TCP 5h9m
kubectl get deployments
查看应用的副本数
[root@master ~]# kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE
nginx 1/1 1 1 5h10m
kubectl exec pod名称 env
查看运行的pod的环境变量信息
[root@master ~]# kubectl exec nginx-85b98978db-ztswj env
HOSTNAME=nginx-85b98978db-ztswj
NGINX_PORT_80_TCP=tcp://10.96.49.203:80
NGINX_PORT=tcp://10.96.49.203:80
NGINX_PORT_80_TCP_PROTO=tcp
KUBERNETES_SERVICE_HOST=10.96.0.1
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_PORT_HTTPS=443
KUBERNETES_PORT=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443
KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_PORT_443_TCP_PORT=443
NGINX_SERVICE_HOST=10.96.49.203
NGINX_SERVICE_PORT=80
NGINX_PORT_80_TCP_PORT=80
NGINX_PORT_80_TCP_ADDR=10.96.49.203
NGINX_VERSION=1.21.4
NJS_VERSION=0.7.0
PKG_RELEASE=1~bullseye
HOME=/root
kubectl logs pod名称
查看pod日志
[root@master ~]# kubectl logs nginx-85b98978db-ztswj
/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/19 07:34:38 [notice] 1#1: using the "epoll" event method
2021/12/19 07:34:38 [notice] 1#1: nginx/1.21.4
2021/12/19 07:34:38 [notice] 1#1: built by gcc 10.2.1 20210110 (Debian 10.2.1-6)
2021/12/19 07:34:38 [notice] 1#1: OS: Linux 3.10.0-862.el7.x86_64
2021/12/19 07:34:38 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/19 07:34:38 [notice] 1#1: start worker processes
2021/12/19 07:34:38 [notice] 1#1: start worker process 32
kubectl get deployment --all-namespaces
获取所有deployment
[root@master ~]# kubectl get deployment --all-namespaces
NAMESPACE NAME READY UP-TO-DATE AVAILABLE AGE
default nginx 1/1 1 1 5h15m
kube-system coredns 2/2 2 2 5h26m
集群类
kubectl get cs
集群健康情况
[root@master ~]# kubectl get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-0 Healthy {"health":"true","reason":""}
kubectl cluster-info
集群核心组件运行情况
[root@master ~]# kubectl cluster-info
Kubernetes control plane is running at https://192.168.58.110:6443
CoreDNS is running at https://192.168.58.110:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
kubectl get namespaces
命名空间
[root@master ~]# kubectl get namespaces
NAME STATUS AGE
default Active 5h30m
kube-node-lease Active 5h30m
kube-public Active 5h30m
kube-system Active 5h30m
kubectl version
获取版本信息
[root@master ~]# kubectl version
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.1", GitCommit:"86ec240af8cbd1b60bcc4c03c20da9b98005b92e", GitTreeState:"clean", BuildDate:"2021-12-16T11:41:01Z", GoVersion:"go1.17.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.1", GitCommit:"86ec240af8cbd1b60bcc4c03c20da9b98005b92e", GitTreeState:"clean", BuildDate:"2021-12-16T11:34:54Z", GoVersion:"go1.17.5", Compiler:"gc", Platform:"linux/amd64"}
kubectl get nodes
获取全部节点信息
[root@master ~]# kubectl get nodes
NAME STATUS ROLES AGE VERSION
master Ready control-plane,master 5h31m v1.23.1
node01 Ready <none> 5h26m v1.23.1
node02 Ready <none> 5h26m v1.23.1
kubectl create
创建
[root@master ~]# kubectl create deployment kubernetes-bootcamp --image=gcr.io/google-samples/kubernetes-bootcamp:v1
deployment.apps/kubernetes-bootcamp created
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ContainerCreating 0 15s
# sleep:延迟
[root@master ~]# kubectl create deployment b2 --image busybox -- slepp 6000
deployment.apps/b2 created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
b2-866876dc6f-nllzq 0/1 ContainerCreating 0 7s
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 15m
# replicas:复制
[root@master ~]# kubectl create deployment myapp --image nginx --replicas 3
deployment.apps/myapp created
[root@master ~]# kubectl get pods //此时pod状态中有三个为myapp
NAME READY STATUS RESTARTS AGE
b2-866876dc6f-nllzq 0/1 CrashLoopBackOff 1 (28s ago) 66s
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 16m
myapp-d56b9c6b9-52gkx /1 ContainerCreating 0 2s
myapp-d56b9c6b9-czs4j 1/1 ContainerCreating 0 2s
myapp-d56b9c6b9-f7wm4 0/1 ContainerCreating 0 2s
# port:指定端口
[root@master ~]# kubectl create deployment web --image nginx --port 8080
deployment.apps/web created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
b2-866876dc6f-nllzq 0/1 CrashLoopBackOff 2 (2m5s ago) 3m14s
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 18m
myapp-d56b9c6b9-52gkx 1/1 Running 0 2m10s
myapp-d56b9c6b9-czs4j 1/1 Running 0 2m10s
myapp-d56b9c6b9-f7wm4 1/1 ContainerCreating 0 2m10s
nginx-85b98978db-ztswj 1/1 Running 1 (134m ago) 5h47m
nginx-app 1/1 Running 0 16m
web-64c55fd557-9vw6v 1/1 ContainerCreating 0 7s
# 查看正在运行pod节点
[root@master ~]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
b2-866876dc6f-nllzq 1/1 CrashLoopBackOff 4 (88s ago) 6m34s 10.244.2.4 node02 <none> <none>
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 22m 10.244.2.3 node02 <none> <none>
myapp-d56b9c6b9-52gkx 1/1 Running 0 5m30s 10.244.1.6 node01 <none> <none>
myapp-d56b9c6b9-czs4j 1/1 Running 0 5m30s 10.244.1.5 node01 <none> <none>
myapp-d56b9c6b9-f7wm4 1/1 Running 0 5m30s 10.244.2.5 node02 <none> <none>
nginx-85b98978db-ztswj 1/1 Running 1 (137m ago) 5h51m 10.244.1.3 node01 <none> <none>
nginx-app 1/1 Running 0 20m 10.244.1.4 node01 <none> <none>
web-64c55fd557-9vw6v 1/1 Running 0 3m27s 10.244.1.7 node01
kubectl expose
给指定pod暴露端口
[root@master ~]# kubectl get deployment
NAME READY UP-TO-DATE AVAILABLE AGE
b2 1/1 1 0 14m
kubernetes-bootcamp 1/1 1 0 30m
myapp 3/3 3 3 13m
nginx 1/1 1 1 5h59m
web 1/1 1 1 11m
# port 是service暴露在Cluster上的端口
# --target-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 6h11m
nginx NodePort 10.96.49.203 <none> 80:30617/TCP 5h59m
web ClusterIP 10.108.175.106 <none> 8080/TCP 21s
[root@master ~]# curl 10.108.175.106:8080 //访问测试, 此时只能在虚拟机中访问无法在主机上访问
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
[root@master ~]# curl 192.168.58.110:8080
curl: (7) Failed connect to 192.168.58.110:8080; 拒绝连接
# NodePort:可以随机暴露出一个端口外部访问的端口(默认值:30000-32767)出来。由于暴露的端口往往都比较大,这时候可以采用nginx反向代理的方式,为外界提供访问服务(HTTP:80,HTTPS:443)。
[root@master ~]# kubectl expose deployment myapp --port 80 --type NodePort
service/myapp exposed // 我们将type是指为 nodeport 模式,将pod的80端口映射到主机上
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6h15m
myapp NodePort 10.103.174.152 <none> 80:30235/TCP 9s
nginx NodePort 10.96.49.203 <none> 80:30617/TCP 6h3m
web ClusterIP 10.108.175.106 <none> 8080/TCP 4m29s
此时主机ip:30235时则能够正常访问
kubectl run
- --labels 指定标签
- --dry-run
- -it 交互
[root@master ~]# kubectl run nginx --image nginx --labels "test=nginx" //指定标签
pod/nginx created
[root@master ~]# kubectl describe pod nginx
Name: nginx
Namespace: default
Priority: 0
Node: node02/192.168.58.125
Start Time: Sun, 19 Dec 2021 18:25:36 +0800
Labels: test=nginx //此处显示
Annotations: <none>
Status: Pending
IP:
IPs: <none>
# 使用-- dry-run 选项
[root@master ~]# kubectl run nginx --image nginx --dry-run abc
W1219 18:28:28.211244 67013 helpers.go:598] --dry-run is deprecated and can be replaced with --dry-run=client.
pod/nginx created (dry run)
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
No resources found in default namespace.
# -it 交互
[root@master ~]# kubectl run -i -t busybox --image=busybox --restart=Never
If you don't see a command prompt, try pressing enter.
/ #
/ # ls
bin dev etc home proc root sys tmp usr var
# 此时重新大概一个控制窗口,查看运行情况
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
busybox 1/1 Running 0 92s
// 退出的时候是Completed状态
/ # exit
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
busybox 0/1 Completed 0 89s
kubectl get
获取资源列表,类似于docker ps,查询各种资源列表。
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 2m17s
nginx-app 0/1 ContainerCreating 0 17s
# 列出所有depolyment
[root@master ~]# kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE
kubernetes-bootcamp 0/1 1 0 6m39s
nginx 1/1 1 1 5h35m
# 查看当前所有service
[root@master ~]# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5h47m
nginx NodePort 10.96.49.203 <none> 80:30617/TCP 5h36m
kubectl describe
查看资源详细信息,类似于docker inspect,获取资源的详细信息。无论何时,只要遇到pod有问题,都先describe看下pod的状态。比如容器创建后,状态一直Pending(未正常启动至Running状态),那么可以用kubectl describe查看具体的原因是什么。
# 查看所有pods详情
[root@master ~]# kubectl describe pods
Name: kubernetes-bootcamp-65d5b99f84-2c5bq
Namespace: default
Priority: 0
Node: node02/192.168.58.125
Start Time: Sun, 19 Dec 2021 17:21:10 +0800
Labels: app=kubernetes-bootcamp
pod-template-hash=65d5b99f84
Annotations: <none>
Status: Pending
IP: 10.244.2.3
IPs:
IP: 10.244.2.3
Controlled By: ReplicaSet/kubernetes-bootcamp-65d5b99f84
Containers:
kubernetes-bootcamp:
Container ID:
Image: gcr.io/google-samples/kubernetes-bootcamp:v1
Image ID:
Port: <none>
Host Port: <none>
State: Waiting
Reason: ImagePullBackOff
Ready: False
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-ng7jf (ro)
Conditions:
Type Status
Initialized True
Ready False
ContainersReady False
PodScheduled True
Volumes:
kube-api-access-ng7jf:
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 8m33s default-scheduler Successfully assigned default/kubernetes-bootcamp-65d5b99f84-2c5bq to node02
Normal SandboxChanged 8m4s kubelet Pod sandbox changed, it will be killed and re-created.
Warning Failed 7m33s kubelet Failed to pull image "gcr.io/google-samples/kubernetes-bootcamp:v1": rpc error: code = Unknown desc = Error response from daemon: Get "https://gcr.io/v2/": net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)
Warning Failed 6m55s (x2 over 8m4s) kubelet Failed to pull image "gcr.io/google-samples/kubernetes-bootcamp:v1": rpc error: code = Unknown desc = Error response from daemon: Get "https://gcr.io/v2/": dial tcp 142.251.8.82:443: i/o timeout
Warning Failed 6m55s (x3 over 8m4s) kubelet Error: ErrImagePull
Warning Failed 6m21s (x7 over 8m1s) kubelet Error: ImagePullBackOff
Normal Pulling 6m9s (x4 over 8m20s) kubelet Pulling image "gcr.io/google-samples/kubernetes-bootcamp:v1"
Normal BackOff 3m17s (x17 over 8m1s) kubelet Back-off pulling image "gcr.io/google-samples/kubernetes-bootcamp:v1"
# 查看指定pod详情
[root@master ~]# kubectl describe pods nginx-app
Name: nginx-app
Namespace: default
Priority: 0
Node: node01/192.168.58.111
Start Time: Sun, 19 Dec 2021 17:23:09 +0800
Labels: run=nginx-app
Annotations: <none>
Status: Running
IP: 10.244.1.4
IPs:
IP: 10.244.1.4
Containers:
nginx-app:
Container ID: docker://ad3a8d568ce878958d6668692cb65b3adc5c53b83cf8e6b1224ec2914ca6f00d
Image: nginx:alpine
Image ID: docker-pullable://nginx@sha256:12aa12ec4a8ca049537dd486044b966b0ba6cd8890c4c900ccb5e7e630e03df0
Port: 8080/TCP
Host Port: 0/TCP
State: Running
Started: Sun, 19 Dec 2021 17:23:47 +0800
Ready: True
Restart Count: 0
Environment: <none>
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-nlpqf (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
kube-api-access-nlpqf:
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 9m2s default-scheduler Successfully assigned default/nginx-app to node01
Normal Pulling 9m kubelet Pulling image "nginx:alpine"
Normal Pulled 8m24s kubelet Successfully pulled image "nginx:alpine" in 35.748400177s
Normal Created 8m24s kubelet Created container nginx-app
Normal Started 8m24s kubelet Started container nginx-app
kubectl delete 删除
- f 强制删除
- l 指定标签删除
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
b2-866876dc6f-nllzq 0/1 CrashLoopBackOff 9 (4m13s ago) 30m
kubernetes-bootcamp-65d5b99f84-2c5bq 0/1 ImagePullBackOff 0 45m
myapp-d56b9c6b9-52gkx 1/1 Running 0 29m
myapp-d56b9c6b9-czs4j 1/1 Running 0 29m
myapp-d56b9c6b9-f7wm4 1/1 Running 0 29m
nginx-85b98978db-ztswj 1/1 Running 1 (161m ago) 6h14m
nginx-app 1/1 Running 0 43m
web-64c55fd557-9vw6v 1/1 Running 0 27m
# 单个删除
[root@master ~]# kubectl delete deployment b2
deployment.apps "b2" deleted
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
kubernetes-bootcamp-65d5b99f84-2c5bq 1/1 ImagePullBackOff 0 46m
myapp-d56b9c6b9-52gkx 1/1 Running 0 30m
myapp-d56b9c6b9-czs4j 1/1 Running 0 30m
myapp-d56b9c6b9-f7wm4 1/1 Running 0 30m
nginx-85b98978db-ztswj 1/1 Running 1 (162m ago) 6h15m
nginx-app 1/1 Running 0 44m
web-64c55fd557-9vw6v 1/1 Running 0 27m
# 多个删除
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6h28m
myapp NodePort 10.103.174.152 <none> 80:30235/TCP 12m
nginx NodePort 10.96.49.203 <none> 80:30617/TCP 6h16m
web ClusterIP 10.108.175.106 <none> 8080/TCP 16m
[root@master ~]# kubectl delete deployment,svc myapp
deployment.apps "myapp" deleted
service "myapp" deleted
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6h28m
nginx NodePort 10.96.49.203 <none> 80:30617/TCP 6h16m
web ClusterIP 10.108.175.106 <none> 8080/TCP 17m
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
kubernetes-bootcamp-65d5b99f84-2c5bq 1/1 ImagePullBackOff 0 48m
nginx-85b98978db-ztswj 1/1 Running 1 (164m ago) 6h17m
nginx-app 1/1 Running 0 46m
web-64c55fd557-9vw6v 1/1 Running 0 29m
# 全部删除
[root@master ~]# kubectl delete deployment --all
deployment.apps "kubernetes-bootcamp" deleted
deployment.apps "nginx" deleted
deployment.apps "web" deleted
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
# 运行多个nginx标签为app=nginx
[root@master ~]# kubectl run web1 --image nginx --labels "app=nginx"
pod/web1 created
[root@master ~]# kubectl run web2 --image nginx --labels "app=nginx"
pod/web2 created
[root@master ~]# kubectl run web3 --image nginx --labels "app=nginx"
pod/web3 created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-app 1/1 Running 0 52m
web1 1/1 Running 0 2m4s
web2 1/1 Running 0 2m
web3 1/1 Running 0 116s
[root@master ~]# kubectl delete pod -l "app=nginx" //-l,指定标签
pod "web1" deleted
pod "web2" deleted
pod "web3" deleted
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-app 1/1 Running 0 53m
kubectl exec
在容器内执行命令,类似于docker exec,在容器内执行一个命令
[root@master ~]# kubectl exec nginx-app ps aux
PID USER TIME COMMAND
1 root 0:00 nginx: master process nginx -g daemon off;
32 nginx 0:00 nginx: worker process
33 root 0:00 ps aux
kubectl cp
把本地计算机上的文件复制到远程k8s中正在运行的容器里或实现逆向文件复制
[root@master ~]# ls //查看/root/下文件
anaconda-ks.cfg init kube-flannel.yml
[root@master ~]# kubectl exec web -- ls /opt/ //查看pod /opt/下的文件
xu
[root@master ~]# kubectl cp /root/init web:/opt/ //将本机的文件通过cp命令传入pod中
[root@master ~]# kubectl exec web -- ls /opt/
init
xu
kubectl logs
查看pod日志
[root@master ~]# kubectl logs nginx-app
/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/19 09:23:47 [notice] 1#1: using the "epoll" event method
2021/12/19 09:23:47 [notice] 1#1: nginx/1.21.4
2021/12/19 09:23:47 [notice] 1#1: built by gcc 10.3.1 20210424 (Alpine 10.3.1_git20210424)
2021/12/19 09:23:47 [notice] 1#1: OS: Linux 3.10.0-862.el7.x86_64
2021/12/19 09:23:47 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/12/19 09:23:47 [notice] 1#1: start worker processes
2021/12/19 09:23:47 [notice] 1#1: start worker process 32
kubectl edit
编辑一个正在运行的资源
[root@master ~]# kubectl run web --image nginx --labels "web=1" // 运行一个名为web的nginx,pod并打上标签
pod/web created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
web 1/1 Running 0 76s
[root@master ~]# kubectl edit pods/web
# 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-20T10:03:53Z"
labels:
web: "nginx" // 修改标签为//web=nginx
name: web
namespace: default
resourceVersion: "34391"
uid: 8ecd12a9-1fec-45c5-a13f-eeeb6141ba58
# 编辑完成后,wq退出
pod/web edited // 成功则会出现提示
[root@master ~]# kubectl describe pod web //再次查看pod的详细信息是发现标签已改变
Name: web
Namespace: default
Priority: 0
Node: node02/192.168.58.125
Start Time: Mon, 20 Dec 2021 18:03:53 +0800
Labels: web=nginx // 此处
Annotations: <none>
Status: Running
IP: 10.244.2.11
IPs:
IP: 10.244.2.11
kubectl explain
查看资源对象拥有的字段
[root@master ~]# kubectl explain deployment
KIND: Deployment
VERSION: apps/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 <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 Deployment.
status <Object>
Most recently observed status of the Deployment.
# 以上Description是对资源对象的简要描述,Fields则是对所有字段的描述
kubectl scale
扩容或缩容 Deployment、ReplicaSet、Replication Controller或 Job 中Pod数量。
(前提是有pod在运行)
# --replicas 指定副本个数
[root@master ~]# kubectl create deployment com --image nginx //创建一个
deployment.apps/com created
[root@master ~]# kubectl get pod //此时只有一个com
NAME READY STATUS RESTARTS AGE
com-858bcd5777-gsfcz 1/1 Running 0 36s
[root@master ~]# kubectl scale --replicas 5 deployment/com //通过scale --replicas 额外扩展四个
deployment.apps/com scaled
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
com-858bcd5777-4fprd 1/1 Running 0 41s
com-858bcd5777-4sxc9 1/1 Running 0 41s
com-858bcd5777-gsfcz 1/1 Running 0 3m
com-858bcd5777-jqj5f 1/1 Running 0 41s
com-858bcd5777-xqj9x 1/1 Running 0 41s
[root@master ~]# kubectl scale --replicas 3 deployment/com // 当业务量少为节约系统资源时,可以缩容
deployment.apps/com scaled
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
com-858bcd5777-4sxc9 1/1 Running 0 3m18s
com-858bcd5777-gsfcz 1/1 Running 0 5m37s
com-858bcd5777-xqj9x 1/1 Running 0 3m18s
kubectl autoscale
使用 autoscaler 自动设置在kubernetes集群中运行的pod数量(水平自动伸缩)。
指定Deployment、ReplicaSet或ReplicationController,并创建已经定义好资源的自动伸缩器。使用自动伸缩器可以根据需要自动增加或减少系统中部署的pod数量。
# min:最小数
# max:最大数
# --cpu-percent:cpu百分比
[root@master ~]# kubectl autoscale --min 1 --max 4 --cpu-percent 40 deployment/com
horizontalpodautoscaler.autoscaling/com autoscaled
[root@master ~]# kubectl get hpa
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
com Deployment/com <unknown>/40% 1 4 4 4m32s
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
com-858bcd5777-4sxc9 1/1 Running 0 13m
com-858bcd5777-gsfcz 1/1 Running 0 16m
com-858bcd5777-xqj9x 1/1 Running 0 13m
com-858bcd5777-fqf6t 1/1 Running 0 1m
kubectl port-forward
通过端口转发映射本地端口到指定的应用端口,从而访问集群中的应用程序(Pod)
[root@master ~]# kubectl create deploy nginx-test --image=nginx //运行一个nginx 服务
deployment.apps/nginx-test created
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
com-858bcd5777-4sxc9 1/1 Running 0 25m
com-858bcd5777-gsfcz 1/1 Running 0 27m
com-858bcd5777-xqj9x 1/1 Running 0 25m
nginx-test-84b478f9c5-z4w5j 1/1 Running 0 95s
[root@master ~]# kubectl port-forward deployment/nginx-test 80
Forwarding from 127.0.0.1:80 -> 80
Forwarding from [::1]:80 -> 80
Handling connection for 80
[root@master ~]# curl 127.0.0.1:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
kubectl label
更新(增加、修改或删除)资源上的 label(标签)
- label 必须以字母或数字开头,可以使用字母、数字、连字符、点和下划线,最长63个字符。
- 如果–overwrite 为 true,则可以覆盖已有的 label,否则尝试覆盖 label 将会报错。
- 如果指定了–resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
语法
[root@master ~]# kubectl run nba --image nginx --labels "abc=123"
pod/nba created
[root@master ~]# kubectl describe pod nba
Name: nba
Namespace: default
Priority: 0
Node: node01/192.168.58.111
Start Time: Mon, 20 Dec 2021 19:33:35 +0800
Labels: abc=123 //此时的标签是abc=123
Annotations: <none>
Status: Running
IP: 10.244.1.17
IPs:
IP: 10.244.1.17
Containers:
[root@master ~]# kubectl label pod nba --overwrite abc=456 //覆盖标签
pod/nba labeled
[root@master ~]# kubectl describe pod nba
Name: nba
Namespace: default
Priority: 0
Node: node01/192.168.58.111
Start Time: Mon, 20 Dec 2021 19:33:35 +0800
Labels: abc=456
Annotations: <none>
Status: Running
IP: 10.244.1.17
IPs:
IP: 10.244.1.17
kubectl rollout
回滚
准备工作
提供镜像
# 先用docker构建两个提供站点服务的镜像
[root@master ~]# vi dockerfile
FROM busybox
RUN mkdir /data && \
echo "This is V1!" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master ~]# docker build -t xm17671855780/httpd:v1.0 . //构建镜像
Sending build context to Docker daemon 3.055MB
Step 1/3 : FROM busybox
latest: Pulling from library/busybox
3cb635b06aa2: Pull complete
Digest: sha256:b5cfd4befc119a590ca1a81d6bb0fa1fb19f1fbebd0397f25fae164abe1e8a6a
Status: Downloaded newer image for busybox:latest
---> ffe9d497c324
Step 2/3 : RUN mkdir /data && echo "This is V1!" > /data/index.html
---> Running in a3d030d19330
Removing intermediate container a3d030d19330
---> 2531bebc47aa
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
---> Running in 898a37dd2be5
Removing intermediate container 898a37dd2be5
---> d77df7be75e2
Successfully built d77df7be75e2
Successfully tagged xm17671855780/httpd:v1.0
[root@master ~]# vi dockerfile
FROM busybox
RUN mkdir /data && \
echo "This is V2!" > /data/index.html //将站点文件添加标识性内容
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master ~]# docker build -t xm17671855780/httpd:v2.0 . //构建镜像
Sending build context to Docker daemon 3.055MB
Step 1/3 : FROM busybox
---> ffe9d497c324
Step 2/3 : RUN mkdir /data && echo "This is V2!" > /data/index.html
---> Running in 6b321b3ec3ca
Removing intermediate container 6b321b3ec3ca
---> 825f5ebc5471
Step 3/3 : ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
---> Running in ed9e4b9b705d
Removing intermediate container ed9e4b9b705d
---> 81b81c64f61d
Successfully built 81b81c64f61d
Successfully tagged xm17671855780/httpd:v2.0
[root@master ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
xm17671855780/httpd v2.0 81b81c64f61d 42 seconds ago 1.24MB
xm17671855780/httpd v1.0 d77df7be75e2 2 minutes ago 1.24MB
运行容器验证,保证服务的正常运行。
[root@master ~]# docker run -dit --name web1 -p 80:80 d77df7be75e2
3dea434911a0f4b009cb94ec52c844b3a56ae8405e1bc36a01c454014faad11f
[root@master ~]# curl 192.168.58.110
This is V1!
[root@master ~]# docker run -dit --name web2 -p 8080:80 81b81c64f61d
5d94342340ae4e012125d853892514838a1664532c59007eab1775a952fafadb
[root@master ~]# curl 192.168.58.110:8080
This is V2!
将镜像上传至docker 仓库
[root@master ~]# docker login //登入仓库
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one.
Username: xm17671855780
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store
Login Succeeded
[root@master ~]# docker push xm17671855780/httpd:v1.0
The push refers to repository [docker.io/xm17671855780/httpd]
573f0faec170: Pushed
64cac9eaf0da: Mounted from library/busybox
v1.0: digest: sha256:18d6439f54b7af07045eec6ad98929fd6d4dc815e29715204959bc157e84b623 size: 734
[root@master ~]# docker push xm17671855780/httpd:v2.0
The push refers to repository [docker.io/xm17671855780/httpd]
d73d3c7bc7d7: Pushed
64cac9eaf0da: Layer already exists
v2.0: digest: sha256:4a6d00fe7447df4fa51a33fb0424d81258c4778709621ae27b144f6b368237bd size: 734
[root@master ~]# kubectl create deployment httpd --image xm17671855780/httpd:v1.0 --replicas 3
deployment.apps/httpd created
实例
创建一个v1版本的pod以及service并暴露端口
# --replicas 指定pod的运行个数
[root@master ~]# kubectl create deployment httpd --image xm17671855780/httpd:v1.0 --replicas 3
deployment.apps/httpd created
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
httpd-66dc445c66-9grfh 1/1 Running 0 78s
httpd-66dc445c66-mltx4 1/1 Running 0 78s
httpd-66dc445c66-nxzm5 1/1 Running 0 78s
[root@master ~]# kubectl expose deployment httpd --port 80 --target-port 80
service/httpd exposed
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
httpd ClusterIP 10.105.78.8 <none> 80/TCP 16s
[root@master ~]# curl 10.105.78.8
This is V1!
新建一个控制窗口,并运用死循环,对此站点进行连续访问
[root@node02 ~]# while :;do curl 10.105.78.8 ;done
This is V1!
This is V1!
This is V1!
This is V1!
This is V1!
This is V1!
This is V1!
This is V1!
通过kubectl set --images 更改镜像,完成版本更替
[root@master ~]# kubectl set image deployment/httpd httpd=xm17671855780/httpd:v2.0
deployment.apps/httpd image updated
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
httpd-66dc445c66-9grfh 1/1 Running 0 4m2s
httpd-66dc445c66-mltx4 1/1 Running 0 4m2s
httpd-66dc445c66-nxzm5 1/1 Terminating 0 4m2s
httpd-689dbd69c9-lxjln 1/1 Running 0 47s
httpd-689dbd69c9-x97ng 0/1 ContainerCreating 0 1s
// 此时的循环内容是
This is V1!
This is V1!
This is V1!
This is V1!
This is V2!
This is V1!
This is V1!
This is V1!
This is V2!
This is V1!
This is V1!
This is V1!
This is V1!
This is V2!
This is V1!
This is V1!
This is V1!
[root@master ~]# kubectl get pods //等待所有pod更换完毕
NAME READY STATUS RESTARTS AGE
httpd-66dc445c66-mltx4 1/1 Running 0 1m48s
httpd-689dbd69c9-lxjln 1/1 Running 0 93s
httpd-689dbd69c9-x97ng 1/1 Running 0 47s
再次查看访问信息
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
This is V2!
# 此时版本变更完毕
回滚至v1
[root@master ~]# kubectl rollout undo deployment/httpd // 撤销当前版本,回滚至v1版本
deployment.apps/httpd rolled back
[root@master ~]# kubectl get pods
NAME READY STATUS RESTARTS AGE
httpd-66dc445c66-46bt7 1/1 Running 0 9s
httpd-66dc445c66-jbf52 1/1 Running 0 4s
httpd-66dc445c66-jnzjc 1/1 Running 0 7s
httpd-689dbd69c9-lxjln 1/1 Terminating 2 (5m3s ago) 4h24m
httpd-689dbd69c9-w8pt8 1/1 Terminating 2 (5m3s ago) 4h22m
httpd-689dbd69c9-x97ng 1/1 Terminating 2 (5m ago) 4h23m //正在进行版本变更
[root@master ~]# kubectl get pods //等待版本变更结束
NAME READY STATUS RESTARTS AGE
httpd-66dc445c66-46bt7 1/1 Running 0 106s
httpd-66dc445c66-jbf52 1/1 Running 0 101s
httpd-66dc445c66-jnzjc 1/1 Running 0 104s
再次访问
[root@master ~]# curl 10.105.78.8
This is V1!
更多推荐
所有评论(0)