首页 > 其他分享 >使用kubeadm部署Kubernetes 1.26及其它版本

使用kubeadm部署Kubernetes 1.26及其它版本

时间:2024-03-13 12:00:32浏览次数:29  
标签:Kubernetes kubernetes etc containerd kubelet nginx io kubeadm 1.26

1.系统配置

环境信息:

  • 系统:CentOS Linux release 7.6.1810 (Core)
  • k8s版本:1.26.0 (可自己选择)
IP 主机名 规划角色
192.168.223.123 auto-inspaction-1 master
192.168.223.68 auto-inspaction-0 node
192.168.223.73 auto-inspaction-2 node

在各个主机上完成下面的系统配置。

如果各个主机启用了防火墙或安全组策略,需要开放Kubernetes各个组件所需要的端口,可以查看Ports and Protocols中的内容, 开放相关端口或者关闭主机的防火墙。

禁用SELINUX:

setenforce 0;sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config;sed -i 's/SELINUX=permissive/SELINUX=disabled/' /etc/selinux/config

创建/etc/modules-load.d/containerd.conf配置文件:

cat << EOF > /etc/modules-load.d/containerd.conf
overlay
br_netfilter
EOF

执行以下命令使配置生效:

modprobe overlay
modprobe br_netfilter

创建/etc/sysctl.d/99-kubernetes-cri.conf配置文件:

cat << EOF > /etc/sysctl.d/99-kubernetes-cri.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.ip_forward = 1
user.max_user_namespaces=28633
EOF

执行以下命令使配置生效:

sysctl -p /etc/sysctl.d/99-kubernetes-cri.conf

配置服务器支持开启ipvs的前提条件:
由于ipvs已经加入到了内核的主干,所以为kube-proxy开启ipvs的前提需要加载以下的内核模块:

ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
nf_conntrack_ipv4

在各个服务器节点上执行以下脚本:

cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack_ipv4
EOF

赋权:

chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules && lsmod | grep -e ip_vs -e nf_conntrack_ipv4

上面脚本创建了的/etc/sysconfig/modules/ipvs.modules文件,保证在节点重启后能自动加载所需模块。
使用lsmod | grep -e ip_vs -e nf_conntrack_ipv4命令查看是否已经正确加载所需的内核模块。

接下来还需要确保各个节点上已经安装了ipset软件包,为了便于查看ipvs的代理规则,最好安装一下管理工具ipvsadm。

yum install -y ipset ipvsadm

如果不满足以上前提条件,则即使kube-proxy的配置开启了ipvs模式,也会退回到iptables模式。

2.部署容器运行时Containerd

在各个服务器节点上安装容器运行时Containerd。
下载Containerd的二进制包,可先在网络可达的机器上下载好,再上传到服务器:

wget https://github.com/containerd/containerd/releases/download/v1.6.14/cri-containerd-cni-1.6.14-linux-amd64.tar.gz

cri-containerd-cni-1.6.14-linux-amd64.tar.gz压缩包中已经按照官方二进制部署推荐的目录结构布局好。 里面包含了systemd配置文件,containerd以及cni的部署文件。 将解压缩到系统的根目录/中:

tar -zxvf cri-containerd-cni-1.6.14-linux-amd64.tar.gz -C /

etc/
etc/cni/
etc/cni/net.d/
etc/cni/net.d/10-containerd-net.conflist
etc/systemd/
etc/systemd/system/
etc/systemd/system/containerd.service
etc/crictl.yaml
usr/
usr/local/
usr/local/sbin/
usr/local/sbin/runc
usr/local/bin/
usr/local/bin/containerd-stress
usr/local/bin/containerd-shim
usr/local/bin/containerd-shim-runc-v1
usr/local/bin/crictl
usr/local/bin/critest
usr/local/bin/containerd-shim-runc-v2
usr/local/bin/ctd-decoder
usr/local/bin/containerd
usr/local/bin/ctr
opt/
opt/cni/
opt/cni/bin/
opt/cni/bin/ptp
opt/cni/bin/bandwidth
opt/cni/bin/static
opt/cni/bin/dhcp
...
opt/containerd/
opt/containerd/cluster/

