一、不可变基础设施核心概念

1.1 从可变到不可变的演进

text

复制

下载

传统可变基础设施:
┌─────────────────────────────────────┐
│        服务器 (pet)                  │
├─────────────────────────────────────┤
│ • SSH登录修改配置                   │
│ • 原地升级应用                      │
│ • 手动打补丁修复                    │
│ • 配置漂移难以追踪                  │
│ • 雪花服务器问题                    │
└─────────────────────────────────────┘

不可变基础设施:
┌─────────────────────────────────────┐
│        镜像 (cattle)                │
├─────────────────────────────────────┤
│ • 禁止SSH登录                        │
│ • 版本化镜像构建                    │
│ • 全量替换而非修改                  │
│ • 完全可重复部署                    │
│ • 一致的运行环境                    │
└─────────────────────────────────────┘

二、基础设施即代码实现

2.1 Terraform基础设施定义

hcl

复制

下载

# main.tf - 核心基础设施定义
terraform {
  required_version = ">= 1.0.0"
  
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 4.0"
    }
    kubernetes = {
      source  = "hashicorp/kubernetes"
      version = "~> 2.0"
    }
  }
  
  backend "s3" {
    bucket         = "terraform-state-prod"
    key            = "global/s3/terraform.tfstate"
    region         = "us-east-1"
    encrypt        = true
    dynamodb_table = "terraform-locks"
  }
}

# VPC网络架构
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "3.0.0"
  
  name = "immutable-vpc"
  cidr = "10.0.0.0/16"
  
  azs             = ["us-east-1a", "us-east-1b", "us-east-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]
  
  enable_nat_gateway     = true
  single_nat_gateway     = false
  one_nat_gateway_per_az = true
  
  enable_dns_hostnames = true
  enable_dns_support   = true
  
  tags = {
    Terraform   = "true"
    Environment = "production"
    Immutable   = "true"
  }
}

