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