注意 经测试cri-containerd-cni-1.6.4-linux-amd64.tar.gz包中包含的runc在CentOS 7下的动态链接有问题,这里从runc的github上单独下载runc,并替换上面安装的containerd中的runc:

wget https://github.com/opencontainers/runc/releases/download/v1.1.2/runc.amd64
mv runc.amd64 runc;\cp runc /usr/local/sbin/

接下来生成containerd的配置文件:

mkdir -p /etc/containerd
containerd config default > /etc/containerd/config.toml

根据文档Container runtimes中的内容,对于使用systemd作为init system的Linux的发行版,使用systemd作为容器的cgroup driver可以确保服务器节点在资源紧张的情况更加稳定,因此这里配置各个节点上containerd的cgroup driver为systemd。

修改前面生成的配置文件/etc/containerd/config.toml:

[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
  ...
  [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc.options]
    SystemdCgroup = true

再修改/etc/containerd/config.toml中的sandbox_image镜像源:

[plugins."io.containerd.grpc.v1.cri"]
  ...
  # sandbox_image = "k8s.gcr.io/pause:3.6"
  sandbox_image = "registry.aliyuncs.com/google_containers/pause:3.9"

配置containerd开机启动,并启动containerd:

systemctl enable containerd --now

使用crictl测试一下,确保可以打印出版本信息并且没有错误信息输出:

crictl version
Version:  0.1.0
RuntimeName:  containerd
RuntimeVersion:  v1.6.14
RuntimeApiVersion:  v1

3.使用kubeadm部署Kubernetes

下面在各节点安装kubeadm和kubelet,创建yum源:

cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=1
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
        http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum makecache fast

跟根据后缀修改自己想要的版本,如kubelet-1.28.0* kubeadm-1.28.0* kubectl-1.28.0*,不指定默认则下载的是yum源里面最新的kubelet kubeadm kubectl。

yum install -y kubelet-1.26.0* kubeadm-1.26.0* kubectl-1.26.0*

运行kubelet --help可以看到原来kubelet的绝大多数命令行flag参数都被DEPRECATED了,官方推荐我们使用--config指定配置文件,并在配置文件中指定原来这些flag所配置的内容。具体内容可以查看这里Set Kubelet parameters via a config file

最初Kubernetes这么做是为了支持动态Kubelet配置(Dynamic Kubelet Configuration),但动态Kubelet配置特性从k8s 1.22中已弃用,并在1.24中被移除。如果需要调整集群汇总所有节点kubelet的配置,还是推荐使用ansible等工具将配置分发到各个节点。
kubelet的配置文件必须是json或yaml格式,具体可查看这里
Kubernetes 1.8开始要求关闭系统的Swap,如果不关闭,默认配置下kubelet将无法启动。 关闭系统的Swap方法如下:

swapoff -a

修改/etc/fstab文件,注释掉 SWAP 的自动挂载,使用free -m确认swap已经关闭。
swappiness参数调整,修改/etc/sysctl.d/99-kubernetes-cri.conf添加下面一行,再执行sysctl -p /etc/sysctl.d/99-kubernetes-cri.conf使修改生效。

vm.swappiness=0

4.使用kubeadm init初始化集群

在各节点开机启动kubelet服务:

systemctl enable kubelet.service

使用kubeadm config print init-defaults --component-configs KubeletConfiguration可以打印集群初始化默认的使用的配置,这里不在贴默认配置。

从默认的配置中可以看到,可以使用imageRepository定制在集群初始化时拉取k8s所需镜像的地址。以下配置是基于默认的配置定制出本次使用kubeadm初始化集群所需的配置文件kubeadm.yaml,特别注意修改advertiseAddress为你的master节点主机地址。

kubernetesVersion: 1.26.0 需要与上面 yum install -y kubelet-1.26.0* kubeadm-1.26.0* kubectl-1.26.0*安装的软件包版本保持一直

cat <<EOF > kubeadm.yaml
apiVersion: kubeadm.k8s.io/v1beta3
kind: InitConfiguration
localAPIEndpoint:
  advertiseAddress: 192.168.223.123
  bindPort: 6443
nodeRegistration:
  criSocket: unix:///run/containerd/containerd.sock
  taints:
  - effect: PreferNoSchedule
    key: node-role.kubernetes.io/master
---
apiVersion: kubeadm.k8s.io/v1beta3
kind: ClusterConfiguration
kubernetesVersion: 1.26.0
imageRepository: registry.aliyuncs.com/google_containers
networking:
  podSubnet: 10.244.0.0/16
---
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
cgroupDriver: systemd
failSwapOn: false
---
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: ipvs
EOF

这里定制了imageRepository为阿里云的registry,避免因gcr被墙,无法直接拉取镜像。criSocket设置了容器运行时为containerd。 同时设置kubelet的cgroupDriver为systemd,设置kube-proxy代理模式为ipvs

在开始初始化集群之前,先在各个服务器节点上拉取所k8s需要的容器镜像。

kubeadm config images pull --config kubeadm.yaml

[config/images] Pulled registry.aliyuncs.com/google_containers/kube-apiserver:v1.26.0
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-controller-manager:v1.26.0
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-scheduler:v1.26.0
[config/images] Pulled registry.aliyuncs.com/google_containers/kube-proxy:v1.26.0
[config/images] Pulled registry.aliyuncs.com/google_containers/pause:3.9
[config/images] Pulled registry.aliyuncs.com/google_containers/etcd:3.5.6-0
[config/images] Pulled registry.aliyuncs.com/google_containers/coredns:v1.9.3

接下来使用kubeadm初始化集群,执行下面的命令:

kubeadm config images pull --config kubeadm.yaml

[init] Using Kubernetes version: v1.26.0
[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 [auto-inspaction-1 kubernetes kubernetes.default kubernetes.default.svc kubernetes.default.svc.cluster.local] and IPs [10.96.0.1 192.168.223.123]
[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 [auto-inspaction-1 localhost] and IPs [192.168.223.123 127.0.0.1 ::1]
[certs] Generating "etcd/peer" certificate and key
[certs] etcd/peer serving cert is signed for DNS names [auto-inspaction-1 localhost] and IPs [192.168.223.123 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 "kubelet.conf" kubeconfig file
[kubeconfig] Writing "controller-manager.conf" kubeconfig file
[kubeconfig] Writing "scheduler.conf" kubeconfig file
[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
[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"
[etcd] Creating static Pod manifest for local etcd in "/etc/kubernetes/manifests"
[wait-control-plane] Waiting for the kubelet to boot up the control plane as static Pods from directory "/etc/kubernetes/manifests". This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.
[apiclient] All control plane components are healthy after 105.073330 seconds
[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 auto-inspaction-1 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 auto-inspaction-1 as control-plane by adding the taints [node-role.kubernetes.io/master:PreferNoSchedule]
[bootstrap-token] Using token: e0q0vm.10lhzrwx4gnbcp57
[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 192.168.223.123:6443 --token e0q0vm.10lhzrwx4gnbcp57 \
        --discovery-token-ca-cert-hash sha256:9b51a862194776913af55246e69b87431bab1b7cbf2117ec6aec9efc7b323821

上面记录了完成的初始化输出的内容,根据输出的内容基本上可以看出手动初始化安装一个Kubernetes集群所需要的关键步骤。 其中有以下关键内容:

  • [certs]生成相关的各种证书
  • [kubeconfig]生成相关的kubeconfig文件
  • [kubelet-start]生成kubelet的配置文件/var/lib/kubelet/config.yaml
  • [control-plane]使用/etc/kubernetes/manifests目录中的yaml文件创建apiserver、controller-manager、scheduler的静态pod
  • [bootstraptoken]生成token记录下来,后边使用kubeadm join往集群中添加节点时会用到
  • [addons]安装基本插件:CoreDNS, kube-proxy

下面的命令是配置常规用户如何使用kubectl访问集群:

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

最后给出了将另外其它节点加入集群的命令:

kubeadm join 192.168.223.123:6443 --token e0q0vm.10lhzrwx4gnbcp57 \
        --discovery-token-ca-cert-hash sha256:9b51a862194776913af55246e69b87431bab1b7cbf2117ec6aec9efc7b323821

查看一下集群状态,确认个组件都处于healthy状态:

kubectl  get cs
Warning: v1 ComponentStatus is deprecated in v1.19+
NAME                 STATUS    MESSAGE                         ERROR
scheduler            Healthy   ok
etcd-0               Healthy   {"health":"true","reason":""}
controller-manager   Healthy   ok

集群初始化如果遇到问题,可以使用kubeadm reset命令进行清理。

5.安装包管理器helm

Helm是Kubernetes的包管理器,后续流程也将可以使用Helm安装Kubernetes的常用组件。 这里先在master节点上安装helm。

wget https://get.helm.sh/helm-v3.10.3-linux-amd64.tar.gz
tar -zxvf helm-v3.10.3-linux-amd64.tar.gz
mv linux-amd64/helm  /usr/local/bin/

执行helm list确认没有错误输出:

helm list
NAME    NAMESPACE       REVISION        UPDATED STATUS  CHART   APP VERSION

6.在线部署flannel网络(flannel与Calico选其中一个部署)

$ kubectl apply -f https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml

$ kubectl get pod  -n kube-flannel -o wide
NAME                    READY   STATUS    RESTARTS   AGE   IP               NODE                NOMINATED NODE   READINESS GATES
kube-flannel-ds-dl5bg   1/1     Running   0          23m   192.168.223.68   auto-inspaction-1   <none>           <none>

7.部署Calico网络(flannel与Calico选其中一个部署)

选择calico作为k8s的Pod网络组件,下面使用helm在k8s集群中安装calico。
下载tigera-operator的helm chart:

wget https://github.com/projectcalico/calico/releases/download/v3.24.5/tigera-operator-v3.24.5.tgz

可以执行查看这个chart的中可定制的默认配置:helm show values tigera-operator-v3.24.5.tgz这里不再贴默认配置
本环境定制的values.yaml如下:

# 可针对上面的配置进行定制,例如calico的镜像改成从私有库拉取。
# 这里只是个人本地环境测试k8s新版本,这里只有下面几行配置
apiServer:
  enabled: false

使用helm安装calico:

helm install calico tigera-operator-v3.24.5.tgz -n kube-system  --create-namespace -f values.yaml

等待并确认所有pod处于Running状态:

kubectl get pod -A |grep -E 'calico|tigera'
NAME                                       READY   STATUS    RESTARTS   AGE
calico-kube-controllers-67df98bdc8-rwlq6   1/1     Running   0          22h
calico-node-5pkkn                          1/1     Running   0          22h
calico-node-wtxpk                          1/1     Running   0          22h
calico-node-xgj8t                          1/1     Running   0          22h
calico-typha-5bf9c7b58-2w6gc               1/1     Running   0          22h
calico-typha-5bf9c7b58-jx575               1/1     Running   0          22h
tigera-operator-7795f5d79b-cflnb   1/1     Running   0          22h

查看一下calico向k8s中添加的api资源:

kubectl api-resources |grep calico
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 
..........................

这些api资源是属于calico的,因此不建议使用kubectl来管理,推荐按照calicoctl来管理这些api资源。 将calicoctl安装为kubectl的插件:

cd /usr/local/bin
curl -o kubectl-calico -O -L  "https://github.com/projectcalico/calicoctl/releases/download/v3.21.5/calicoctl-linux-amd64" 
chmod +x kubectl-calico

验证插件正常工作:

kubectl calico -h

8.验证k8s DNS是否可用

首次验证:

kubectl run curl --image=radial/busyboxplus:curl -it
If you don't see a command prompt, try pressing enter.
[ root@curl:/ ]$ nslookup kubernetes.default
Server:    10.96.0.10
Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes.default
Address 1: 10.96.0.1 kubernetes.default.svc.cluster.local

后续进入相同的容器可继续执行命令:

kubectl exec -it curl -- /bin/sh

9.使用Helm部署ingress-nginx

了便于将集群中的服务暴露到集群外部,需要使用Ingress。接下来使用Helm将ingress-nginx部署到Kubernetes上。 Nginx Ingress Controller被部署在Kubernetes的边缘节点上。
这里将主机 auto-inspaction-0 作为边缘节点,打上Label:

kubectl label node auto-inspaction-0 node-role.kubernetes.io/edge=

下载ingress-nginx的helm chart:

wget https://github.com/kubernetes/ingress-nginx/releases/download/helm-chart-4.4.2/ingress-nginx-4.4.2.tgz

执行helm show values ingress-nginx-4.4.2.tgz查看ingress-nginx-4.4.2.tgz这个chart的m默认配置,这里不再贴出默认配置。

对ingress-values.yaml配置定制如下,可以直接用:

cat <<EOF > ingress-values.yaml
controller:
  ingressClassResource:
    name: nginx
    enabled: true
    default: true
    controllerValue: "k8s.io/ingress-nginx"
  admissionWebhooks:
    enabled: false
  replicaCount: 1
  image:
    # registry: registry.k8s.io
    # image: ingress-nginx/controller
    # tag: "v1.5.1"
    registry: docker.io
    image: unreachableg/registry.k8s.io_ingress-nginx_controller
    tag: "v1.5.1"
    digest: sha256:97fa1ff828554ff4ee1b0416e54ae2238b27d1faa6d314d5a94a92f1f99cf767
  hostNetwork: true
  nodeSelector:
    node-role.kubernetes.io/edge: ''
  affinity:
    podAntiAffinity:
        requiredDuringSchedulingIgnoredDuringExecution:
        - labelSelector:
            matchExpressions:
            - key: app
              operator: In
              values:
              - nginx-ingress
            - key: component
              operator: In
              values:
              - controller
          topologyKey: kubernetes.io/hostname
  tolerations:
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: NoSchedule
      - key: node-role.kubernetes.io/master
        operator: Exists
        effect: PreferNoSchedule
EOF

nginx ingress controller的副本数replicaCount为1,将被调度到node1这个边缘节点上。这里并没有指定nginx ingress controller service的externalIPs,而是通过hostNetwork: true设置nginx ingress controller使用宿主机网络。 因为k8s.gcr.io被墙,这里替换成unreachableg/registry.k8s.io_ingress-nginx_controller提前拉取一下镜像:

crictl pull unreachableg/registry.k8s.io_ingress-nginx_controller:v1.5.1

部署:

helm install ingress-nginx ingress-nginx-4.4.2.tgz --create-namespace -n ingress-nginx -f ingress-values.yaml

查看部署结果

kubectl get pods -n ingress-nginx
NAME                                       READY   STATUS    RESTARTS   AGE
ingress-nginx-controller-7c96f857f-szcct   1/1     Running   0          22h

创建deployment service ingress测试:

cat <<EOF > nginx.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.13.12
        ports:
        - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80
  type: NodePort
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: "k8s.example.com"
    http:
      paths:
      - pathType: Prefix
        path: "/app"
        backend:
          service:
            name: nginx-service
            port:
              number: 80
EOF

执行创建测试资源,并检查相应资源状态。

kubectl create -f nginx.yaml
kubectl get pod
NAME                                READY   STATUS    RESTARTS      AGE
curl                                1/1     Running   2 (25m ago)   46h
nginx-deployment-65fd9f9d8b-w7r7g   1/1     Running   1 (25m ago)   36m
[root@auto-inspaction-0 k8s-1.26]# kubectl get pod,svc,ingress
NAME                                    READY   STATUS    RESTARTS      AGE
pod/curl                                1/1     Running   2 (25m ago)   46h
pod/nginx-deployment-65fd9f9d8b-w7r7g   1/1     Running   1 (25m ago)   36m

NAME                    TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
service/kubernetes      ClusterIP   10.96.0.1        <none>        443/TCP        47h
service/nginx-service   NodePort    10.110.125.169   <none>        80:30403/TCP   23m

NAME                                      CLASS   HOSTS             ADDRESS   PORTS   AGE
ingress.networking.k8s.io/nginx-ingress   nginx   k8s.example.com             80      15m

浏览器测试访问nginx,出现Welcome to nginx!则成功,访问前提电脑要配置域名地址解析
https://k8s.example.com/app

10.在线部署kubernetes dashbord


# 部署kubernetes dashborad
$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml

# 测试dashborad, 返回:HTTP/1.1 200 OK则正常。
$ curl -ki https://$(kubectl get svc -n kubernetes-dashboard   kubernetes-dashboard | grep -Eo '([0-9]{1,3}\.){3}.[0-9]{1,3}')


# 访问dashborad,可以先把dashborad service里面的 type: ClusterIP 改为type: NodePort
# kubectl edit svc -n kubernetes-dashboard   kubernetes-dashboard

# 找到NodePort端口
$  kubectl get svc -n kubernetes-dashboard   kubernetes-dashboard -o yaml| grep nodePort
$ - nodePort: 32696

# 宿主机的IP访问dashborad
$ https://192.168.3.226:32696

# 使用 Kubernetes 的服务帐户机制创建新用户,授予该用户管理员权限并使用与该用户绑定的令牌登录仪表板。
$ cat << EOF > /root/admin-token.yaml
## Creating a Service Account
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: admin-user
  namespace: kubernetes-dashboard

## Creating a ClusterRoleBinding
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: admin-user
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: admin-user
  namespace: kubernetes-dashboard

## Getting a Bearer Token for ServiceAccount
# kubectl -n kubernetes-dashboard create token admin-user --duration=8760h


## Getting a long-lived Bearer Token for ServiceAccount
---
apiVersion: v1
kind: Secret
metadata:
  name: admin-user
  namespace: kubernetes-dashboard
  annotations:
    kubernetes.io/service-account.name: "admin-user"
type: kubernetes.io/service-account-token
EOF

# 获取token登录仪表板
kubectl get secret admin-user -n kubernetes-dashboard -o jsonpath={".data.token"} | base64 -d

eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc0SWU1S2cxUzVoSll5S3pZQmh1b1pFMjR4ZlpDSDlUS1NwRW9JRFhfVW8ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJrdWJlcm5ldGVzLWRhc2hib2FyZCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VjcmV0Lm5hbWUiOiJhZG1pbi11c2VyIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImFkbWluLXVzZXIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51aWQiOiIzOGM0N2RmZC0wNjk0LTQ4MGEtOTYzNy1kNmQ3MzE2ODU3MTMiLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZXJuZXRlcy1kYXNoYm9hcmQ6YWRtaW4tdXNlciJ9.3Mf3IlS0hRnt3FlVAbY1Z7omWZ4MAfV7ILXLM6zzGnkHpEtMwx1QC5fwCeyMLarfo3eEzS-BkbkCgi8QZ0btdnUDC_7y1j4XckblazcXVI98Jff0UOu58KXy5KJzsRVTT25GKvPHsE8sJUOkx7SUaoLN-XtwRqF8wfUADgNQAHAEUtuhpxk1KxHaxUmffgHsa3VhMVAJxy4G80ZhFwAu9_HabFXzmq8NAxQm0I6W3UBLk0JyLAu5QOz2j68AW9iPFDx0pYyucO7IiwA1jOwwgYjXY7xSamxJK-xWDrTP-LqLN03Lw90IZKDzWmb-SDZp41BWC9ppF7LKAFgNsU8QXQ

参考文献:kubeadm-install-kubernetes-1.26

标签:Kubernetes,kubernetes,etc,containerd,kubelet,nginx,io,kubeadm,1.26
From: https://www.cnblogs.com/acommoners/p/18067794

相关文章

  • 升级kubeadm 集群(只有master单节点)
    具体步骤可以参考kubernetes官网:https://kubernetes.io/zh-cn/docs/tasks/administer-cluster/kubeadm/kubeadm-upgrade/确定升级到哪个版本示例是从同版本1.28.2升级到1.28.7所以使用操作系统的包管理器找到最新可按照的版本中,是否有需要的补丁版本sudoyumlist--showdupl......
  • kubernetes 安装 kubernetes-dashboard 7.x
    kubernetes安装kubernetes-dashboard7.x介绍Kubernetes仪表板是Kubernetes集群的通用、基于Web的UI。它允许用户管理集群中运行的应用程序并对其进行故障排除,以及管理集群本身。从7.x版开始,不再支持基于Manifest的安装。现在只支持基于Helm的安装。由于多容器设置和对Kong网......
  • 将Asp.net Core 微服务容器部署到 Kubernetes
    将微服务容器部署到KubernetesKubernetes会为你运行容器,需要通过YAML文件描述希望Kubernetes执行的操作,在Kubernetes上部署和运行后端服务简单操作如下步骤安装Kubernetes工具和实现我们需要同时安装kubectl工具和Kubernetes实现按照参考:https://www.cnblogs.co......
  • kubernetes-服务器重启后集群检查
    kubernetes-服务器重启后集群检查搭建k8s集群的服务器因机房断电原因挂掉。以下是恢复后的常规检查检查k8s的master组件服务systemctlstatuskube-apiserver.servicekube-controller-manager.servicekube-scheduler.service检查k8s的node组件服务systemctlstatuskubel......
  • Kubernetes与Docker Swarm的区别如何
    1)安装和部署:k8s安装很复杂;但是一旦安装完毕,集群就非常强大,DockerSwarm安装非常简单;但是集群不是很强大;2)图形用户界面:k8s有,DockerSwarm无;3)可伸缩性:k8s支持,DockerSwarm比k8s快5倍;4)自动伸缩:k8s有,DockerSwarm无;5)负载均衡:k8s在不同的Pods中的不同容器之间平衡负载流量,需要手......
  • Kubernetes 网络
    简述Kubernetes网络模型Kubernetes网络模型中每个Pod都拥有一个独立的IP地址,不管它们是否运行在同一个Node(宿主机)中,都要求它们可以直接通过对方的IP进行访问;同时为每个Pod都设置一个IP地址的模型使得同一个Pod内的不同容器会共享同一个网络命名空间,也就是同一个Linux网络协议栈......
  • Kubernetes PodSecurityPolicy
    简述KubernetesPodSecurityPolicy机制KubernetesPodSecurityPolicy是为了更精细地控制Pod对资源的使用方式以及提升安全策略。在开启PodSecurityPolicy准入控制器后,Kubernetes默认不允许创建任何Pod,需要创建PodSecurityPolicy策略和相应的RBAC授权策略(AuthorizingPolicies),Pod......
  • 简述Kubernetes各模块如何与API Server通信
    K8sAPIServer作为集群的核心,负责集群各功能模块之间的通信。集群内的各个功能模块通过APIServer将信息存入etcd,当需要获取和操作这些数据时,则通过APIServer提供的REST接口(用GET、LIST或WATCH方法)来实现,从而实现各模块之间的信息交互。1)kubelet进程与APIServer的交互:每个Nod......
  • 简述Kubernetes准入机制
    在对集群进行请求时,每个准入控制代码都按照一定顺序执行。如果有一个准入控制拒绝了此次请求,那么整个请求的结果将会立即返回,并提示用户相应的error信息,准入控制(AdmissionControl)准入控制本质上为一段准入代码,在对kubernetesapi的请求过程中,顺序为:先经过认证&授权,然后执行准入......
  • 简述Kubernetes如何保证集群的安全性
    1)基础设施方面:保证容器与其所在宿主机的隔离;2)用户权限:划分普通用户和管理员的角色;3)APIServer的认证授权:Kubernetes集群中所有资源的访问和变更都是通过KubernetesAPIServer来实现的,因此需要建议采用更安全的HTTPS或Token来识别和认证客户端身份(Authentication),以及随后访问权......