# EKS集群定义
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "18.0.0"
  
  cluster_name    = "immutable-cluster"
  cluster_version = "1.24"
  
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets
  
  # 节点组配置
  eks_managed_node_groups = {
    default = {
      desired_size = 3
      min_size     = 1
      max_size     = 10
      
      instance_types = ["t3.medium"]
      capacity_type  = "SPOT"
      
      # 不可变启动模板
      create_launch_template = true
      launch_template_name   = "immutable-launch-template"
      
      # 节点标签
      labels = {
        Environment = "production"
        Immutable   = "true"
        Workload    = "general"
      }
      
      # 污点管理
      taints = [
        {
          key    = "dedicated"
          value  = "app"
          effect = "NO_SCHEDULE"
        }
      ]
      
      # 更新策略 - 不可变更新
      update_config = {
        max_unavailable_percentage = 33
      }
      
      # 禁止SSH访问
      remote_access = {
        ec2_ssh_key = null  # 无SSH密钥
        source_security_group_ids = []
      }
    }
  }
  
  # 集群安全配置
  cluster_security_group_additional_rules = {
    ingress_https = {
      description = "HTTPS from anywhere"
      protocol    = "tcp"
      from_port   = 443
      to_port     = 443
      type        = "ingress"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
  
  # 不可变集群配置
  cluster_addons = {
    coredns = {
      resolve_conflicts = "OVERWRITE"
    }
    kube-proxy = {}
    vpc-cni = {
      resolve_conflicts = "OVERWRITE"
    }
  }
}

2.2 Packer不可变镜像构建

hcl

复制

下载

# immutable-ami.pkr.hcl
variable "aws_region" {
  type    = string
  default = "us-east-1"
}

variable "source_ami" {
  type    = string
  default = "ami-0c55b159cbfafe1f0" # Amazon Linux 2
}

variable "ssh_username" {
  type    = string
  default = "ec2-user"
}

source "amazon-ebs" "immutable-base" {
  region          = var.aws_region
  source_ami      = var.source_ami
  instance_type   = "t3.micro"
  ssh_username    = var.ssh_username
  
  # 加密AMI
  encrypt_boot = true
  kms_key_id   = "alias/aws/ebs"
  
  # 标签管理
  ami_name        = "immutable-base-{{timestamp}}"
  ami_description = "Immutable base image with hardened configuration"
  
  tags = {
    Name        = "immutable-base"
    Environment = "production"
    Version     = "{{timestamp}}"
    ManagedBy   = "packer"
  }
}

build {
  sources = ["source.amazon-ebs.immutable-base"]
  
  # 1. 基础系统配置
  provisioner "shell" {
    inline = [
      # 禁用SSH密码登录
      "sudo sed -i 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config",
      "sudo sed -i 's/^#PermitRootLogin prohibit-password/PermitRootLogin no/' /etc/ssh/sshd_config",
      
      # 配置日志聚合
      "sudo yum install -y awslogs",
      "sudo systemctl enable awslogsd",
      
      # 安装基本监控工具
      "sudo yum install -y amazon-cloudwatch-agent",
      
      # 清理Yum缓存
      "sudo yum clean all",
      "sudo rm -rf /var/cache/yum"
    ]
  }
  
  # 2. 安全加固
  provisioner "shell" {
    script = "scripts/security-hardening.sh"
  }
  
  # 3. 运行时环境安装
  provisioner "shell" {
    inline = [
      # 安装Docker
      "sudo amazon-linux-extras install docker -y",
      "sudo systemctl enable docker",
      
      # 安装Kubernetes工具
      "curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.24.0/bin/linux/amd64/kubectl",
      "sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl",
      
      # 安装Helm
      "curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash"
    ]
  }
  
  # 4. 应用运行时
  provisioner "file" {
    source      = "runtime/"
    destination = "/opt/app/"
  }
  
  # 5. 配置系统服务
  provisioner "file" {
    source      = "systemd/"
    destination = "/etc/systemd/system/"
  }
  
  # 6. 最终清理
  provisioner "shell" {
    inline = [
      # 清理历史命令
      "cat /dev/null > ~/.bash_history",
      "history -c",
      
      # 清理临时文件
      "sudo rm -rf /tmp/*",
      
      # 标记为不可变
      "sudo touch /etc/immutable-infrastructure",
      "echo 'This is an immutable infrastructure image. Do not modify.' | sudo tee /etc/motd"
    ]
  }
  
  # 7. 验证镜像
  provisioner "shell" {
    inline = [
      # 验证关键服务状态
      "sudo systemctl is-enabled docker",
      "sudo systemctl is-enabled awslogsd",
      
      # 验证工具安装
      "docker --version",
      "kubectl version --client",
      "helm version"
    ]
  }
  
  # 后处理 - 创建启动模板
  post-processor "manifest" {
    output = "manifest.json"
    strip_path = true
  }
}

bash

复制

下载

#!/bin/bash
# scripts/security-hardening.sh

# 安全加固脚本
set -e

echo "开始安全加固..."

# 1. 内核参数调优
cat << EOF | sudo tee /etc/sysctl.d/99-immutable.conf
# 网络安全
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0

# 内存保护
vm.overcommit_memory = 1
vm.swappiness = 1
vm.dirty_ratio = 10
vm.dirty_background_ratio = 5

# 文件系统保护
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
fs.suid_dumpable = 0

# 进程限制
kernel.core_uses_pid = 1
kernel.sysrq = 0
kernel.randomize_va_space = 2
EOF

sudo sysctl -p /etc/sysctl.d/99-immutable.conf

# 2. 防火墙配置
sudo systemctl enable firewalld
sudo systemctl start firewalld

# 只开放必要端口
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
sudo firewall-cmd --permanent --add-port=6443/tcp  # Kubernetes API
sudo firewall-cmd --reload

# 3. SSH加固
sudo sed -i 's/#AllowUsers/AllowUsers/' /etc/ssh/sshd_config
sudo sed -i 's/#DenyUsers/DenyUsers root/' /etc/ssh/sshd_config
sudo sed -i 's/#ClientAliveInterval/ClientAliveInterval 300/' /etc/ssh/sshd_config
sudo sed -i 's/#ClientAliveCountMax/ClientAliveCountMax 2/' /etc/ssh/sshd_config

# 4. 文件权限加固
sudo chmod 750 /usr/bin/
sudo chmod 750 /usr/sbin/
sudo chmod 644 /etc/passwd
sudo chmod 600 /etc/shadow

# 5. 禁用不需要的服务
sudo systemctl disable postfix
sudo systemctl disable rpcbind
sudo systemctl disable nfs

# 6. 安装安全工具
sudo yum install -y aide  # 文件完整性检查
sudo aide --init
sudo mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz

sudo yum install -y rkhunter  #  rootkit检查
sudo rkhunter --update
sudo rkhunter --propupd

echo "安全加固完成"

 篇幅限制下面就只能给大家展示小册部分内容了。整理了一份核心面试笔记包括了:Java面试、Spring、JVM、MyBatis、Redis、MySQL、并发编程、微服务、Linux、Springboot、SpringCloud、MQ、Kafc

需要全套面试笔记及答案
【点击此处即可/免费获取】

三、容器镜像不可变构建

3.1 Dockerfile多阶段构建

dockerfile

复制

下载

# 阶段1: 构建环境
FROM golang:1.19-alpine AS builder

# 安装依赖
RUN apk add --no-cache git make gcc musl-dev

# 设置工作目录
WORKDIR /app

# 复制依赖文件
COPY go.mod go.sum ./
RUN go mod download

# 复制源代码
COPY . .

# 构建应用
RUN CGO_ENABLED=0 GOOS=linux go build \
    -a -installsuffix cgo \
    -ldflags="-w -s" \
    -o /app/main ./cmd/server

# 阶段2: 安全扫描
FROM aquasec/trivy:0.35 AS security-scanner
COPY --from=builder /app/main /app/main
RUN trivy filesystem --severity HIGH,CRITICAL --exit-code 1 /app/main

# 阶段3: 运行时环境
FROM gcr.io/distroless/base:nonroot AS runtime

# 安装CA证书
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# 复制应用
COPY --from=builder --chown=nonroot:nonroot /app/main /app/main

# 复制非root用户信息
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/group /etc/group

# 切换到非root用户
USER nonroot:nonroot

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD ["/app/main", "health"]

# 暴露端口
EXPOSE 8080

# 设置不可变标签
LABEL maintainer="devops@company.com"
LABEL version="1.0.0"
LABEL immutable="true"
LABEL security.scan="passed"

# 入口点
ENTRYPOINT ["/app/main"]

3.2 Kaniko无特权构建

yaml

复制

下载

# kaniko-build.yaml
apiVersion: v1
kind: Pod
metadata:
  name: kaniko-build
  namespace: build
spec:
  restartPolicy: Never
  serviceAccountName: kaniko-sa
  
  containers:
  - name: kaniko
    image: gcr.io/kaniko-project/executor:v1.9.0
    args:
    - "--dockerfile=Dockerfile"
    - "--context=git://github.com/company/app.git#refs/heads/main"
    - "--destination=registry.company.com/app:v1.0.0-$(git rev-parse --short HEAD)"
    - "--cache=true"
    - "--cache-repo=registry.company.com/cache"
    - "--cache-ttl=168h" # 7天缓存
    - "--skip-tls-verify=false"
    - "--verbosity=info"
    - "--label=build-timestamp=$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
    - "--label=git-commit=$(git rev-parse HEAD)"
    - "--label=vcs-url=github.com/company/app"
    
    # 资源限制
    resources:
      requests:
        memory: "2Gi"
        cpu: "1"
      limits:
        memory: "4Gi"
        cpu: "2"
    
    # 安全上下文
    securityContext:
      runAsUser: 1000
      runAsGroup: 1000
      allowPrivilegeEscalation: false
      privileged: false
      readOnlyRootFilesystem: true
      capabilities:
        drop: ["ALL"]
    
    # 卷挂载
    volumeMounts:
    - name: kaniko-secret
      mountPath: /kaniko/.docker
      readOnly: true
    - name: docker-config
      mountPath: /kaniko/.docker/config.json
      subPath: config.json
  
  volumes:
  - name: kaniko-secret
    secret:
      secretName: registry-credentials
      items:
      - key: .dockerconfigjson
        path: config.json
  - name: docker-config
    configMap:
      name: docker-config

3.3 Cosign镜像签名

yaml

复制

下载

# cosign-sign.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cosign-sign
  namespace: security
spec:
  schedule: "*/5 * * * *" # 每5分钟执行
  concurrencyPolicy: Forbid
  
  jobTemplate:
    spec:
      template:
        spec:
          serviceAccountName: cosign-sa
          
          containers:
          - name: cosign
            image: gcr.io/projectsigstore/cosign:v1.13.0
            
            args:
            - "sign"
            - "--key"
            - "k8s://security/cosign-keys/private"
            - "--upload=true"
            - "--tlog-upload=true"
            - "--rekor-url=https://rekor.sigstore.dev"
            - "--output-signature"
            - "/tmp/signature.sig"
            - "--output-certificate"
            - "/tmp/certificate.crt"
            - "registry.company.com/app:$(IMAGE_TAG)"
            
            env:
            - name: IMAGE_TAG
              valueFrom:
                configMapKeyRef:
                  name: build-info
                  key: latest-image-tag
            
            # 安全上下文
            securityContext:
              runAsNonRoot: true
              runAsUser: 1000
              allowPrivilegeEscalation: false
              readOnlyRootFilesystem: true
              capabilities:
                drop: ["ALL"]
            
            volumeMounts:
            - name: cosign-keys
              mountPath: /var/run/cosign
              readOnly: true
            - name: tmp
              mountPath: /tmp
            
          restartPolicy: OnFailure
          
          volumes:
          - name: cosign-keys
            secret:
              secretName: cosign-private-key
          - name: tmp
            emptyDir: {}

四、Kubernetes不可变部署

4.1 Deployment不可变配置

yaml

复制

下载

# immutable-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: immutable-app
  namespace: production
  labels:
    app: immutable-app
    immutable: "true"
  annotations:
    deployment.kubernetes.io/revision: "1"
    kubernetes.io/change-cause: "Initial immutable deployment"
spec:
  # 不可变部署策略
  strategy:
    type: Recreate  # 先停止所有Pod再创建新的
    rollingUpdate: null
  
  replicas: 3
  revisionHistoryLimit: 3  # 保留3个历史版本
  
  selector:
    matchLabels:
      app: immutable-app
      version: v1.0.0
  
  template:
    metadata:
      labels:
        app: immutable-app
        version: v1.0.0
        immutable: "true"
      annotations:
        # 不可变注解
        sidecar.istio.io/inject: "false"
        checksum/config: "sha256:abc123..."
    
    spec:
      # 安全上下文
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
        fsGroup: 1000
        seccompProfile:
          type: RuntimeDefault
        
        # Pod安全标准
        sysctls:
        - name: net.ipv4.tcp_keepalive_time
          value: "300"
        
        # 禁止特权升级
        allowPrivilegeEscalation: false
        
        # 能力限制
        capabilities:
          drop:
          - ALL
          add:
          - NET_BIND_SERVICE  # 仅允许绑定端口
      
      # 服务账户
      serviceAccountName: immutable-app-sa
      automountServiceAccountToken: false
      
      # 节点选择器
      nodeSelector:
        immutable: "true"
        workload: "app"
      
      # 亲和性规则
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
          - weight: 100
            podAffinityTerm:
              labelSelector:
                matchExpressions:
                - key: app
                  operator: In
                  values:
                  - immutable-app
              topologyKey: kubernetes.io/hostname
      
      # 拓扑约束
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: immutable-app
      
      # 初始化容器(不可变配置)
      initContainers:
      - name: init-config
        image: busybox:1.35
        command: ['sh', '-c', 'echo "Initializing immutable app..."']
        
        # 资源限制
        resources:
          requests:
            memory: "32Mi"
            cpu: "10m"
          limits:
            memory: "64Mi"
            cpu: "50m"
        
        # 安全上下文
        securityContext:
          runAsNonRoot: true
          runAsUser: 1000
          readOnlyRootFilesystem: true
          allowPrivilegeEscalation: false
        
        # 卷挂载
        volumeMounts:
        - name: config-volume
          mountPath: /etc/app/config
          readOnly: true
      
      # 主容器
      containers:
      - name: app
        image: registry.company.com/app:v1.0.0@sha256:abc123...
        
        # 镜像拉取策略
        imagePullPolicy: Always
        
        # 资源请求和限制
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        
        # 环境变量(不可变)
        env:
        - name: NODE_ENV
          value: "production"
        - name: APP_VERSION
          valueFrom:
            fieldRef:
              fieldPath: metadata.labels['version']
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        
        # 配置从Secret读取
        envFrom:
        - secretRef:
            name: app-secrets
        
        # 端口定义
        ports:
        - name: http
          containerPort: 8080
          protocol: TCP
        
        # 健康检查
        livenessProbe:
          httpGet:
            path: /healthz
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
          failureThreshold: 3
        
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 3
          failureThreshold: 1
        
        # 安全上下文
        securityContext:
          readOnlyRootFilesystem: true
          privileged: false
          allowPrivilegeEscalation: false
          capabilities:
            drop:
            - ALL
        
        # 卷挂载(只读)
        volumeMounts:
        - name: config-volume
          mountPath: /etc/app/config
          readOnly: true
        - name: tmp-volume
          mountPath: /tmp
        
        # 生命周期钩子
        lifecycle:
          postStart:
            exec:
              command: ["/bin/sh", "-c", "echo 'Container started' > /tmp/startup.log"]
          preStop:
            exec:
              command: ["/bin/sh", "-c", "sleep 10; echo 'Gracefully shutting down'"]
      
      # 卷定义
      volumes:
      - name: config-volume
        configMap:
          name: app-config
          defaultMode: 0440  # 只读
      
      - name: tmp-volume
        emptyDir:
          medium: Memory
          sizeLimit: 128Mi
      
      # 优先级
      priorityClassName: high-priority
      
      # 终止宽限期
      terminationGracePeriodSeconds: 30
      
      # 禁止Service Account自动挂载
      automountServiceAccountToken: false
      
      # DNS配置
      dnsConfig:
        options:
        - name: ndots
          value: "2"
        - name: single-request-reopen

4.2 不可变配置管理

yaml

复制

下载

# immutable-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
  namespace: production
  annotations:
    config.immutable: "true"  # Kubernetes 1.19+ 原生支持
    checksum/data: "sha256:def456..."
    last-updated: "2024-01-15T10:30:00Z"
data:
  # 应用配置
  application.yaml: |
    server:
      port: 8080
      shutdown: graceful
      
    logging:
      level: INFO
      format: json
      
    metrics:
      enabled: true
      port: 9090
  
  # 功能开关
  feature-flags.yaml: |
    features:
      newDashboard: false
      experimentalAPI: true
      
    limits:
      maxRequestsPerMinute: 1000
      maxConcurrentUsers: 100
  
  # 不可变标记
  immutable.flag: |
    # 此配置映射是不可变的
    # 任何修改都需要创建新版本
    # 当前版本: v1.0.0
    # 哈希: sha256:def456...

yaml

复制

下载

# immutable-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: app-secrets
  namespace: production
  annotations:
    secret.immutable: "true"
    sealed.by: "kubeseal"
type: Opaque
data:
  # 加密的数据库密码
  database.password: c2VjcmV0LXBhc3N3b3JkCg==
  
  # API密钥
  api.key: YXBpLWtleS1zZWNyZXQK
  
  # JWT密钥
  jwt.secret: and0LXNlY3JldC1rZXkK

4.3 不可变更新策略

yaml

复制

下载

# immutable-update.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: immutable-app-deployment
  namespace: argocd
spec:
  project: default
  
  source:
    repoURL: git@github.com:company/gitops.git
    targetRevision: HEAD
    path: apps/immutable-app/overlays/production
    
    # 不可变配置源
    directory:
      recurse: true
      exclude: |
        **/tmp/
        **/*.tmp
        **/.#*
      
    # 插件配置
    plugin:
      name: kustomize
      env:
      - name: KUSTOMIZE_BUILD_OPTIONS
        value: "--load-restrictor=LoadRestrictionsNone"
  
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  
  # 同步策略
  syncPolicy:
    automated:
      prune: true  # 删除旧资源
      selfHeal: true  # 自动修复漂移
      allowEmpty: false
    
    # 不可变同步选项
    syncOptions:
    - CreateNamespace=true
    - PruneLast=true  # 最后执行清理
    - Validate=false  # 由准入控制验证
    
    # 重试策略
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m
  
  # 健康检查
  healthChecks:
  - apiVersion: v1
    kind: Service
    name: immutable-app
    namespace: production
  - apiVersion: apps/v1
    kind: Deployment
    name: immutable-app
    namespace: production
  
  # 忽略差异(只关注特定字段)
  ignoreDifferences:
  - group: apps
    kind: Deployment
    name: immutable-app
    namespace: production
    jsonPointers:
    - /spec/replicas  # 允许HPA调整副本数
    - /metadata/annotations/deployment.kubernetes.io~1revision  # 忽略版本号

 篇幅限制下面就只能给大家展示小册部分内容了。整理了一份核心面试笔记包括了:Java面试、Spring、JVM、MyBatis、Redis、MySQL、并发编程、微服务、Linux、Springboot、SpringCloud、MQ、Kafc

需要全套面试笔记及答案
【点击此处即可/免费获取】

五、不可变网络策略

5.1 网络策略定义

yaml

复制

下载

# network-policies.yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: immutable-app-ingress
  namespace: production
spec:
  podSelector:
    matchLabels:
      app: immutable-app
  
  # 入站规则
  ingress:
  # 1. 内部服务访问
  - from:
    - namespaceSelector:
        matchLabels:
          name: monitoring
      podSelector:
        matchLabels:
          app: prometheus
    
    ports:
    - protocol: TCP
      port: 9090  # metrics端口
  
  # 2. API网关访问
  - from:
    - namespaceSelector:
        matchLabels:
          name: ingress
      podSelector:
        matchLabels:
          app: nginx-ingress
    
    ports:
    - protocol: TCP
      port: 8080  # 应用端口
  
  # 3. 内部微服务通信
  - from:
    - podSelector:
        matchLabels:
          app: api-gateway
    
    ports:
    - protocol: TCP
      port: 8080
  
  # 4. 拒绝所有其他入站
  - {}
  
  # 出站规则
  egress:
  # 1. 允许访问DNS
  - to:
    - namespaceSelector: {}
      podSelector:
        matchLabels:
          k8s-app: kube-dns
    
    ports:
    - protocol: UDP
      port: 53
    - protocol: TCP
      port: 53
  
  # 2. 允许访问数据库
  - to:
    - namespaceSelector:
        matchLabels:
          name: database
      podSelector:
        matchLabels:
          app: postgresql
    
    ports:
    - protocol: TCP
      port: 5432
  
  # 3. 允许访问外部API
  - to:
    - ipBlock:
        cidr: 203.0.113.0/24  # 外部API地址
    
    ports:
    - protocol: TCP
      port: 443
  
  # 4. 默认拒绝所有出站
  - {}
  
  # 策略类型
  policyTypes:
  - Ingress
  - Egress

5.2 服务网格策略

yaml

复制

下载

# istio-authorization-policy.yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: immutable-app-authz
  namespace: production
spec:
  selector:
    matchLabels:
      app: immutable-app
  
  # 动作:拒绝所有,除非明确允许
  action: DENY
  
  rules:
  # 允许健康检查
  - from:
    - source:
        principals: ["cluster.local/ns/monitoring/sa/prometheus"]
    
    to:
    - operation:
        paths: ["/healthz", "/ready"]
        methods: ["GET"]
  
  # 允许API网关访问
  - from:
    - source:
        principals: ["cluster.local/ns/ingress/sa/api-gateway"]
    
    to:
    - operation:
        paths: ["/api/*"]
        methods: ["GET", "POST", "PUT", "DELETE"]
  
  # 允许监控访问
  - from:
    - source:
        principals: ["cluster.local/ns/monitoring/sa/prometheus"]
    
    to:
    - operation:
        paths: ["/metrics"]
        methods: ["GET"]
  
  # 内部管理API(仅限特定服务账户)
  - from:
    - source:
        principals: ["cluster.local/ns/production/sa/immutable-app-admin"]
    
    to:
    - operation:
        paths: ["/admin/*"]
        methods: ["*"]

---
apiVersion: security.istio.io/v1beta1
kind: PeerAuthentication
metadata:
  name: immutable-app-mtls
  namespace: production
spec:
  selector:
    matchLabels:
      app: immutable-app
  
  # mTLS策略
  mtls:
    mode: STRICT  # 强制双向TLS

六、不可变安全策略

6.1 Pod安全策略

yaml

复制

下载

# pod-security-policies.yaml
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: immutable-restricted
  annotations:
    seccomp.security.alpha.kubernetes.io/allowedProfileNames: 'runtime/default'
    seccomp.security.alpha.kubernetes.io/defaultProfileName: 'runtime/default'
spec:
  # 权限控制
  privileged: false
  allowPrivilegeEscalation: false
  
  # 能力控制
  requiredDropCapabilities:
  - ALL
  allowedCapabilities: []  # 不允许任何额外能力
  
  # 卷控制
  volumes:
  - 'configMap'
  - 'secret'
  - 'emptyDir'
  - 'projected'
  - 'downwardAPI'
  - 'persistentVolumeClaim'
  
  # 主机控制
  hostNetwork: false
  hostPID: false
  hostIPC: false
  
  # 安全上下文
  runAsUser:
    rule: 'MustRunAsNonRoot'
  
  seLinux:
    rule: 'RunAsAny'
  
  supplementalGroups:
    rule: 'MustRunAs'
    ranges:
    - min: 1
      max: 65535
  
  fsGroup:
    rule: 'MustRunAs'
    ranges:
    - min: 1
      max: 65535
  
  # 只读根文件系统
  readOnlyRootFilesystem: true
  
  # 允许的proc挂载类型
  allowedProcMountTypes:
  - 'Default'

6.2 安全上下文约束

yaml

复制

下载

# security-context-constraints.yaml
apiVersion: security.openshift.io/v1
kind: SecurityContextConstraints
metadata:
  name: immutable-restricted
annotations:
  kubernetes.io/description: "Immutable restricted security context"
spec:
  # 权限
  allowPrivilegedContainer: false
  allowPrivilegeEscalation: false
  defaultAllowPrivilegeEscalation: false
  
  # 能力
  requiredDropCapabilities:
  - KILL
  - MKNOD
  - SETUID
  - SETGID
  - SYS_CHROOT
  
  allowedCapabilities: []
  
  # 卷
  volumes:
  - configMap
  - secret
  - emptyDir
  - persistentVolumeClaim
  - projected
  
  # SELinux
  seLinuxContext:
    type: MustRunAs
  
  # 用户上下文
  runAsUser:
    type: MustRunAsRange
    uidRangeMin: 1000
    uidRangeMax: 10000
  
  # 组上下文
  supplementalGroups:
    type: RunAsAny
  
  fsGroup:
    type: MustRunAs
  
  # 优先级
  priority: 10
  
  # 只读根文件系统
  readOnlyRootFilesystem: true
  
  # 允许的用户
  users: []
  
  # 允许的组
  groups:
  - system:authenticated

七、不可变监控与审计

7.1 Prometheus监控规则

yaml

复制

下载

# immutable-monitoring-rules.yaml
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: immutable-infra-rules
  namespace: monitoring
  labels:
    app: prometheus
    role: alert-rules
spec:
  groups:
  - name: immutable-infrastructure
    rules:
    
    # 1. 配置漂移检测
    - alert: ConfigDriftDetected
      expr: |
        count(
          kube_pod_container_status_restarts_total{
            namespace="production"
          } > 0
        ) by (pod) 
        > 3
      for: 5m
      labels:
        severity: critical
        immutable: "true"
      annotations:
        summary: "配置漂移检测到Pod频繁重启"
        description: "Pod {{ $labels.pod }} 在过去5分钟内重启超过3次,可能存在配置漂移"
    
    # 2. 镜像版本一致性
    - alert: ImageVersionMismatch
      expr: |
        count(
          kube_pod_container_info{
            namespace="production",
            image!~".*:v[0-9]+\.[0-9]+\.[0-9]+-[a-z0-9]+$"
          }
        ) by (deployment) > 0
      for: 1m
      labels:
        severity: warning
        immutable: "true"
      annotations:
        summary: "检测到非标准镜像版本"
        description: "Deployment {{ $labels.deployment }} 使用了非标准镜像版本"
    
    # 3. 安全上下文违规
    - alert: SecurityContextViolation
      expr: |
        kube_pod_security_context_violations{
          namespace="production"
        } > 0
      for: 2m
      labels:
        severity: high
        immutable: "true"
      annotations:
        summary: "安全上下文违规检测"
        description: "检测到违反不可变安全上下文的Pod"
    
    # 4. 资源限制违规
    - alert: ResourceLimitViolation
      expr: |
        kube_pod_container_resource_limits_violated{
          namespace="production"
        } > 0
      for: 3m
      labels:
        severity: medium
        immutable: "true"
      annotations:
        summary: "资源限制违规"
        description: "Pod超出配置的资源限制"
    
    # 5. 网络策略违规
    - alert: NetworkPolicyViolation
      expr: |
        sum(
          rate(
            kube_pod_network_policy_violations_total{
              namespace="production"
            }[5m]
          )
        ) > 10
      for: 2m
      labels:
        severity: high
        immutable: "true"
      annotations:
        summary: "网络策略违规"
        description: "检测到网络策略违规流量"

 篇幅限制下面就只能给大家展示小册部分内容了。整理了一份核心面试笔记包括了:Java面试、Spring、JVM、MyBatis、Redis、MySQL、并发编程、微服务、Linux、Springboot、SpringCloud、MQ、Kafc

需要全套面试笔记及答案
【点击此处即可/免费获取】

7.2 Falco安全审计

yaml

复制

下载

# falco-security-rules.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: falco-immutable-rules
  namespace: falco
data:
  immutable-rules.yaml: |
    - rule: Immutable Infrastructure Violation
      desc: Detect changes to immutable infrastructure
      condition: >
        container and
        (evt.type in (open,openat,openat2) and
         evt.arg.flags contains O_WRONLY and
         fd.name startswith "/etc/" or
         fd.name startswith "/usr/" or
         fd.name startswith "/bin/" or
         fd.name startswith "/sbin/")
      output: >
        Immutable filesystem modification detected
        (user=%user.name command=%proc.cmdline file=%fd.name)
      priority: CRITICAL
      tags: [immutable, filesystem]
    
    - rule: SSH Access to Immutable Container
      desc: Detect SSH access to immutable containers
      condition: >
        container and
        proc.name = "sshd" and
        evt.type = execve
      output: >
        SSH access detected in immutable container
        (user=%user.name container=%container.name image=%container.image.repository)
      priority: HIGH
      tags: [immutable, ssh, container]
    
    - rule: Privilege Escalation in Immutable Pod
      desc: Detect privilege escalation attempts
      condition: >
        container and
        evt.type = setuid and
        proc.name != "ping"
      output: >
        Privilege escalation attempt detected
        (user=%user.name command=%proc.cmdline container=%container.name)
      priority: CRITICAL
      tags: [immutable, privilege_escalation]
    
    - rule: Unauthorized Volume Mount
      desc: Detect unauthorized volume mounts
      condition: >
        container and
        evt.type = mount and
        not (fs.target in ("/proc", "/sys", "/dev", "/run", "/tmp"))
      output: >
        Unauthorized volume mount detected
        (source=%evt.arg.src target=%evt.arg.target container=%container.name)
      priority: WARNING
      tags: [immutable, volume]
    
    - rule: Container Breakout Attempt
      desc: Detect container breakout attempts
      condition: >
        container and
        (evt.type = pivot_root or
         evt.type = chroot)
      output: >
        Container breakout attempt detected
        (user=%user.name command=%proc.cmdline container=%container.name)
      priority: CRITICAL
      tags: [immutable, container_breakout]

八、GitOps不可变工作流

8.1 ArgoCD不可变同步

yaml

复制

下载

# argocd-immutable-app.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: immutable-app
  namespace: argocd
  finalizers:
  - resources-finalizer.argocd.argoproj.io
spec:
  project: immutable
  
  source:
    repoURL: git@github.com:company/immutable-infra.git
    targetRevision: HEAD
    path: apps/immutable-app
    
    # 不可变源配置
    directory:
      recurse: true
      exclude: |
        **/*.md
        **/test/
        **/*_test.yaml
      
    # 插件配置
    plugin:
      name: kustomize
      env:
      - name: KUSTOMIZE_ENABLE_ALPHA_COMMANDS
        value: "true"
  
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  
  # 不可变同步策略
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
      allowEmpty: false
    
    syncOptions:
    - CreateNamespace=false
    - PrunePropagationPolicy=foreground
    - PruneLast=true
    - RespectIgnoreDifferences=true
    - ApplyOutOfSyncOnly=true
    
    # 重试策略
    retry:
      limit: 3
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 1m
  
  # 忽略的差异
  ignoreDifferences:
  - group: apps
    kind: Deployment
    name: immutable-app
    namespace: production
    jsonPointers:
    - /spec/replicas
    - /status
  
  # 健康检查
  healthChecks:
  - apiVersion: v1
    kind: Service
    name: immutable-app
    namespace: production
  - apiVersion: apps/v1
    kind: Deployment
    name: immutable-app
    namespace: production
  - apiVersion: networking.k8s.io/v1
    kind: NetworkPolicy
    name: immutable-app-ingress
    namespace: production
  
  # 信息
  info:
  - name: description
    value: Immutable infrastructure application
  - name: immutable
    value: "true"
  - name: version
    value: v1.0.0

8.2 Flux不可变配置

yaml

复制

下载

# flux-immutable-config.yaml
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
kind: Kustomization
metadata:
  name: immutable-app
  namespace: flux-system
spec:
  # 源引用
  sourceRef:
    kind: GitRepository
    name: immutable-infra
    namespace: flux-system
  
  # 目标路径
  path: ./apps/immutable-app
  
  # 不可变配置
  prune: true
  validation: client
  wait: true
  timeout: 5m
  
  # 健康检查
  healthChecks:
  - apiVersion: apps/v1
    kind: Deployment
    name: immutable-app
    namespace: production
  - apiVersion: v1
    kind: Service
    name: immutable-app
    namespace: production
  
  # 依赖项
  dependsOn:
  - name: base-infrastructure
  
  # 修补程序
  patches:
  - patch: |
      - op: replace
        path: /spec/template/metadata/labels/version
        value: v1.0.0
    target:
      kind: Deployment
      name: immutable-app
  
  # 不可变标记
  commonMetadata:
    labels:
      immutable: "true"
      managed-by: flux
    
    annotations:
      fluxcd.io/immutable: "true"
      fluxcd.io/last-applied-revision: "main/abc123"
  
  # 服务账户
  serviceAccountName: flux-kustomize-controller
  
  # 重试
  retryInterval: 2m
  interval: 5m
  
  # 暂停
  suspend: false
  
  # 解密
  decryption:
    provider: sops
    secretRef:
      name: sops-gpg

九、不可变基础设施最佳实践

9.1 实现原则

text

复制

下载

1. 版本化一切
   • 基础设施代码版本化
   • 容器镜像版本化
   • 配置版本化

2. 不可变部署
   • 禁止SSH访问生产环境
   • 使用不可变镜像
   • 全量替换而非修改

3. 声明式配置
   • 基础设施即代码
   • GitOps工作流
   • 配置漂移检测

4. 安全默认值
   • 最小权限原则
   • 只读文件系统
   • 网络策略默认拒绝

9.2 技术栈推荐

text

复制

下载

基础设施层:
• Terraform / Pulumi - 基础设施即代码
• Packer - 不可变镜像构建
• Ansible (仅用于初始化) - 配置管理

容器层:
• Docker / Podman - 容器运行时
• Kaniko / Buildah - 无特权构建
• Cosign / Notary - 镜像签名

编排层:
• Kubernetes - 容器编排
• Kustomize / Helm - 配置管理
• ArgoCD / Flux - GitOps

安全层:
• Pod Security Policies
• Network Policies
• Istio / Linkerd - 服务网格
• Falco - 运行时安全

监控层:
• Prometheus - 监控
• Grafana - 可视化
• ELK Stack - 日志
• Jaeger - 分布式追踪

9.3 成熟度模型

text

复制

下载

级别1:基础不可变
• 容器化应用
• 基础设施代码
• 自动部署

级别2:中级不可变
• 不可变镜像
• GitOps工作流
• 安全策略

级别3:高级不可变
• 完全不可变基础设施
• 零信任安全
• 自愈系统

级别4:完全不可变
• 自动伸缩和修复
• AI驱动的运维
• 完全声明式

通过实施以上不可变基础设施方案,可以实现高度可靠、安全、可重复的云原生环境部署和管理。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