1. Kubernetes概述
Kubernetes是一种开源的容器编排平台,用于自动化容器的部署、扩展和管理。它提供了容器编排、服务发现、负载均衡、自动扩展、滚动更新等功能,是现代云原生应用的基础平台。更多学习教程www.fgedu.net.cn
# kubectl version
Client Version: version.Info{Major:”1″, Minor:”21″, GitVersion:”v1.21.0″, GitCommit:”cb303e613a121a29364f75cc67d3d580833a7479″, GitTreeState:”clean”, BuildDate:”2021-04-08T16:31:21Z”, GoVersion:”go1.16.1″, Compiler:”gc”, Platform:”linux/amd64″}
Server Version: version.Info{Major:”1″, Minor:”21″, GitVersion:”v1.21.0″, GitCommit:”cb303e613a121a29364f75cc67d3d580833a7479″, GitTreeState:”clean”, BuildDate:”2021-04-08T16:25:06Z”, GoVersion:”go1.16.1″, Compiler:”gc”, Platform:”linux/amd64″}
# 查看集群信息
# kubectl cluster-info
Kubernetes control plane is running at https://192.168.1.100:6443
CoreDNS is running at https://192.168.1.100:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use ‘kubectl cluster-info dump’.
2. Kubernetes安装
Kubernetes可以通过多种方式安装,包括kubeadm、kubespray、minikube等。学习交流加群风哥微信: itpux-com
# 安装kubeadm、kubelet和kubectl
# yum install -y kubelet kubeadm kubectl
# 启动kubelet服务
# systemctl start kubelet
# systemctl enable kubelet
# 初始化Kubernetes集群
# kubeadm init –pod-network-cidr=10.244.0.0/16
[init] Using Kubernetes version: v1.21.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’
[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
[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 server] and IPs [10.96.0.1 192.168.1.100]
[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 [fgedudb server] and IPs [127.0.0.1 ::1 192.168.1.100]
[certs] Generating “etcd/peer” certificate and key
[certs] etcd/peer serving cert is signed for DNS names [fgedudb server] and IPs [127.0.0.1 ::1 192.168.1.100]
[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
[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”
[wait-control-plane] This can take up to 4m0s
[apiclient] All control plane components are healthy after 10.501286 seconds
[upload-config] Storing the configuration used in ConfigMap “kubeadm-config” in the “kube-system” Namespace
[kubelet] Creating a ConfigMap “kubelet-config-1.21” 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 server as control-plane by adding the labels “node-role.kubernetes.io/master=”” and “node-role.kubernetes.io/control-plane=””
[mark-control-plane] Marking the node server as control-plane by adding the taints [node-role.kubernetes.io/master:NoSchedule]
[bootstrap-token] Using token: abcdef.1234567890abcdef
[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 “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.1.100:6443 –token abcdef.1234567890abcdef \ –discovery-token-ca-cert-hash sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
# 安装网络插件
# kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
# 查看节点状态
# kubectl get nodes
NAME STATUS ROLES AGE VERSION
server Ready control-plane,master 10m v1.21.0
3. Kubernetes基础
Kubernetes的核心概念包括Pod、Service、Deployment、ConfigMap、Secret等,理解这些概念是使用Kubernetes的基础。
# kubectl –help
# 查看Kubernetes资源类型
# kubectl api-resources
# 查看集群节点
# kubectl get nodes
NAME STATUS ROLES AGE VERSION
server Ready control-plane,master 10m v1.21.0
# 查看命名空间
# kubectl get namespaces
NAME STATUS AGE
default Active 10m
kube-node-lease Active 10m
kube-public Active 10m
kube-system Active 10m
# 查看系统Pod
# kubectl get pods -n kube-system
NAME READY STATUS RESTARTS AGE
coredns-558bd4d5db-2x56v 1/1 Running 0 10m
coredns-558bd4d5db-6x78k 1/1 Running 0 10m
etcd-server 1/1 Running 0 10m
kube-apiserver-server 1/1 Running 0 10m
kube-controller-manager-server 1/1 Running 0 10m
kube-flannel-ds-amd64-5x78k 1/1 Running 0 5m
kube-proxy-5x78k 1/1 Running 0 10m
kube-scheduler-server 1/1 Running 0 10m
4. Pod管理
Pod是Kubernetes的最小部署单位,包含一个或多个容器。
# cat pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
# 部署Pod
# kubectl apply -f pod.yaml
pod/nginx-pod created
# 查看Pod状态
# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-pod 1/1 Running 0 1m
# 查看Pod详情
# kubectl describe pod nginx-pod
Name: nginx-pod
Namespace: default
Priority: 0
Node: server/192.168.1.100
Start Time: Wed, 30 Mar 2026 10:00:00 +0800
Labels: app=nginx
Annotations:
Status: Running
IP: 10.244.0.2
IPs:
IP: 10.244.0.2
Containers:
nginx:
Container ID: docker://1234567890abcdefghijklmnopqrstuvwxyz
Image: nginx:latest
Image ID: docker-pullable://nginx@sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Wed, 30 Mar 2026 10:00:00 +0800
Ready: True
Restart Count: 0
Environment:
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-5x78k (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-5x78k:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-5x78k
Optional: false
QoS Class: BestEffort
Node-Selectors:
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 1m default-scheduler Successfully assigned default/nginx-pod to server
Normal Pulling 1m kubelet Pulling image “nginx:latest”
Normal Pulled 1m kubelet Successfully pulled image “nginx:latest” in 5.234s
Normal Created 1m kubelet Created container nginx
Normal Started 1m kubelet Started container nginx
# 删除Pod
# kubectl delete pod nginx-pod
pod “nginx-pod” deleted
5. 服务管理
Service用于暴露Pod的网络服务,支持ClusterIP、NodePort、LoadBalancer等类型。
# cat service.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
– port: 80
targetPort: 80
type: NodePort
# 部署Service
# kubectl apply -f service.yaml
service/nginx-service created
# 查看Service状态
# kubectl get services
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1
nginx-service NodePort 10.100.200.100
# 查看Service详情
# kubectl describe service nginx-service
Name: nginx-service
Namespace: default
Labels:
Annotations:
Selector: app=nginx
Type: NodePort
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.100.200.100
IPs: 10.100.200.100
Port:
TargetPort: 80/TCP
NodePort:
Endpoints: 10.244.0.2:80
Session Affinity: None
External Traffic Policy: Cluster
Events:
# 访问Service
# curl http://192.168.1.100:30080
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.
For online documentation and support please refer to
nginx.org.
Commercial support is available at
nginx.com.
Thank you for using nginx.
6. 部署管理
Deployment用于管理Pod的部署和更新,支持滚动更新、回滚等功能。
# cat deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
# 部署Deployment
# kubectl apply -f deployment.yaml
deployment.apps/nginx-deployment created
# 查看Deployment状态
# kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-deployment 3/3 3 3 1m
# 查看Pod状态
# kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-deployment-1234567890-abcde 1/1 Running 0 1m
nginx-deployment-1234567890-fghij 1/1 Running 0 1m
nginx-deployment-1234567890-klmno 1/1 Running 0 1m
# 扩展Deployment
# kubectl scale deployment nginx-deployment –replicas=5
deployment.apps/nginx-deployment scaled
# 查看扩展后的状态
# kubectl get deployments
NAME READY UP-TO-DATE AVAILABLE AGE
nginx-deployment 5/5 5 5 2m
# 更新Deployment
# kubectl set image deployment nginx-deployment nginx=nginx:1.19.10
deployment.apps/nginx-deployment image updated
# 查看更新状态
# kubectl rollout status deployment nginx-deployment
Waiting for deployment “nginx-deployment” rollout to finish: 3 of 5 updated replicas are available…
deployment “nginx-deployment” successfully rolled out
7. 配置管理
ConfigMap用于存储配置数据,支持环境变量、配置文件等方式使用。
# cat configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
nginx.conf: |
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
server {
listen 80;
server_name fgedudb;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}
# 部署ConfigMap
# kubectl apply -f configmap.yaml
configmap/nginx-config created
# 查看ConfigMap
# kubectl get configmaps
NAME DATA AGE
nginx-config 1 1m
# 在Pod中使用ConfigMap
# cat pod-with-configmap.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-with-configmap
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
volumeMounts:
– name: nginx-config-volume
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
volumes:
– name: nginx-config-volume
configMap:
name: nginx-config
# 部署Pod
# kubectl apply -f pod-with-configmap.yaml
pod/nginx-with-configmap created
8. 密钥管理
Secret用于存储敏感数据,如密码、证书等,支持Opaque、kubernetes.io/tls、kubernetes.io/dockerconfigjson等类型。
# kubectl create secret generic my-secret –from-literal=username=admin –from-literal=password=secret123
secret/my-secret created
# 查看Secret
# kubectl get secrets
NAME TYPE DATA AGE
default-token-5x78k kubernetes.io/service-account-token 3 20m
my-secret Opaque 2 1m
# 查看Secret详情
# kubectl describe secret my-secret
Name: my-secret
Namespace: default
Labels:
Annotations:
Type: Opaque
Data
====
password: 8 bytes
username: 5 bytes
# 在Pod中使用Secret
# cat pod-with-secret.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-with-secret
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
env:
– name: USERNAME
valueFrom:
secretKeyRef:
name: my-secret
key: username
– name: PASSWORD
valueFrom:
secretKeyRef:
name: my-secret
key: password
# 部署Pod
# kubectl apply -f pod-with-secret.yaml
pod/pod-with-secret created
# 验证环境变量
# kubectl exec pod-with-secret — env | grep -E “USERNAME|PASSWORD”
USERNAME=admin
PASSWORD=secret123
9. 存储管理
Kubernetes支持多种存储方案,包括EmptyDir、HostPath、PersistentVolume、PersistentVolumeClaim等。
# cat pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 1Gi
accessModes:
– ReadWriteOnce
hostPath:
path: /data
# 部署PersistentVolume
# kubectl apply -f pv.yaml
persistentvolume/my-pv created
# 查看PersistentVolume
# kubectl get pv
NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE
my-pv 1Gi RWO Retain Available 1m
# 创建PersistentVolumeClaim
# cat pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
– ReadWriteOnce
resources:
requests:
storage: 1Gi
# 部署PersistentVolumeClaim
# kubectl apply -f pvc.yaml
persistentvolumeclaim/my-pvc created
# 查看PersistentVolumeClaim
# kubectl get pvc
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
my-pvc Bound my-pv 1Gi RWO 1m
# 在Pod中使用PersistentVolumeClaim
# cat pod-with-pvc.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-with-pvc
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
volumeMounts:
– name: data-volume
mountPath: /usr/share/nginx/html
volumes:
– name: data-volume
persistentVolumeClaim:
claimName: my-pvc
# 部署Pod
# kubectl apply -f pod-with-pvc.yaml
pod/pod-with-pvc created
10. Kubernetes最佳实践
遵循Kubernetes最佳实践可以提高集群的安全性、可靠性和性能。
# kubectl create namespace production
namespace/production created
# 使用资源限制
# cat deployment-with-resources.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 256Mi
# 部署Deployment
# kubectl apply -f deployment-with-resources.yaml
# 使用健康检查
# cat deployment-with-healthchecks.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
namespace: production
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
– name: nginx
image: nginx:latest
ports:
– containerPort: 80
readinessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 5
periodSeconds: 10
livenessProbe:
httpGet:
path: /
port: 80
initialDelaySeconds: 15
periodSeconds: 20
# 部署Deployment
# kubectl apply -f deployment-with-healthchecks.yaml
# 使用水平自动缩放
# kubectl autoscale deployment nginx-deployment –namespace=production –min=3 –max=10 –cpu-percent=80
horizontalpodautoscaler.autoscaling/nginx-deployment autoscaled
# 查看水平自动缩放状态
# kubectl get hpa -n production
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
nginx-deployment Deployment/nginx-deployment 0%/80% 3 10 3 1m
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
