创建Ubuntu集群

kubenetes安装与使用

创建集群

下载镜像

在master节点初始化集群过程中,需要下载镜像,这里我们提前下载。

bash 复制代码
[root@master30 ~]# kubeadm config images pull --kubernetes-version=v1.30.2
[config/images] Pulled registry.k8s.io/kube-apiserver:v1.30.2
[config/images] Pulled registry.k8s.io/kube-controller-manager:v1.30.2
[config/images] Pulled registry.k8s.io/kube-scheduler:v1.30.2
[config/images] Pulled registry.k8s.io/kube-proxy:v1.30.2
[config/images] Pulled registry.k8s.io/coredns/coredns:v1.11.1
[config/images] Pulled registry.k8s.io/pause:3.9
[config/images] Pulled registry.k8s.io/etcd:3.5.12-0

备选方案-使用阿里云仓库镜像:

bash 复制代码
[root@master30 ~]# kubeadm config images pull --kubernetes-version=v1.30.2 --image-repository registry.aliyuncs.com/google_containers
[config/images] Pulled registry.k8s.io/kube-apiserver:v1.30.2
[config/images] Pulled registry.k8s.io/kube-controller-manager:v1.30.2
[config/images] Pulled registry.k8s.io/kube-scheduler:v1.30.2
[config/images] Pulled registry.k8s.io/kube-proxy:v1.30.2
[config/images] Pulled registry.k8s.io/coredns/coredns:v1.11.1
[config/images] Pulled registry.k8s.io/pause:3.9
[config/images] Pulled registry.k8s.io/etcd:3.5.12-0

worker 节点需要kube-proxy和pause镜像:

bash 复制代码
[root@worker31 ~]# nerdctl pull registry.k8s.io/kube-proxy:v1.30.2
[root@worker31 ~]# nerdctl pull registry.k8s.io/pause:3.9

[root@worker32 ~]# nerdctl pull registry.k8s.io/kube-proxy:v1.30.2
[root@worker32 ~]# nerdctl pull registry.k8s.io/pause:3.9

初始化集群

bash 复制代码
[root@master30 ~]# kubeadm init --kubernetes-version=v1.30.2 --pod-network-cidr=10.224.0.0/16 

备选方案-使用阿里云仓库镜像初始化集群:

bash 复制代码
[root@master30 ~]# kubeadm init --kubernetes-version=v1.30.2 --pod-network-cidr=10.224.0.0/16 --image-repository registry.aliyuncs.com/google_containers

初始化过程如下:

