七、安全加固最佳实践
7.1 镜像安全
# 1. 使用官方slim版本基础镜像
FROM python:3.9-slim
# 2. 创建非root用户
RUN groupadd -r appuser && useradd -r -g appuser appuser
# 3. 设置文件权限
COPY --chown=appuser:appuser . .
# 4. 切换到非root用户
USER appuser
# 5. 只读文件系统(运行时配置)
# docker run --read-only ...
7.2 运行时安全
# Pod安全上下文
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 3000
fsGroup: 2000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:v1
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop:
- ALL
add:
- NET_BIND_SERVICE
7.3 网络策略
# NetworkPolicy限制Pod间通信
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-network-policy
spec:
podSelector:
matchLabels:
app: api
policyTypes:
- Ingress
- Egress
ingress:
- from:
- namespaceSelector:
matchLabels:
name: frontend
- podSelector:
matchLabels:
app: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- namespaceSelector:
matchLabels:
name: database
ports:
- protocol: TCP
port: 5432
7.4 RBAC权限控制
# Role(命名空间级别)
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
namespace: default
name: pod-reader
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
---
# RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
namespace: default
name: read-pods
subjects:
- kind: ServiceAccount
name: my-sa
namespace: default
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
八、Helm应用包管理
Helm是K8s的包管理工具,通过Chart模板化部署应用。
# 安装Helm
curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash
# 添加仓库
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# 安装MySQL Chart
helm install my-mysql bitnami/mysql \
--set auth.rootPassword=secretpassword \
--set primary.persistence.size=10Gi
# 创建自定义Chart
helm create myapp
# Chart目录结构:
myapp/
├── Chart.yaml # Chart元数据
├── values.yaml # 默认配置值
├── charts/ # 依赖的子Chart
├── templates/ # K8s YAML模板
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── _helpers.tpl # 模板辅助函数
│ └── NOTES.txt # 安装后提示信息
└── .helmignore # 忽略文件
# values.yaml示例
replicaCount: 3
image:
repository: myapp
tag: latest
pullPolicy: IfNotPresent
service:
type: ClusterIP
port: 80
targetPort: 8080
resources:
limits:
cpu: 500m
memory: 512Mi
requests:
cpu: 250m
memory: 256Mi
ingress:
enabled: true
host: myapp.example.com
config:
logLevel: INFO
dbHost: mysql-service
# templates/deployment.yaml模板
apiVersion: apps/v1
kind: Deployment
metadata:
name: {
{ include "myapp.fullname" . }}
labels:
{
{- include "myapp.labels" . | nindent 4 }}
spec:
replicas: {
{ .Values.replicaCount }}
selector:
matchLabels:
{
{- include "myapp.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{
{- include "myapp.selectorLabels" . | nindent 8 }}
spec:
containers:
- name: {
{ .Chart.Name }}
image: "{
{ .Values.image.repository }}:{
{ .Values.image.tag }}"
imagePullPolicy: {
{ .Values.image.pullPolicy }}
ports:
- containerPort: {
{ .Values.service.targetPort }}
env:
- name: LOG_LEVEL
value: {
{ .Values.config.logLevel | quote }}
resources:
{
{- toYaml .Values.resources | nindent 10 }}
九、GitOps与持续交付
GitOps是云原生时代的持续交付模式,核心思想是使用Git作为声明式基础设施和应用的单一事实来源。
9.1 ArgoCD架构
# ArgoCD Application定义
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp
namespace: argocd
spec:
project: default
# Git仓库源
source:
repoURL: https://github.com/company/myapp-k8s-config
targetRevision: main
path: overlays/production
helm:
valueFiles:
- values.yaml
# 目标集群
destination:
server: https://kubernetes.default.svc
namespace: production
# 同步策略
syncPolicy:
automated:
prune: true # 自动删除多余资源
selfHeal: true # 自动修复漂移
syncOptions:
- CreateNamespace=true
# 保留历史版本
retry:
limit: 5
backoff:
duration: 5s
factor: 2
maxDuration: 3m
9.2 CI/CD流水线
# GitLab CI示例
stages:
- test
- build
- scan
- deploy
variables:
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
# 单元测试
test:
stage: test
script:
- go test -v ./...
# 镜像构建
build:
stage: build
script:
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
# 安全扫描
security-scan:
stage: scan
script:
- trivy image --severity HIGH,CRITICAL $IMAGE_TAG
# GitOps部署(更新Git仓库)
deploy-dev:
stage: deploy
script:
- git clone https://gitlab.com/company/k8s-config.git
- cd k8s-config/overlays/dev
- kustomize edit set image myapp=$IMAGE_TAG
- git commit -am "Update image to $CI_COMMIT_SHA"
- git push
only:
- main
十、未来演进趋势
10.1 Service Mesh(服务网格)
Service Mesh将服务通信能力下沉到基础设施层,实现流量管理、安全、可观测性的平台化。
# Istio VirtualService示例
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: myapp
spec:
hosts:
- myapp
http:
# 金丝雀发布:90%流量到v1,10%到v2
- route:
- destination:
host: myapp
subset: v1
weight: 90
- destination:
host: myapp
subset: v2
weight: 10
# 基于Header的路由
match:
- headers:
version:
exact: v2
route:
- destination:
host: myapp
subset: v2
weight: 100
10.2 eBPF技术
eBPF(扩展伯克利包过滤器)正在改变云原生可观测性、网络和安全的面貌。
# Cilium(基于eBPF的CNI插件)
# 提供高性能网络和可观测性
cilium status
cilium monitor
cilium endpoint list
10.3 Serverless容器
# Knative Service定义(Serverless工作负载)
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: myapp
spec:
template:
spec:
containers:
- image: myapp:latest
resources:
requests:
cpu: 100m
memory: 128Mi
# 缩容到零
scale-to-zero: true
traffic:
- percent: 100
latestRevision: true
附:云原生最佳实践清单
设计原则:
- 容器镜像: 多阶段构建、非root用户、单一进程
- Pod配置: 设置requests/limits、配置探针、优雅停机
- 应用设计: 无状态、健康检查、配置外置
安全加固:
- 镜像安全: 漏洞扫描、签名验证、最小基础镜像
- 运行时: 非root运行、只读文件系统、禁用特权容器
- 网络: NetworkPolicy限制、RBAC最小权限
可观测性:
- 统一日志输出到stdout/stderr
- 暴露/metrics端点
- 集成分布式追踪Header
运维实践:
- 声明式管理(避免kubectl edit)
- Git作为单一事实来源
- 蓝绿/金丝雀发布