内容大纲
1. 容器编排管理概述
容器编排管理是指自动化容器的部署、扩展、网络配置和管理的过程。随着容器技术的广泛应用,容器编排已成为现代云原生应用的核心基础设施。
主流的容器编排平台包括:
- Kubernetes:最流行的容器编排平台,由Google开源
- Docker Swarm:Docker原生的容器编排工具
- OpenShift:基于Kubernetes的企业级容器平台
- Nomad:HashiCorp开源的简单灵活的容器编排工具
学习交流加群风哥微信: itpux-com
2. Kubernetes 基础
2.1 Kubernetes 架构
Kubernetes采用主从架构,主要组件包括:
- Master节点:控制平面,负责集群管理
- Worker节点:运行容器的节点
- Pod:最小的部署单元,包含一个或多个容器
- Service:提供稳定的网络访问
- Deployment:管理Pod的部署和更新
2.2 集群搭建
# 初始化Master节点
$ kubeadm init –pod-network-cidr=10.244.0.0/16
# 设置kubectl配置
$ mkdir -p $HOME/.kube
$ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
$ sudo chown $(id -u):$(id -g) $HOME/.kube/config
# 安装网络插件(Calico)
$ kubectl apply -f https://docs.projectcalico.org/manifests/calico.yaml
# 加入Worker节点
$ kubeadm join 192.168.1.100:6443 –token abcdef.1234567890abcdef \
–discovery-token-ca-cert-hash sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
[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
[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”
[apiclient] All control plane components are healthy after 24.501275 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 option in kubeadm init phase upload-certs for more information
[mark-control-plane] Marking the node k8s-master 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 k8s-master 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
You should now deploy a pod network to the cluster.
Run “kubectl apply -f [podnetwork].yaml”
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
2.3 集群状态检查
$ kubectl get nodes
# 查看集群组件状态
$ kubectl get componentstatuses
# 查看所有Pod
$ kubectl get pods –all-namespaces
k8s-master Ready control-plane,master 1h v1.21.0
k8s-worker1 Ready
k8s-worker2 Ready
NAME STATUS MESSAGE ERROR
scheduler Healthy ok
controller-manager Healthy ok
etcd-0 Healthy ok
NAMESPACE NAME READY STATUS RESTARTS AGE
kube-system calico-kube-controllers-569766584b-7xq2k 1/1 Running 0 45m
kube-system calico-node-2x7v8 1/1 Running 0 45m
kube-system calico-node-5k46t 1/1 Running 0 45m
kube-system calico-node-7b8c9 1/1 Running 0 45m
kube-system coredns-558bd4d5db-6f4f6 1/1 Running 0 1h
kube-system coredns-558bd4d5db-rv52c 1/1 Running 0 1h
kube-system etcd-k8s-master 1/1 Running 0 1h
kube-system kube-apiserver-k8s-master 1/1 Running 0 1h
kube-system kube-controller-manager-k8s-master 1/1 Running 0 1h
kube-system kube-proxy-4k57t 1/1 Running 0 1h
kube-system kube-proxy-8f8c8 1/1 Running 0 30m
kube-system kube-proxy-p5z7k 1/1 Running 0 25m
kube-system kube-scheduler-k8s-master 1/1 Running 0 1h
风哥风哥提示:集群搭建完成后,应定期检查集群状态,确保所有组件正常运行。
3. 应用部署
3.1 部署示例
$ cat nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
– name: nginx
image: nginx:1.19.10
ports:
– containerPort: 80
# 应用部署
$ kubectl apply -f nginx-deployment.yaml
3.2 查看部署状态
$ kubectl get deployments
# 查看Pod
$ kubectl get pods
# 查看Pod详情
$ kubectl describe pod nginx-deployment-66b6c48dd5-7f89c
nginx-deployment 3/3 3 3 5m
NAME READY STATUS RESTARTS AGE
nginx-deployment-66b6c48dd5-7f89c 1/1 Running 0 5m
nginx-deployment-66b6c48dd5-8k47d 1/1 Running 0 5m
nginx-deployment-66b6c48dd5-p9s2t 1/1 Running 0 5m
Name: nginx-deployment-66b6c48dd5-7f89c
Namespace: default
Priority: 0
Node: k8s-worker1/192.168.1.101
Start Time: Sat, 03 Apr 2026 00:00:00 +0000
Labels: app=nginx
pod-template-hash=66b6c48dd5
Annotations:
Status: Running
IP: 10.244.1.2
IPs:
IP: 10.244.1.2
Controlled By: ReplicaSet/nginx-deployment-66b6c48dd5
Containers:
nginx:
Container ID: docker://1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
Image: nginx:1.19.10
Image ID: docker-pullable://nginx@sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
Port: 80/TCP
Host Port: 0/TCP
State: Running
Started: Sat, 03 Apr 2026 00:00:05 +0000
Ready: True
Restart Count: 0
Environment:
Mounts:
/var/run/secrets/kubernetes.io/serviceaccount from default-token-xyz (ro)
Conditions:
Type Status
Initialized True
Ready True
ContainersReady True
PodScheduled True
Volumes:
default-token-xyz:
Type: Secret (a volume populated by a Secret)
SecretName: default-token-xyz
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 5m default-scheduler Successfully assigned default/nginx-deployment-66b6c48dd5-7f89c to k8s-worker1
Normal Pulling 5m kubelet Pulling image “nginx:1.19.10”
Normal Pulled 5m kubelet Successfully pulled image “nginx:1.19.10”
Normal Created 5m kubelet Created container nginx
Normal Started 5m kubelet Started container nginx
更多学习教程www.fgedu.net.cn
4. 服务管理
4.1 创建Service
$ cat nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
– port: 80
targetPort: 80
type: ClusterIP
# 应用Service
$ kubectl apply -f nginx-service.yaml
4.2 查看Service
$ kubectl get services
# 查看Service详情
$ kubectl describe service nginx-service
kubernetes ClusterIP 10.96.0.1
nginx-service ClusterIP 10.96.123.45
Name: nginx-service
Namespace: default
Labels:
Annotations:
Selector: app=nginx
Type: ClusterIP
IP Family Policy: SingleStack
IP Families: IPv4
IP: 10.96.123.45
IPs: 10.96.123.45
Port:
TargetPort: 80/TCP
Endpoints: 10.244.1.2:80,10.244.2.2:80,10.244.2.3:80
Session Affinity: None
Events:
4.3 访问Service
$ kubectl run curl –image=curlimages/curl –rm -i –tty — curl nginx-service
Dload Upload Total Spent Left Speed
100 612 100 612 0 0 103k 0 –:–:– –:–:– –:–:– 103k
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.
pod “curl” deleted
author:www.itpux.com
5. 网络管理
5.1 网络插件
Kubernetes支持多种网络插件,包括:
- Calico:基于BGP的网络解决方案
- Flannel:简单的网络解决方案
- Cilium:基于eBPF的网络解决方案
- Weave Net:简单的网络解决方案
5.2 网络策略
$ cat nginx-network-policy.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: nginx-network-policy
spec:
podSelector:
matchLabels:
app: nginx
ingress:
– from:
– podSelector:
matchLabels:
app: frontend
ports:
– protocol: TCP
port: 80
# 应用网络策略
$ kubectl apply -f nginx-network-policy.yaml
5.3 Ingress 配置
$ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v0.48.1/deploy/static/provider/cloud/deploy.yaml
# 创建Ingress资源
$ cat nginx-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-ingress
annotations:
kubernetes.io/ingress.class: “nginx”
spec:
rules:
– host: nginx.fgedu.net.cn
http:
paths:
– path: /
pathType: Prefix
backend:
service:
name: nginx-service
port:
number: 80
# 应用Ingress
$ kubectl apply -f nginx-ingress.yaml
serviceaccount/ingress-nginx created
configmap/ingress-nginx-controller created
clusterrole.rbac.authorization.k8s.io/ingress-nginx created
clusterrolebinding.rbac.authorization.k8s.io/ingress-nginx created
role.rbac.authorization.k8s.io/ingress-nginx created
rolebinding.rbac.authorization.k8s.io/ingress-nginx created
service/ingress-nginx-controller created
service/ingress-nginx-controller-admission created
deployment.apps/ingress-nginx-controller created
validatingwebhookconfiguration.admissionregistration.k8s.io/ingress-nginx-admission created
ingress.networking.k8s.io/nginx-ingress created
更多学习教程公众号风哥教程itpux_com
6. 存储管理
6.1 持久卷(PV)
$ cat pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: my-pv
spec:
capacity:
storage: 10Gi
accessModes:
– ReadWriteOnce
persistentVolumeReclaimPolicy: Retain
hostPath:
path: /data
# 应用持久卷
$ kubectl apply -f pv.yaml
6.2 持久卷声明(PVC)
$ cat pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
– ReadWriteOnce
resources:
requests:
storage: 5Gi
# 应用持久卷声明
$ kubectl apply -f pvc.yaml
6.3 在Pod中使用存储
$ cat nginx-pvc.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-with-pvc
spec:
containers:
– name: nginx
image: nginx:1.19.10
ports:
– containerPort: 80
volumeMounts:
– name: nginx-storage
mountPath: /usr/share/nginx/html
volumes:
– name: nginx-storage
persistentVolumeClaim:
claimName: my-pvc
# 应用Pod
$ kubectl apply -f nginx-pvc.yaml
风哥风哥提示:在生产环境中,应使用云提供商的持久化存储服务,如AWS EBS、Azure Disk或Google Persistent Disk,而不是hostPath。
7. 自动扩缩容
7.1 水平 Pod 自动扩缩容(HPA)
$ kubectl autoscale deployment nginx-deployment –cpu-percent=70 –min=3 –max=10
# 查看HPA
$ kubectl get hpa
# 查看HPA详情
$ kubectl describe hpa nginx-deployment
NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS AGE
nginx-deployment Deployment/nginx-deployment 0%/70% 3 10 3 1m
Name: nginx-deployment
Namespace: default
Reference: Deployment/nginx-deployment
Metrics: ( current / target )
resource cpu on pods (as a percentage of request): 0% (0m) / 70%
Min replicas: 3
Max replicas: 10
Deployment pods: 3 current / 3 desired
Conditions:
Type Status Reason Message
—- —— —— ——-
AbleToScale True ReadyForNewScale recommended size matches current size
ScalingActive True ValidMetricFound the HPA was able to successfully calculate a replica count from cpu resource utilization (percentage of request)
ScalingLimited False DesiredWithinRange the desired count is within the acceptable range
Events:
Type Reason Age From Message
—- —— —- —- ——-
Normal SuccessfulRescale 1m horizontal-pod-autoscaler New size: 3; reason: All metrics below target
7.2 基于自定义指标的扩缩容
除了CPU和内存,Kubernetes还支持基于自定义指标的自动扩缩容,如请求数、队列长度等。
8. 滚动更新
8.1 滚动更新配置
$ kubectl set image deployment nginx-deployment nginx=nginx:1.20.0
# 查看滚动更新状态
$ kubectl rollout status deployment nginx-deployment
# 查看滚动更新历史
$ kubectl rollout history deployment nginx-deployment
Waiting for deployment “nginx-deployment” rollout to finish: 1 out of 3 new replicas have been updated…
Waiting for deployment “nginx-deployment” rollout to finish: 2 out of 3 new replicas have been updated…
Waiting for deployment “nginx-deployment” rollout to finish: 2 out of 3 new replicas have been updated…
Waiting for deployment “nginx-deployment” rollout to finish: 3 out of 3 new replicas have been updated…
deployment “nginx-deployment” successfully rolled out
deployment.apps/nginx-deployment
REVISION CHANGE-CAUSE
1 kubectl apply –filename=nginx-deployment.yaml
2 kubectl set image deployment nginx-deployment nginx=nginx:1.20.0
8.2 回滚更新
$ kubectl rollout undo deployment nginx-deployment
# 回滚到指定版本
$ kubectl rollout undo deployment nginx-deployment –to-revision=1
deployment.apps/nginx-deployment rolled back
学习交流加群风哥QQ113257174
9. 安全管理
9.1 Pod 安全上下文
$ cat secure-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
containers:
– name: nginx
image: nginx:1.19.10
securityContext:
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
# 应用Pod
$ kubectl apply -f secure-pod.yaml
9.2 服务账户
$ kubectl create serviceaccount my-service-account
# 查看服务账户
$ kubectl get serviceaccounts
# 在Pod中使用服务账户
$ cat pod-with-service-account.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-with-service-account
spec:
serviceAccountName: my-service-account
containers:
– name: nginx
image: nginx:1.19.10
# 应用Pod
$ kubectl apply -f pod-with-service-account.yaml
NAME SECRETS AGE
default 1 1h
my-service-account 1 1m
pod/pod-with-service-account created
9.3 secrets管理
$ kubectl create secret generic my-secret –from-literal=username=admin –from-literal=password=secret123
# 查看Secret
$ kubectl get secrets
# 在Pod中使用Secret
$ cat pod-with-secret.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-with-secret
spec:
containers:
– name: nginx
image: nginx:1.19.10
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
NAME TYPE DATA AGE
default-token-xyz kubernetes.io/service-account-token 3 1h
my-secret Opaque 2 1m
pod/pod-with-secret created
更多学习教程www.fgedu.net.cn
10. 最佳实践
10.1 部署最佳实践
- 使用Deployment管理无状态应用
- 使用StatefulSet管理有状态应用
- 使用DaemonSet部署每个节点都需要的服务
- 使用CronJob运行定时任务
10.2 资源管理最佳实践
- 为每个容器设置资源请求和限制
- 使用命名空间隔离不同的应用
- 使用标签和注解组织资源
- 定期清理未使用的资源
10.3 安全最佳实践
- 使用最小权限原则
- 定期更新容器镜像
- 使用Secret管理敏感信息
- 启用Pod安全策略
- 定期审计集群配置
10.4 监控和日志最佳实践
- 使用Prometheus监控集群
- 使用ELK Stack收集和分析日志
- 设置合理的告警阈值
- 定期备份集群配置
- 使用多Master节点确保高可用性
- 实施备份策略,定期备份etcd数据
- 使用网络策略限制Pod间通信
- 启用RBAC,控制用户和服务账户的权限
- 定期更新Kubernetes版本
- 使用Helm管理应用部署
- 实施CI/CD流水线,自动化部署流程
author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