bash 复制代码
[init] Using Kubernetes version: v1.30.2
[preflight] Running pre-flight checks
[preflight] Pulling images required for setting up a Kubernetes cluster
[preflight] This might take a minute or two, depending on the speed of your internet connection
[preflight] You can also perform this action in beforehand using 'kubeadm config images pull'
[certs] Using certificateDir folder "/etc/kubernetes/pki"
[certs] Generating "ca" certificate and key
[certs] Generating "apiserver" certificate and key
[certs] apiserver serving cert is signed for DNS names [kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local master30.laoma.cloud] and IPs [10.96.0.1 10.1.8.30]
[certs] Generating "apiserver-kubelet-client" certificate and key
[certs] Generating "front-proxy-ca" certificate and key
[certs] Generating "front-proxy-client" certificate and key
[certs] Generating "etcd/ca" certificate and key
[certs] Generating "etcd/server" certificate and key
[certs] etcd/server serving cert is signed for DNS names [localhost master30.laoma.cloud] and IPs [10.1.8.30 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [localhost master30.laoma.cloud] and IPs [10.1.8.30 127.0.0.1 ::1]
[certs] Generating "etcd/healthcheck-client" certificate and key
[certs] Generating "apiserver-etcd-client" certificate and key
[certs] Generating "sa" key and public key
[kubeconfig] Using kubeconfig folder "/etc/kubernetes"
[kubeconfig] Writing "admin.conf" kubeconfig file
[kubeconfig] Writing "super-admin.conf" kubeconfig file
[kubeconfig] Writing "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[control-plane] Using manifest folder "/etc/kubernetes/manifests"
[control-plane] Creating static Pod manifest for "kube-apiserver"
[control-plane] Creating static Pod manifest for "kube-controller-manager"
[control-plane] Creating static Pod manifest for "kube-scheduler"
[kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
[kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
[kubelet-start] Starting the kubelet
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests"
[kubelet-check] Waiting for a healthy kubelet. This can take up to 4m0s
[kubelet-check] The kubelet is healthy after 502.398615ms
[api-check] Waiting for a healthy API server. This can take up to 4m0s
[api-check] The API server is healthy after 7.50265248s
[upload-config] Storing the configuration used in ConfigMap "kubeadm-config" in the "kube-system" Namespace
[kubelet] Creating a ConfigMap "kubelet-config" in namespace kube-system with the configuration for the kubelets in the cluster
[upload-certs] Skipping phase. Please see --upload-certs
[mark-control-plane] Marking the node master30.laoma.cloud as control-plane by adding the labels: [node-role.kubernetes.io/control-plane node.kubernetes.io/exclude-from-external-load-balancers]
[mark-control-plane] Marking the node master30.laoma.cloud as control-plane by adding the taints [node-role.kubernetes.io/control-plane:NoSchedule]
[bootstrap-token] Using token: ybenal.6mszwb1nf8nck72g
[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to get nodes
[bootstrap-token] Configured RBAC rules to allow Node Bootstrap tokens to post CSRs in order for nodes to get long term certificate credentials
[bootstrap-token] Configured RBAC rules to allow the csrapprover controller automatically approve CSRs from a Node Bootstrap Token
[bootstrap-token] Configured RBAC rules to allow certificate rotation for all node client certificates in the cluster
[bootstrap-token] Creating the "cluster-info" ConfigMap in the "kube-public" namespace
[kubelet-finalize] Updating "/etc/kubernetes/kubelet.conf" to point to a rotatable kubelet client certificate and key
[addons] Applied essential addon: CoreDNS
[addons] Applied essential addon: kube-proxy

Your Kubernetes control-plane has initialized successfully!

To start using your cluster, you need to run the following as a regular user:

  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config

Alternatively, if you are the root user, you can run:

  export KUBECONFIG=/etc/kubernetes/admin.conf

You should now deploy a pod network to the cluster.
Run "kubectl apply -f [podnetwork].yaml" with one of the options listed at:
  https://kubernetes.io/docs/concepts/cluster-administration/addons/

Then you can join any number of worker nodes by running the following on each as root:

kubeadm join 10.1.8.30:6443 --token mi0yt8.1tzza4q64dr8y3pc \
	--discovery-token-ca-cert-hash sha256:5606e09618330aee8859abe3ea4cd8734f9b540630048a6e1c3aaf6c54d486fd

选项说明:

--image-repository registry.aliyuncs.com/google_containers,指定镜像下载位置

--kubernetes-version=v1.30.2,指定版本

--pod-network-cidr=10.224.0.0/16,指定Pod网络的范围。 Kubernetes支持多种网络

方案, 而且不同网络方案对--pod-network-cidr有自己的要求。

--apiserver-advertise-address指明用哪个interface与Cluster的其他节点通信。 如果master有多个interface, 建议明确指定, 如果不指定, kubeadm会自动选择有默认网关的interface。

初始化过程说明:

  1. kubeadm执行初始化前的检查。
  2. 下载组件的镜像。 这一步可能会花一些时间, 主要取决于网络质量。
  3. 生成token和证书。
  4. 生成KubeConfig文件, kubelet需要用这个文件与master通信。
  5. 安装master组件。
  6. 安装附加组件kube-proxy和CoreDNS。
  7. Kubernetes master初始化成功。
  8. 提示如何配置kubectl。
  9. 提示如何安装Pod网络。
  10. 提示如何注册其他节点到Cluster。

配置集群

配置凭据

  1. kubectl默认使用~/.kube/config文件中凭据信息管理kubernetes。
bash 复制代码
[root@master30 ~]# mkdir -p $HOME/.kube
[root@master30 ~]# cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  1. 如果环境变量KUBECONFIG存在,则优先使用境变量KUBECONFIG设置的值。
bash 复制代码
[root@master30 ~]# mv .kube/config .
[root@master30 ~]# export KUBECONFIG=/root/config
[root@master30 ~]# kubectl get nodes
NAME                 STATUS     ROLES                  AGE    VERSION
master30.laoma.cloud   NotReady   control-plane,master   5m2s   v1.28.2

# 等网络配置完成后,STATUS状态由NotReady变更为Ready
  1. 还可以通过选项--kubeconfig=''明确指定凭据文件位置。
bash 复制代码
[root@master30 ~]# kubectl get nodes --kubeconfig /root/config

kubernetes对凭据文件名没有要求。

bash 复制代码
[root@master30 ~]# mv config kube.conf
[root@master30 ~]# kubectl get nodes --kubeconfig kube.conf
  1. 恢复使用默认位置~/.kube/config
bash 复制代码
[root@master30 ~]# unset KUBECONFIG
[root@master30 ~]# mv kube.conf .kube/config

部署网络

这里采用 calico 网络。

官方地址:http://projectcalico.org 或者 https://www.tigera.io/project-calico/

产品文档:https://projectcalico.docs.tigera.io/about/about-calico

项目地址:https://github.com/projectcalico/calico(提供镜像)

下载 calico 配置
bash 复制代码
[root@master30 ~]# wget --no-check-certificate https://raw.githubusercontent.com/projectcalico/calico/v3.30.7/manifests/calico.yaml
修改 pod 网络
bash 复制代码
# 查看集群 pod 网络范围
[root@master30 ~]# kubectl get cm -n kube-system kubeadm-config -o yaml|grep podSubnet
      podSubnet: 10.224.0.0/16

# 更改 calico.yml,确保 CALICO_IPV4POOL_CIDR 与集群初始化的pod网络一致。
[root@master30 ~]# sed -i "s|# - name: CALICO_IPV4POOL_CIDR|- name: CALICO_IPV4POOL_CIDR|g" calico.yaml
[root@master30 ~]# sed -i "s|#   value: \"192.*|  value: \"10.224.0.0/16\"|g" calico.yaml
下载镜像
bash 复制代码
[root@master30 ~]# grep image: calico.yaml | uniq
          image: docker.io/calico/cni:v3.30.7
          image: docker.io/calico/node:v3.30.7
          image: docker.io/calico/kube-controllers:v3.30.7

# 所有节点下载以上镜像
[root@all-node ~]# nerdctl pull docker.io/calico/cni:v3.30.7
[root@all-node ~]# nerdctl pull docker.io/calico/node:v3.30.7
[root@all-node ~]# nerdctl pull docker.io/calico/kube-controllers:v3.30.7
部署 calico 网络
bash 复制代码
[root@master30 ~]# kubectl apply -f calico.yaml
验证部署

脚本:

bash 复制代码
# master节点:拉取 k8s.io 镜像
images=(
registry.k8s.io/kube-apiserver:v1.30.2
registry.k8s.io/kube-controller-manager:v1.30.2
registry.k8s.io/kube-scheduler:v1.30.2
registry.k8s.io/kube-proxy:v1.30.2

registry.k8s.io/pause:3.9
registry.k8s.io/etcd:3.5.12-0
)
for image in ${images[@]}
do
    image_new=$(echo $image| sed 's#registry.k8s.io#hub.laoma.cloud/kubernetes#g')
    nerdctl pull --insecure-registry $image_new
    nerdctl tag ${image_new} $image 
    nerdctl rmi ${image_new}
done

# 单独处理coredns
nerdctl pull --insecure-registry hub.laoma.cloud/kubernetes/coredns:v1.11.1
nerdctl tag hub.laoma.cloud/kubernetes/coredns:v1.11.1 registry.k8s.io/coredns/coredns:v1.11.1
nerdctl rmi hub.laoma.cloud/kubernetes/coredns:v1.11.1


# 客户端拉取镜像kube-proxy和pause
images=(
registry.k8s.io/kube-proxy:v1.30.2
registry.k8s.io/pause:3.9
)
for image in ${images[@]}
do
    image_new=$(echo $image| sed 's#registry.k8s.io#hub.laoma.cloud/kubernetes#g')
    nerdctl pull --insecure-registry $image_new
    nerdctl tag ${image_new} $image 
    nerdctl rmi ${image_new}
done


# 集群初始化
[root@master30 ~]# kubeadm init --kubernetes-version=v1.30.2 --pod-network-cidr=10.224.0.0/16

# 配置凭据
[root@master30 ~]#
  mkdir -p $HOME/.kube
  sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
  sudo chown $(id -u):$(id -g) $HOME/.kube/config


# 配置网络
[root@master30 ~]# wget --no-check-certificate https://raw.githubusercontent.com/projectcalico/calico/v3.30.7/manifests/calico.yaml
[root@master30 ~]# sed -i "s|# - name: CALICO_IPV4POOL_CIDR|- name: CALICO_IPV4POOL_CIDR|g" calico.yaml
[root@master30 ~]# sed -i "s|#   value: \"192.*|  value: \"10.224.0.0/16\"|g" calico.yaml

# 所有节点: 拉取calico 镜像
images=(
hub.laoma.cloud/calico/cni:v3.30.7
hub.laoma.cloud/calico/node:v3.30.7
hub.laoma.cloud/calico/kube-controllers:v3.30.7
)
for image in ${images[@]}
do
    nerdctl pull --insecure-registry $image
    image_new=$(echo $image| sed 's#hub.laoma.cloud#docker.io#g')
    nerdctl tag $image ${image_new}
    nerdctl rmi $image
done

# 应用配置
[root@master30 ~]# kubectl apply -f calico.yaml

#客户端加入集群
[root@worker31 ~]# kubeadm join 10.1.8.30:6443 --token u8sssw.wtz8c130yx5i7ako  --discovery-token-ca-cert-hash sha256:52619b52a782691eeb937c83f3a6e43898f1c79baa15378dff859942a3f3aa19
[root@worker32 ~]# kubeadm join 10.1.8.30:6443 --token u8sssw.wtz8c130yx5i7ako  --discovery-token-ca-cert-hash sha256:52619b52a782691eeb937c83f3a6e43898f1c79baa15378dff859942a3f3aa19

查看节点

bash 复制代码
[root@master30 ~ 13:34:11]# kubectl get nodes
NAME                STATUS   ROLES           AGE    VERSION
master30.my.cloud   Ready    control-plane   156m   v1.30.2
worker31.my.cloud   Ready    <none>          147m   v1.30.2
worker32.my.cloud   Ready    <none>          154m   v1.30.2
[root@master30 ~ 14:01:00]# kubectl get nodes -o name
node/master30.my.cloud
node/worker31.my.cloud
node/worker32.my.cloud
[root@master30 ~ 14:02:25]# kubectl describe node worker31.my.cloud
Name:               worker31.my.cloud
Roles:              <none>
Labels:             beta.kubernetes.io/arch=amd64
                    beta.kubernetes.io/os=linux
                    kubernetes.io/arch=amd64
                    kubernetes.io/hostname=worker31.my.cloud
                    kubernetes.io/os=linux
Annotations:        kubeadm.alpha.kubernetes.io/cri-socket: unix:///var/run/containerd/containerd.sock
                    node.alpha.kubernetes.io/ttl: 0
                    projectcalico.org/IPv4Address: 10.1.8.31/24
                    projectcalico.org/IPv4IPIPTunnelAddr: 10.224.15.64
                    volumes.kubernetes.io/controller-managed-attach-detach: true
CreationTimestamp:  Tue, 23 Jun 2026 11:07:44 +0800
Taints:             <none>
Unschedulable:      false
Lease:
  HolderIdentity:  worker31.my.cloud
  AcquireTime:     <unset>
  RenewTime:       Tue, 23 Jun 2026 14:03:01 +0800
Conditions:
  Type                 Status  LastHeartbeatTime                 LastTransitionTime                Reason                       Message
  ----                 ------  -----------------                 ------------------                ------                       -------
  NetworkUnavailable   False   Tue, 23 Jun 2026 13:33:34 +0800   Tue, 23 Jun 2026 13:33:34 +0800   CalicoIsUp                   Calico is running on this node
  MemoryPressure       False   Tue, 23 Jun 2026 13:58:56 +0800   Tue, 23 Jun 2026 11:07:44 +0800   KubeletHasSufficientMemory   kubelet has sufficient memory available
  DiskPressure         False   Tue, 23 Jun 2026 13:58:56 +0800   Tue, 23 Jun 2026 11:07:44 +0800   KubeletHasNoDiskPressure     kubelet has no disk pressure
  PIDPressure          False   Tue, 23 Jun 2026 13:58:56 +0800   Tue, 23 Jun 2026 11:07:44 +0800   KubeletHasSufficientPID      kubelet has sufficient PID available
  Ready                True    Tue, 23 Jun 2026 13:58:56 +0800   Tue, 23 Jun 2026 11:07:49 +0800   KubeletReady                 kubelet is posting ready status
Addresses:
  InternalIP:  10.1.8.31
  Hostname:    worker31.my.cloud
Capacity:
  cpu:                4
  ephemeral-storage:  10218772Ki
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             3961040Ki
  pods:               110
Allocatable:
  cpu:                4
  ephemeral-storage:  9417620260
  hugepages-1Gi:      0
  hugepages-2Mi:      0
  memory:             3858640Ki
  pods:               110
System Info:
  Machine ID:                 761a3d97a08b415d9bdd4c0e4e0ba625
  System UUID:                791e4d56-3142-ea19-6ee5-82ed03f48a3c
  Boot ID:                    87d62fc1-50b0-4895-9f83-29036186bd05
  Kernel Version:             6.8.0-31-generic
  OS Image:                   Ubuntu 24.04 LTS
  Operating System:           linux
  Architecture:               amd64
  Container Runtime Version:  containerd://1.7.20
  Kubelet Version:            v1.30.2
  Kube-Proxy Version:         v1.30.2
PodCIDR:                      10.224.3.0/24
PodCIDRs:                     10.224.3.0/24
Non-terminated Pods:          (2 in total)
  Namespace                   Name                 CPU Requests  CPU Limits  Memory Requests  Memory Limits  Age
  ---------                   ----                 ------------  ----------  ---------------  -------------  ---
  kube-system                 calico-node-6lb2m    250m (6%)     0 (0%)      0 (0%)           0 (0%)         3h2m
  kube-system                 kube-proxy-xmsh4     0 (0%)        0 (0%)      0 (0%)           0 (0%)         3h2m
Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource           Requests   Limits
  --------           --------   ------
  cpu                250m (6%)  0 (0%)
  memory             0 (0%)     0 (0%)
  ephemeral-storage  0 (0%)     0 (0%)
  hugepages-1Gi      0 (0%)     0 (0%)
  hugepages-2Mi      0 (0%)     0 (0%)
Events:
  Type     Reason                   Age                  From             Message
  ----     ------                   ----                 ----             -------
  Normal   Starting                 175m                 kube-proxy
  Normal   Starting                 29m                  kube-proxy
  Normal   Starting                 3h2m                 kube-proxy
  Normal   NodeAllocatableEnforced  3h2m                 kubelet          Updated Node Allocatable limit across pods
  Normal   NodeHasNoDiskPressure    3h2m (x2 over 3h2m)  kubelet          Node worker31.my.cloud status is now: NodeHasNoDiskPressure
  Normal   NodeHasSufficientPID     3h2m (x2 over 3h2m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientPID
  Normal   NodeHasSufficientMemory  3h2m (x2 over 3h2m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientMemory
  Warning  InvalidDiskCapacity      3h2m                 kubelet          invalid capacity 0 on image filesystem
  Normal   Starting                 178m                 kubelet          Starting kubelet.
  Warning  InvalidDiskCapacity      178m                 kubelet          invalid capacity 0 on image filesystem
  Normal   NodeAllocatableEnforced  178m                 kubelet          Updated Node Allocatable limit across pods
  Normal   NodeHasSufficientMemory  175m (x4 over 178m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientMemory
  Normal   NodeHasNoDiskPressure    175m (x4 over 178m)  kubelet          Node worker31.my.cloud status is now: NodeHasNoDiskPressure
  Normal   NodeHasSufficientPID     175m (x4 over 178m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientPID
  Normal   NodeHasNoDiskPressure    175m (x2 over 175m)  kubelet          Node worker31.my.cloud status is now: NodeHasNoDiskPressure
  Normal   NodeHasSufficientMemory  175m (x2 over 175m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientMemory
  Normal   NodeHasSufficientPID     175m (x2 over 175m)  kubelet          Node worker31.my.cloud status is now: NodeHasSufficientPID
  Normal   NodeAllocatableEnforced  175m                 kubelet          Updated Node Allocatable limit across pods
  Warning  InvalidDiskCapacity      175m                 kubelet          invalid capacity 0 on image filesystem
  Normal   RegisteredNode           175m                 node-controller  Node worker31.my.cloud event: Registered Node worker31.my.cloud in Controller
  Normal   NodeReady                175m                 kubelet          Node worker31.my.cloud status is now: NodeReady
  Normal   Starting                 172m                 kubelet          Starting kubelet.
  Normal   NodeHasNoDiskPressure    172m                 kubelet          Node worker31.my.cloud status is now: NodeHasNoDiskPressure
  Normal   NodeAllocatableEnforced  172m                 kubelet          Updated Node Allocatable limit across pods
  Normal   NodeHasSufficientMemory  172m                 kubelet          Node worker31.my.cloud status is now: NodeHasSufficientMemory
  Warning  InvalidDiskCapacity      172m                 kubelet          invalid capacity 0 on image filesystem
  Normal   NodeHasSufficientPID     172m                 kubelet          Node worker31.my.cloud status is now: NodeHasSufficientPID
  Normal   Starting                 29m                  kubelet          Starting kubelet.
  Warning  InvalidDiskCapacity      29m                  kubelet          invalid capacity 0 on image filesystem
  Normal   NodeHasSufficientMemory  29m (x3 over 29m)    kubelet          Node worker31.my.cloud status is now: NodeHasSufficientMemory
  Normal   NodeHasNoDiskPressure    29m (x3 over 29m)    kubelet          Node worker31.my.cloud status is now: NodeHasNoDiskPressure
  Normal   NodeHasSufficientPID     29m (x3 over 29m)    kubelet          Node worker31.my.cloud status is now: NodeHasSufficientPID
  Normal   NodeAllocatableEnforced  29m                  kubelet          Updated Node Allocatable limit across pods
  Warning  Rebooted                 29m                  kubelet          Node worker31.my.cloud has been rebooted, boot id: 87d62fc1-50b0-4895-9f83-29036186bd05
  Normal   RegisteredNode           29m                  node-controller  Node worker31.my.cloud event: Registered Node worker31.my.cloud in Controller

删除节点

以 worker31 节点为例。

bash 复制代码
# 设置节点为维护模式
[root@master30 ~14:03:08]# kubectl drain worker31.my.cloud --ignore-daemonsets
node/worker31.my.cloud cordoned
Warning: ignoring DaemonSet-managed Pods: kube-system/calico-node-v8jdn, kube-system/kube-proxy-27vl2
evicting pod kube-system/calico-kube-controllers-7cb4fd5784-jx2xl
pod/calico-kube-controllers-7cb4fd5784-jx2xl evicted
node/worker31.my.cloud drained

[root@master30 ~14:03:16]# kubectl get nodes
NAME                  STATUS                     ROLES           AGE   VERSION
master30.my.cloud   Ready                      control-plane   41h   v1.30.2
worker31.my.cloud   Ready,SchedulingDisabled   <none>          41h   v1.30.2
worker32.my.cloud   Ready                      <none>          41h   v1.30.2

# 删除 worker31 节点
[root@master30 ~14:03:23]# kubectl delete node worker31.my.cloud
node "worker31.my.cloud" deleted
[root@master30 ~14:03:29]# kubectl get nodes
NAME                  STATUS   ROLES           AGE   VERSION
master30.my.cloud   Ready    control-plane   41h   v1.30.2
worker32.my.cloud   Ready    <none>          41h   v1.30.2

# 重置删除的 worker31 节点
[root@worker31 ~14:03:47]# kubeadm reset -f
[preflight] Running pre-flight checks
W1019 07:37:44.242023    7660 removeetcdmember.go:106] [reset] No kubeadm config, using etcd pod spec to get data directory
[reset] Deleted contents of the etcd data directory: /var/lib/etcd
[reset] Stopping the kubelet service
[reset] Unmounting mounted directories in "/var/lib/kubelet"
[reset] Deleting contents of directories: [/etc/kubernetes/manifests /var/lib/kubelet /etc/kubernetes/pki]
[reset] Deleting files: [/etc/kubernetes/admin.conf /etc/kubernetes/kubelet.conf /etc/kubernetes/bootstrap-kubelet.conf /etc/kubernetes/controller-manager.conf /etc/kubernetes/scheduler.conf]

The reset process does not clean CNI configuration. To do so, you must remove /etc/cni/net.d

The reset process does not reset or clean up iptables rules or IPVS tables.
If you wish to reset iptables, you must do so manually by using the "iptables" command.

If your cluster was setup to utilize IPVS, run ipvsadm --clear (or similar)
to reset your system's IPVS tables.

The reset process does not clean your kubeconfig files and you must remove them manually.
Please, check the contents of the $HOME/.kube/config file.

删除集群

删除集群流程:

  1. 删除所有 node
  2. 删除所有 master

具体步骤:

  1. 删除所有node节点
bash 复制代码
[root@master30 ~14:04:08]# kubectl drain worker31.my.cloud --ignore-daemonsets --force
[root@master30 ~14:04:14]# kubectl drain worker32.my.cloud --ignore-daemonsets --force
[root@master30 ~14:04:19]# kubectl delete node worker31.my.cloud worker32.my.cloud

# 重置节点,注意执行位置
[root@worker31 ~14:04:28]# kubeadm reset -f
[root@worker32 ~14:04:38]# kubeadm reset -f
  1. 删除master节点
bash 复制代码
# 删除集群前获取集群配置
[root@master30 ~]# kubectl get cm kubeadm-config -n kube-system -o yaml > kubeadm.yml

# 修改kubeadm.yml内容如下:
[root@master30 ~]# vim kubeadm.yml
# 删除1-3和22-28行,效果如下
apiServer:
  timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta3
certificatesDir: /etc/kubernetes/pki
clusterName: kubernetes
controllerManager: {}
dns: {}
etcd:
  local:
    dataDir: /var/lib/etcd
imageRepository: registry.k8s.io
kind: ClusterConfiguration
kubernetesVersion: v1.30.2
networking:
  dnsDomain: cluster.local
  podSubnet: 10.224.0.0/16
  serviceSubnet: 10.96.0.0/12
scheduler: {}

[root@master30 ~]# kubectl delete node master30.my.cloud
[root@master30 ~]# kubeadm reset -f
[root@master30 ~]# rm -fr .kube/

重建集群

bash 复制代码
# 初始化集群
[root@master30 ~]# kubeadm init --config kubeadm.yml

# 也可以使用之前的命令
[root@master30 ~]# kubeadm init --kubernetes-version=v1.30.2 --pod-network-cidr=10.224.0.0/16

# 配置凭据
[root@master30 ~]# mkdir -p $HOME/.kube
[root@master30 ~]# sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
[root@master30 ~]# sudo chown $(id -u):$(id -g) $HOME/.kube/config

# 配置网络
[root@master30 ~]# kubectl apply -f calico.yaml

# 加入集群
[root@worker31 ~]# kubeadm join 10.1.8.30:6443 --token ky95b9.sjg0fn21pdi1m0xz    --discovery-token-ca-cert-hash sha256xxxxxxx
[root@worker32 ~]# kubeadm join 10.1.8.30:6443 --token ky95b9.sjg0fn21pdi1m0xz    --discovery-token-ca-cert-hash sha256xxxx

namespace命名空间

bash 复制代码
[root@master30 ~ 14:33:49]# kubectl get namespaces -n kube-system
NAME              STATUS   AGE
default           Active   3h56m
kube-node-lease   Active   3h56m
kube-public       Active   3h56m
kube-system       Active   3h56m
[root@master30 ~ 14:54:24]# kubectl api-resources
NAME                                SHORTNAMES   APIVERSION                        NAMESPACED   KIND
bindings                                         v1                                true         Binding
componentstatuses                   cs           v1                                false        ComponentStatus
configmaps                          cm           v1                                true         ConfigMap
endpoints                           ep           v1                                true         Endpoints
events                              ev           v1                                true         Event
limitranges                         limits       v1                                true         LimitRange
namespaces                          ns           v1                                false        Namespace
nodes                               no           v1                                false        Node
persistentvolumeclaims              pvc          v1                                true         PersistentVolumeClaim
persistentvolumes                   pv           v1                                false        PersistentVolume
pods                                po           v1                                true         Pod
podtemplates                                     v1                                true         PodTemplate
replicationcontrollers              rc           v1                                true         ReplicationController
resourcequotas                      quota        v1                                true         ResourceQuota
secrets                                          v1                                true         Secret
serviceaccounts                     sa           v1                                true         ServiceAccount
services                            svc          v1                                true         Service
mutatingwebhookconfigurations                    admissionregistration.k8s.io/v1   false        MutatingWebhookConfiguration
validatingadmissionpolicies                      admissionregistration.k8s.io/v1   false        ValidatingAdmissionPolicy
validatingadmissionpolicybindings                admissionregistration.k8s.io/v1   false        ValidatingAdmissionPolicyBinding
validatingwebhookconfigurations                  admissionregistration.k8s.io/v1   false        ValidatingWebhookConfiguration
customresourcedefinitions           crd,crds     apiextensions.k8s.io/v1           false        CustomResourceDefinition
apiservices                                      apiregistration.k8s.io/v1         false        APIService
controllerrevisions                              apps/v1                           true         ControllerRevision
daemonsets                          ds           apps/v1                           true         DaemonSet
deployments                         deploy       apps/v1                           true         Deployment
replicasets                         rs           apps/v1                           true         ReplicaSet
statefulsets                        sts          apps/v1                           true         StatefulSet
selfsubjectreviews                               authentication.k8s.io/v1          false        SelfSubjectReview
tokenreviews                                     authentication.k8s.io/v1          false        TokenReview
localsubjectaccessreviews                        authorization.k8s.io/v1           true         LocalSubjectAccessReview
selfsubjectaccessreviews                         authorization.k8s.io/v1           false        SelfSubjectAccessReview
selfsubjectrulesreviews                          authorization.k8s.io/v1           false        SelfSubjectRulesReview
subjectaccessreviews                             authorization.k8s.io/v1           false        SubjectAccessReview
horizontalpodautoscalers            hpa          autoscaling/v2                    true         HorizontalPodAutoscaler
cronjobs                            cj           batch/v1                          true         CronJob
jobs                                             batch/v1                          true         Job
certificatesigningrequests          csr          certificates.k8s.io/v1            false        CertificateSigningRequest
leases                                           coordination.k8s.io/v1            true         Lease
bgpconfigurations                                crd.projectcalico.org/v1          false        BGPConfiguration
bgppeers                                         crd.projectcalico.org/v1          false        BGPPeer
blockaffinities                                  crd.projectcalico.org/v1          false        BlockAffinity
caliconodestatuses                               crd.projectcalico.org/v1          false        CalicoNodeStatus
clusterinformations                              crd.projectcalico.org/v1          false        ClusterInformation
felixconfigurations                              crd.projectcalico.org/v1          false        FelixConfiguration
globalnetworkpolicies                            crd.projectcalico.org/v1          false        GlobalNetworkPolicy
globalnetworksets                                crd.projectcalico.org/v1          false        GlobalNetworkSet
hostendpoints                                    crd.projectcalico.org/v1          false        HostEndpoint
ipamblocks                                       crd.projectcalico.org/v1          false        IPAMBlock
ipamconfigs                                      crd.projectcalico.org/v1          false        IPAMConfig
ipamhandles                                      crd.projectcalico.org/v1          false        IPAMHandle
ippools                                          crd.projectcalico.org/v1          false        IPPool
ipreservations                                   crd.projectcalico.org/v1          false        IPReservation
kubecontrollersconfigurations                    crd.projectcalico.org/v1          false        KubeControllersConfiguration
networkpolicies                                  crd.projectcalico.org/v1          true         NetworkPolicy
networksets                                      crd.projectcalico.org/v1          true         NetworkSet
endpointslices                                   discovery.k8s.io/v1               true         EndpointSlice
events                              ev           events.k8s.io/v1                  true         Event
flowschemas                                      flowcontrol.apiserver.k8s.io/v1   false        FlowSchema
prioritylevelconfigurations                      flowcontrol.apiserver.k8s.io/v1   false        PriorityLevelConfiguration
ingressclasses                                   networking.k8s.io/v1              false        IngressClass
ingresses                           ing          networking.k8s.io/v1              true         Ingress
networkpolicies                     netpol       networking.k8s.io/v1              true         NetworkPolicy
runtimeclasses                                   node.k8s.io/v1                    false        RuntimeClass
poddisruptionbudgets                pdb          policy/v1                         true         PodDisruptionBudget
clusterrolebindings                              rbac.authorization.k8s.io/v1      false        ClusterRoleBinding
clusterroles                                     rbac.authorization.k8s.io/v1      false        ClusterRole
rolebindings                                     rbac.authorization.k8s.io/v1      true         RoleBinding
roles                                            rbac.authorization.k8s.io/v1      true         Role
priorityclasses                     pc           scheduling.k8s.io/v1              false        PriorityClass
csidrivers                                       storage.k8s.io/v1                 false        CSIDriver
csinodes                                         storage.k8s.io/v1                 false        CSINode
csistoragecapacities                             storage.k8s.io/v1                 true         CSIStorageCapacity
storageclasses                      sc           storage.k8s.io/v1                 false        StorageClass
volumeattachments                                storage.k8s.io/v1                 false        VolumeAttachment
[root@master30 ~ 14:54:52]# kubectl api-resources
NAME                                SHORTNAMES   APIVERSION                        NAMESPACED   KIND
bindings                                         v1                                true         Binding
componentstatuses                   cs           v1                                false        ComponentStatus
configmaps                          cm           v1                                true         ConfigMap
endpoints                           ep           v1                                true         Endpoints
events                              ev           v1                                true         Event
limitranges                         limits       v1                                true         LimitRange
namespaces                          ns           v1                                false        Namespace
nodes                               no           v1                                false        Node
persistentvolumeclaims              pvc          v1                                true         PersistentVolumeClaim
persistentvolumes                   pv           v1                                false        PersistentVolume
pods                                po           v1                                true         Pod
podtemplates                                     v1                                true         PodTemplate
replicationcontrollers              rc           v1                                true         ReplicationController
resourcequotas                      quota        v1                                true         ResourceQuota
secrets                                          v1                                true         Secret
serviceaccounts                     sa           v1                                true         ServiceAccount
services                            svc          v1                                true         Service
mutatingwebhookconfigurations                    admissionregistration.k8s.io/v1   false        MutatingWebhookConfiguration
validatingadmissionpolicies                      admissionregistration.k8s.io/v1   false        ValidatingAdmissionPolicy
validatingadmissionpolicybindings                admissionregistration.k8s.io/v1   false        ValidatingAdmissionPolicyBinding
validatingwebhookconfigurations                  admissionregistration.k8s.io/v1   false        ValidatingWebhookConfiguration
customresourcedefinitions           crd,crds     apiextensions.k8s.io/v1           false        CustomResourceDefinition
apiservices                                      apiregistration.k8s.io/v1         false        APIService
controllerrevisions                              apps/v1                           true         ControllerRevision
daemonsets                          ds           apps/v1                           true         DaemonSet
deployments                         deploy       apps/v1                           true         Deployment
replicasets                         rs           apps/v1                           true         ReplicaSet
statefulsets                        sts          apps/v1                           true         StatefulSet
selfsubjectreviews                               authentication.k8s.io/v1          false        SelfSubjectReview
tokenreviews                                     authentication.k8s.io/v1          false        TokenReview
localsubjectaccessreviews                        authorization.k8s.io/v1           true         LocalSubjectAccessReview
selfsubjectaccessreviews                         authorization.k8s.io/v1           false        SelfSubjectAccessReview
selfsubjectrulesreviews                          authorization.k8s.io/v1           false        SelfSubjectRulesReview
subjectaccessreviews                             authorization.k8s.io/v1           false        SubjectAccessReview
horizontalpodautoscalers            hpa          autoscaling/v2                    true         HorizontalPodAutoscaler
cronjobs                            cj           batch/v1                          true         CronJob
jobs                                             batch/v1                          true         Job
certificatesigningrequests          csr          certificates.k8s.io/v1            false        CertificateSigningRequest
leases                                           coordination.k8s.io/v1            true         Lease
bgpconfigurations                                crd.projectcalico.org/v1          false        BGPConfiguration
bgppeers                                         crd.projectcalico.org/v1          false        BGPPeer
blockaffinities                                  crd.projectcalico.org/v1          false        BlockAffinity
caliconodestatuses                               crd.projectcalico.org/v1          false        CalicoNodeStatus
clusterinformations                              crd.projectcalico.org/v1          false        ClusterInformation
felixconfigurations                              crd.projectcalico.org/v1          false        FelixConfiguration
globalnetworkpolicies                            crd.projectcalico.org/v1          false        GlobalNetworkPolicy
globalnetworksets                                crd.projectcalico.org/v1          false        GlobalNetworkSet
hostendpoints                                    crd.projectcalico.org/v1          false        HostEndpoint
ipamblocks                                       crd.projectcalico.org/v1          false        IPAMBlock
ipamconfigs                                      crd.projectcalico.org/v1          false        IPAMConfig
ipamhandles                                      crd.projectcalico.org/v1          false        IPAMHandle
ippools                                          crd.projectcalico.org/v1          false        IPPool
ipreservations                                   crd.projectcalico.org/v1          false        IPReservation
kubecontrollersconfigurations                    crd.projectcalico.org/v1          false        KubeControllersConfiguration
networkpolicies                                  crd.projectcalico.org/v1          true         NetworkPolicy
networksets                                      crd.projectcalico.org/v1          true         NetworkSet
endpointslices                                   discovery.k8s.io/v1               true         EndpointSlice
events                              ev           events.k8s.io/v1                  true         Event
flowschemas                                      flowcontrol.apiserver.k8s.io/v1   false        FlowSchema
prioritylevelconfigurations                      flowcontrol.apiserver.k8s.io/v1   false        PriorityLevelConfiguration
ingressclasses                                   networking.k8s.io/v1              false        IngressClass
ingresses                           ing          networking.k8s.io/v1              true         Ingress
networkpolicies                     netpol       networking.k8s.io/v1              true         NetworkPolicy
runtimeclasses                                   node.k8s.io/v1                    false        RuntimeClass
poddisruptionbudgets                pdb          policy/v1                         true         PodDisruptionBudget
clusterrolebindings                              rbac.authorization.k8s.io/v1      false        ClusterRoleBinding
clusterroles                                     rbac.authorization.k8s.io/v1      false        ClusterRole
rolebindings                                     rbac.authorization.k8s.io/v1      true         RoleBinding
roles                                            rbac.authorization.k8s.io/v1      true         Role
priorityclasses                     pc           scheduling.k8s.io/v1              false        PriorityClass
csidrivers                                       storage.k8s.io/v1                 false        CSIDriver
csinodes                                         storage.k8s.io/v1                 false        CSINode
csistoragecapacities                             storage.k8s.io/v1                 true         CSIStorageCapacity
storageclasses                      sc           storage.k8s.io/v1                 false        StorageClass
volumeattachments                                storage.k8s.io/v1                 false        VolumeAttachment
[root@master30 ~ 14:55:08]# kubectl api-resources |head
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
[root@master30 ~ 14:55:28]# kubectl get namespaces default
NAME      STATUS   AGE
default   Active   3h57m
[root@master30 ~ 14:55:58]# kubectl get namespaces default -o name
namespace/default
[root@master30 ~ 14:56:04]# kubectl get namespaces default -o write
error: unable to match a printer suitable for the output format "write", allowed formats are: custom-columns,custom-columns-file,go-template,go-template-file,json,jsonpath,jsonpath-as-json,jsonpath-file,name,template,templatefile,wide,yaml
[root@master30 ~ 14:56:16]# kubectl get namespaces default -o wide
NAME      STATUS   AGE
default   Active   3h58m
[root@master30 ~ 14:56:22]# kubectl get namespaces default -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2026-06-23T02:58:22Z"
  labels:
    kubernetes.io/metadata.name: default
  name: default
  resourceVersion: "38"
  uid: 19bd27a6-2280-45f4-87e6-7cfa671d921d
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@master30 ~ 14:56:28]# kubectl get namespaces default -o yaml >namespace-default.yaml
[root@master30 ~ 14:57:06]# vim namespace-default.yaml
[root@master30 ~ 14:59:12]# mv namespace-default.yaml namespace-webapp.yaml
[root@master30 ~ 14:59:43]# kubectl create namespace webapp
namespace/webapp created
[root@master30 ~ 15:00:05]# kubectl get namespaces
NAME              STATUS   AGE
default           Active   4h1m
kube-node-lease   Active   4h1m
kube-public       Active   4h1m
kube-system       Active   4h1m
webapp            Active   11s
[root@master30 ~ 15:00:16]# cat namespace-webapp.yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2026-06-23T02:58:22Z"
  labels:
    kubernetes.io/metadata.name: default
  name: my
  resourceVersion: "38"
  uid: 19bd27a6-2280-45f4-87e6-7cfa671d921d
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@master30 ~ 15:01:05]# kubectl get namespaces webapp -o yaml > namespace-webapp.yaml
[root@master30 ~ 15:01:44]# vim namespace-webapp.yaml
[root@master30 ~ 15:02:08]# kubectl delete namespaces webapp
namespace "webapp" deleted
[root@master30 ~ 15:02:33]# kubectl create -f namespace-webapp.yaml
namespace/webapp created
[root@master30 ~ 15:02:47]# ls
cni-plugins-linux-amd64-v1.6.0.tgz  namespace-webapp.yaml  nerdctl-1.7.7-linux-amd64.tar.gz
[root@master30 ~ 15:03:06]# kubectl get namespaces
NAME              STATUS   AGE
default           Active   4h5m
kube-node-lease   Active   4h5m
kube-public       Active   4h5m
kube-system       Active   4h5m
webapp            Active   54s
[root@master30 ~ 15:03:41]# kubectl delete namespaces webapp webapp1
namespace "webapp" deleted
Error from server (NotFound): namespaces "webapp1" not found
[root@master30 ~ 15:04:20]# kubectl apply -f namespace-webapp.yaml
namespace/webapp created
[root@master30 ~ 15:04:42]# kubectl get namespaces --show-labels
NAME              STATUS   AGE    LABELS
default           Active   4h6m   kubernetes.io/metadata.name=default
kube-node-lease   Active   4h6m   kubernetes.io/metadata.name=kube-node-lease
kube-public       Active   4h6m   kubernetes.io/metadata.name=kube-public
kube-system       Active   4h6m   kubernetes.io/metadata.name=kube-system
webapp            Active   28s    kubernetes.io/metadata.name=webapp
[root@master30 ~ 15:05:10]# kubectl apply -f calico.yaml
error: the path "calico.yaml" does not exist
[root@master30 ~ 15:05:28]# kubectl get nodes
NAME                STATUS   ROLES           AGE     VERSION
master30.my.cloud   Ready    control-plane   4h7m    v1.30.2
worker31.my.cloud   Ready    <none>          3h57m   v1.30.2
worker32.my.cloud   Ready    <none>          4h5m    v1.30.2
[root@master30 ~ 15:05:40]# cat namespace-webapp.yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2026-06-23T07:00:05Z"
  labels:
    kubernetes.io/metadata.name: webapp
  name: webapp
  resourceVersion: "10082"
  uid: cf1ea705-54ba-449e-98c0-f792c466b548
spec:
  finalizers:
  - kubernetes
status:
  phase: Active
[root@master30 ~ 15:06:44]# kubectl create namespace dbapp --dry-run=client -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: null
  name: dbapp
spec: {}
status: {}
[root@master30 ~ 15:07:07]#  kubectl create namespace dbapp --dry-run -o yaml
W0623 15:08:36.510642   57873 helpers.go:703] --dry-run is deprecated and can be replaced with --dry-run=client.
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: null
  name: dbapp
spec: {}
status: {}

context

bash 复制代码
[root@master30 ~ 16:01:11]# kubectl config set-context kubernetes-1-admin@kubernetes \
  --cluster=kubernetes \
  --user=kubernetes-admin \
  --namespace=webapp \
  --kubeconfig=multi-config

kubectl config set-context kubernetes-2-admin@kubernetes \
  --cluster=kubernetes \
  --user=kubernetes-admin \
  --namespace=webapp \
  --kubeconfig=multi-config
Context "kubernetes-1-admin@kubernetes" created.
Context "kubernetes-2-admin@kubernetes" created.
[root@master30 ~ 16:02:15]# kubectl config get-contexts --kubeconfig multi-config
CURRENT   NAME                            CLUSTER      AUTHINFO           NAMESPACE
          kubernetes-1-admin@kubernetes   kubernetes   kubernetes-admin   webapp
          kubernetes-2-admin@kubernetes   kubernetes   kubernetes-admin   webapp
bash 复制代码
[root@master30 ~ 14:52:01]# kubectl describe pod bbs
Name:             bbs
Namespace:        default
Priority:         0
Service Account:  default
Node:             worker32.my.cloud/10.1.8.32
Start Time:       Wed, 24 Jun 2026 14:50:14 +0800
Labels:           run=bbs
Annotations:      cni.projectcalico.org/containerID: 0f1f75561ded001bb113750f5f9ababa1b7bb56b5c0132910f936c315971fef9
                  cni.projectcalico.org/podIP: 10.224.125.129/32
                  cni.projectcalico.org/podIPs: 10.224.125.129/32
Status:           Pending
IP:
IPs:              <none>
Containers:
  mysql:
    Container ID:
    Image:          docker.io/library/mysql:latest
    Image ID:
    Port:           3306/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:
      MYSQL_ROOT_PASSWORD:  123
      MYSQL_USER:           tom
      MYSQL_PASSWORD:       123
      MYSQL_DATABASE:       bbs
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-88kbg (ro)
  wordpress:
    Container ID:
    Image:          docker.io/library/wordpress:latest
    Image ID:
    Port:           80/TCP
    Host Port:      80/TCP
    State:          Waiting
      Reason:       ContainerCreating
    Ready:          False
    Restart Count:  0
    Environment:
      WORDPRESS_DB_USER:      tom
      WORDPRESS_DB_PASSWORD:  123
      WORDPRESS_DB_NAME:      bbs
      WORDPRESS_DB_HOST:      127.0.0.1
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-88kbg (ro)
Conditions:
  Type                        Status
  PodReadyToStartContainers   False
  Initialized                 True
  Ready                       False
  ContainersReady             False
  PodScheduled                True
Volumes:
  kube-api-access-88kbg:
    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  113s  default-scheduler  Successfully assigned default/bbs to worker32.my.cloud
  Normal  Pulling    112s  kubelet            Pulling image "docker.io/library/mysql:latest"
  Normal  Pulled     12s   kubelet            Successfully pulled image "docker.io/library/mysql:latest" in 1m40.05s (1m40.05s including waiting). Image size: 270854774 bytes.
  Normal  Created    12s   kubelet            Created container mysql
  Normal  Started    12s   kubelet            Started container mysql
  Normal  Pulling    12s   kubelet            Pulling image "docker.io/library/wordpress:latest"

示例文件:blog.yaml

bash 复制代码
[root@master30 ~]# vim pod-blog.yaml
apiVersion: v1
kind: Pod
metadata:
  name: bbs
  labels:
    run: bbs
spec:
  containers:
  - image: docker.io/library/mysql:latest
    imagePullPolicy: IfNotPresent
    name: mysql
    env:
    - name: MYSQL_ROOT_PASSWORD
      value: "123"
    - name: MYSQL_USER
      value: tom
    - name: MYSQL_PASSWORD
      value: "123"
    - name: MYSQL_DATABASE
      value: bbs
    ports:
    - containerPort: 3306
      name: mysql
      protocol: TCP
  - image: docker.io/library/wordpress:latest
    imagePullPolicy: IfNotPresent
    name: wordpress
    env:
    - name: WORDPRESS_DB_USER
      value: tom
    - name: WORDPRESS_DB_PASSWORD
      value: "123"
    - name: WORDPRESS_DB_NAME
      value: bbs
    - name: WORDPRESS_DB_HOST
      value: 127.0.0.1
    ports:
    - containerPort: 80
      name: wordpress
      protocol: TCP
      hostPort: 80

pod 关键属性

bash 复制代码
[root@master30 ~]# kubectl explain pod | grep '^  [a-zA-Z]'
  apiVersion    <string>
  kind  <string>
  metadata  <ObjectMeta>
  spec  <PodSpec>
  status    <PodStatus>

pod.metadata

bash 复制代码
[root@master30 ~]# kubectl explain pod.metadata | grep '^  [a-zA-Z]'
   annotations  <map[string]string>
   clusterName  <string>
   creationTimestamp    <string>
   deletionGracePeriodSeconds   <integer>
   deletionTimestamp    <string>
   finalizers   <[]string>
   generateName <string>
   generation   <integer>
   labels   <map[string]string>
   managedFields    <[]Object>
   name <string>
   namespace    <string>
   ownerReferences  <[]Object>
   resourceVersion  <string>
   selfLink <string>
   uid  <string>

需要关注的属性:labels,name,namespace,deletionGracePeriodSeconds。

pod.spec

bash 复制代码
[root@master30 ~]# kubectl explain pod.spec | grep '^  [a-zA-Z]'
   activeDeadlineSeconds    <integer>
   affinity <Object>
   automountServiceAccountToken <boolean>
   containers   <[]Object> -required-
   dnsConfig    <Object>
   dnsPolicy    <string>
   enableServiceLinks   <boolean>
   ephemeralContainers  <[]Object>
   hostAliases  <[]Object>
   hostIPC  <boolean>
   hostNetwork  <boolean>
   hostPID  <boolean>
   hostname <string>
   imagePullSecrets <[]Object>
   initContainers   <[]Object>
   nodeName <string>
   nodeSelector <map[string]string>
   overhead <map[string]string>
   preemptionPolicy <string>
   priority <integer>
   priorityClassName    <string>
   readinessGates   <[]Object>
   restartPolicy    <string>
   runtimeClassName <string>
   schedulerName    <string>
   securityContext  <Object>
   serviceAccount   <string>
   serviceAccountName   <string>
   setHostnameAsFQDN    <boolean>
   shareProcessNamespace    <boolean>
   subdomain    <string>
   terminationGracePeriodSeconds    <integer>
   tolerations  <[]Object>
   topologySpreadConstraints    <[]Object>
   volumes  <[]Object>

重点关注:containers、nodeName、volumes等。

pod.spec.containers
bash 复制代码
[root@master30 ~]# kubectl explain pod.spec.containers | grep '^   [a-zA-Z]'
   args <[]string>
   command  <[]string>
   env  <[]Object>
   envFrom  <[]Object>
   image    <string>
   imagePullPolicy  <string>
   lifecycle    <Object>
   livenessProbe    <Object>
   name <string> -required-
   ports    <[]Object>
   readinessProbe   <Object>
   resources    <Object>
   securityContext  <Object>
   startupProbe <Object>
   stdin    <boolean>
   stdinOnce    <boolean>
   terminationMessagePath   <string>
   terminationMessagePolicy <string>
   tty  <boolean>
   volumeDevices    <[]Object>
   volumeMounts <[]Object>
   workingDir   <string>

编写 kubernetes 资源文件

python 安装

为后续python开发做准备。

  1. 下载安装包 :打开浏览器,访问Python 官方网站 → 点击顶部 Downloads → 选择 Windows → 在 Stable Releases(稳定版)区域,点击 Python 3.14.x(x 为最新小版本)对应的 Download 按钮 → 选择 Windows installer (64-bit)(64 位系统,主流电脑均支持)。
  2. 运行安装包 :找到下载好的python-3.14.x-amd64.exe文件,双击运行 → 关键步骤 :勾选窗口底部的 Add Python 3.14 to PATH(这一步是让系统能在任意位置调用 Python,必须勾选!) → 点击 Install Now(默认安装,也可选择 Customize installation 自定义路径)。
  3. 验证安装结果 :按下Win + R,输入cmd打开命令提示符 → 输入python --version(注意是两个短横线),如果输出Python 3.14.x,说明安装成功;如果提示 python 不是内部或外部命令,则是 Add to PATH 未勾选,需重新安装并勾选该选项。

pycharm 安装和配置

1 PyCharm 安装

PyCharm 版本选择

  • 社区版(Community):免费开源,支持 Python 核心开发功能,适合新手;
  • 专业版(Professional):付费,支持 Web 开发、数据库等高级功能,适合企业开发。

安装步骤

  1. 访问JetBrains 官网 → 点击 Download → 选择 Community 版本 → 下载对应系统的安装包;

历史版本:https://www.jetbrains.com/pycharm/download/other.html

  1. 实验环境安装 2025.3 版本。

  2. 运行安装包:勾选 Create Desktop Shortcut(创建桌面快捷方式)、Add launchers dir to PATH(可选)→ 点击 Next→ 选择安装路径→ 点击 Install
    volumeMounts <\[\]Object>
    workingDir

    编写 kubernetes 资源文件

    python 安装

    为后续python开发做准备。

    1. 下载安装包:打开浏览器,访问Python 官方网站 → 点击顶部 Downloads → 选择 Windows → 在 Stable Releases(稳定版)区域,点击 Python 3.14.x(x 为最新小版本)对应的 Download 按钮 → 选择 Windows installer (64-bit)(64 位系统,主流电脑均支持)。
    2. 运行安装包:找到下载好的python-3.14.x-amd64.exe文件,双击运行 → 关键步骤:勾选窗口底部的 Add Python 3.14 to PATH(这一步是让系统能在任意位置调用 Python,必须勾选!) → 点击 Install Now(默认安装,也可选择 Customize installation 自定义路径)。
    3. 验证安装结果:按下Win + R,输入cmd打开命令提示符 → 输入python --version(注意是两个短横线),如果输出Python 3.14.x,说明安装成功;如果提示 python 不是内部或外部命令,则是 Add to PATH 未勾选,需重新安装并勾选该选项。

    pycharm 安装和配置

    1 PyCharm 安装

    PyCharm 版本选择

    • 社区版(Community):免费开源,支持 Python 核心开发功能,适合新手;
    • 专业版(Professional):付费,支持 Web 开发、数据库等高级功能,适合企业开发。

    安装步骤

    1. 访问JetBrains 官网 → 点击 Download → 选择 Community 版本 → 下载对应系统的安装包;

    历史版本:https://www.jetbrains.com/pycharm/download/other.html

    1. 实验环境安装 2025.3 版本。
    2. 运行安装包:勾选 Create Desktop Shortcut(创建桌面快捷方式)、Add launchers dir to PATH(可选)→ 点击 Next→ 选择安装路径→ 点击 Install