一、DevOps技术架构
1.1 整体架构图
┌───────────────────────────────────────────────────────────────┐
│ 开发阶段 │
│ IDE → Git → GitLab/GitHub → Code Review → Merge │
└────────────────────────┬──────────────────────────────────────┘
│ (Git Push触发)
↓
┌───────────────────────────────────────────────────────────────┐
│ 持续集成CI阶段 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Jenkins Pipeline / GitLab CI / GitHub Actions │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ 1. Git Clone代码 │ │
│ │ 2. Maven/Gradle编译 │ │
│ │ 3. 单元测试 (JUnit) │ │
│ │ 4. 代码检查 (SonarQube) │ │
│ │ 5. 安全扫描 (SAST) │ │
│ │ 6. 构建Docker镜像 │ │
│ │ 7. 推送到镜像仓库 (Harbor/Docker Registry) │ │
│ └─────────────────────────────────────────────────────────┘ │
└────────────────────────┬──────────────────────────────────────┘
│ (构建成功)
↓
┌───────────────────────────────────────────────────────────────┐
│ 持续部署CD阶段 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ ArgoCD / Spinnaker / Jenkins │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ 1. 拉取Docker镜像 │ │
│ │ 2. 部署到Dev环境 (K8s) → 自动化测试 │ │
│ │ 3. 部署到Test环境 (K8s) → 集成测试 │ │
│ │ 4. 部署到Staging环境 → UAT测试 │ │
│ │ 5. 【人工审批】 │ │
│ │ 6. 灰度发布到Production环境 │ │
│ │ - 10% → 监控 → 50% → 监控 → 100% │ │
│ └─────────────────────────────────────────────────────────┘ │
└────────────────────────┬──────────────────────────────────────┘
│ (部署完成)
↓
┌───────────────────────────────────────────────────────────────┐
│ 运行与监控阶段 │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ 日志:ELK (Elasticsearch + Logstash + Kibana) │ │
│ │ 指标:Prometheus + Grafana │ │
│ │ 追踪:SkyWalking / Jaeger │ │
│ │ 告警:AlertManager → 钉钉/邮件/短信 │ │
│ │ 反馈:用户行为分析 → 产品优化 │ │
│ └─────────────────────────────────────────────────────────┘ │
└───────────────────────────────────────────────────────────────┘
1.2 技术栈分层
┌─────────────────────────────────────────────┐
│ 应用层(Application) │
│ Spring Boot, Django, Node.js, Go... │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ 容器层(Container) │
│ Docker, containerd │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ 编排层(Orchestration) │
│ Kubernetes, Docker Swarm │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ 基础设施层(Infrastructure) │
│ 阿里云ECS, AWS EC2, 物理服务器 │
└─────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────┐
│ IaC层(Infrastructure as Code) │
│ Terraform, Ansible, CloudFormation │
└─────────────────────────────────────────────┘
1.3 DevOps工具链全景图
┌─────────────────────────────────────────────────────────────┐
│ 计划层: Jira, Confluence, Trello, Notion │
├─────────────────────────────────────────────────────────────┤
│ 开发层: IntelliJ IDEA, VSCode, Git, GitHub/GitLab │
├─────────────────────────────────────────────────────────────┤
│ 构建层: Maven, Gradle, npm, webpack │
├─────────────────────────────────────────────────────────────┤
│ 测试层: JUnit, Selenium, JMeter, Postman │
├─────────────────────────────────────────────────────────────┤
│ CI/CD层: Jenkins, GitLab CI, GitHub Actions, ArgoCD │
├─────────────────────────────────────────────────────────────┤
│ 制品层: Nexus, Artifactory, Harbor │
├─────────────────────────────────────────────────────────────┤
│ 部署层: Docker, K8s, Helm │
├─────────────────────────────────────────────────────────────┤
│ 配置层: Nacos, Apollo, Consul, Vault │
├─────────────────────────────────────────────────────────────┤
│ 监控层: Prometheus, Grafana, ELK, SkyWalking │
├─────────────────────────────────────────────────────────────┤
│ 安全层: SonarQube, Trivy, Vault, RBAC │
└─────────────────────────────────────────────────────────────┘
二、版本控制系统
2.1 Git核心概念
Git的三个区域
┌──────────────┐
│ 工作区 │ git add
│ (Working Dir)│ ─────────→ ┌──────────────┐
└──────────────┘ │ 暂存区 │ git commit
│ (Staging Area)│ ─────────→ ┌──────────────┐
└──────────────┘ │ 本地仓库 │
│ (Local Repo) │
└──────┬───────┘
│ git push
↓
┌──────────────┐
│ 远程仓库 │
│ (Remote Repo)│
└──────────────┘
常用命令
bash
# 基础操作
git clone <url> # 克隆仓库
git status # 查看状态
git add . # 添加所有修改到暂存区
git commit -m "feat: add feature" # 提交
git push origin master # 推送到远程
# 分支操作
git branch # 查看分支
git branch feature-login # 创建分支
git checkout feature-login # 切换分支
git checkout -b feature-login # 创建并切换分支
git merge feature-login # 合并分支
git branch -d feature-login # 删除分支
# 查看历史
git log # 查看提交历史
git log --oneline --graph # 图形化查看
git diff # 查看差异
# 撤销操作
git reset HEAD file # 取消暂存
git checkout -- file # 丢弃工作区修改
git reset --hard HEAD^ # 回退到上个版本
# 远程操作
git remote -v # 查看远程仓库
git fetch origin # 拉取远程更新
git pull origin master # 拉取并合并
2.2 Git工作流
1. Git Flow工作流
master分支(生产环境)
↑
│ (发布)
│
develop分支(开发环境)
↑
│ (合并)
│
feature分支(功能开发)
│
├─ feature/login
├─ feature/payment
└─ feature/order
hotfix分支(紧急修复)
└─ hotfix/bug-123
release分支(发布准备)
└─ release/v1.2.0
适用场景:
- 大型项目
- 版本发布周期固定
- 需要维护多个版本
流程示例:
bash
# 1. 从develop创建功能分支
git checkout develop
git checkout -b feature/login
# 2. 开发功能
# ... coding ...
git add .
git commit -m "feat: implement login"
# 3. 合并回develop
git checkout develop
git merge feature/login
# 4. 创建发布分支
git checkout -b release/v1.0.0
# 修复小问题、更新版本号
# 5. 合并到master和develop
git checkout master
git merge release/v1.0.0
git tag v1.0.0
git checkout develop
git merge release/v1.0.0
# 6. 删除发布分支
git branch -d release/v1.0.0
2. GitHub Flow工作流
master分支(生产环境,永远可部署)
↑
│ (Pull Request合并)
│
feature分支
├─ feature/add-user
├─ feature/fix-bug
└─ feature/optimize
特点:
- 简单:只有master和feature分支
- 快速:功能完成立即合并部署
- 适合持续部署
流程示例:
bash
# 1. 从master创建功能分支
git checkout master
git pull origin master
git checkout -b feature/add-user
# 2. 开发并提交
git add .
git commit -m "feat: add user management"
git push origin feature/add-user
# 3. 创建Pull Request(在GitHub上)
# 4. Code Review
# 5. 合并到master
# 6. 自动部署到生产环境
3. Trunk-Based Development(主干开发)
master分支(主干)
│
├─ (频繁提交,至少每天一次)
│
├─ Feature Flag控制功能开关
│
└─ 直接部署
特点:
- 极简:只有一个主干分支
- 高频:每天多次提交到主干
- Feature Flag:用开关控制功能上线
适用场景:
- 成熟的CI/CD
- 强大的自动化测试
- 小团队,高度信任
代码示例:
java
// 使用Feature Flag
@RestController
public class UserController {
@Autowired
private FeatureFlagService featureFlagService;
@GetMapping("/users")
public List<User> getUsers() {
if (featureFlagService.isEnabled("new-user-api")) {
// 新版本API(还在开发中,但已经合入主干)
return userServiceV2.getUsers();
} else {
// 旧版本API(生产环境使用)
return userService.getUsers();
}
}
}
2.3 GitLab vs GitHub vs Gitee
| 特性 | GitLab | GitHub | Gitee |
|---|---|---|---|
| 部署方式 | 支持私有部署 | 仅云服务 | 云服务 + 企业版 |
| CI/CD | 内置GitLab CI | GitHub Actions | Gitee Go |
| 代码审查 | Merge Request | Pull Request | Pull Request |
| 项目管理 | Issue, Board | Projects, Issues | Issue, Board |
| 价格 | 免费 + 企业版 | 免费 + Pro/Team/Enterprise | 免费 + 企业版 |
| 访问速度(国内) | 较慢 | 慢 | 快 |
| 社区 | 大 | 最大 | 中等 |
| 适用场景 | 企业内部 | 开源项目 | 国内企业 |
推荐选型:
- 大型企业:GitLab私有部署(数据安全)
- 开源项目:GitHub(社区最大)
- 国内中小企业:Gitee(速度快,价格友好)
三、持续集成CI
3.1 Jenkins详解
Jenkins架构
┌─────────────────────────────────────────────┐
│ Jenkins Master │
│ - 任务调度 │
│ - 插件管理 │
│ - 配置管理 │
└──────────────┬──────────────────────────────┘
│ (通过SSH/JNLP连接)
↓
┌──────────────┴──────────────────────────────┐
│ Jenkins Agents(多个) │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Agent 1 │ │ Agent 2 │ │
│ │ (Linux) │ │ (Windows) │ │
│ │ 执行构建 │ │ 执行构建 │ │
│ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────┘
Pipeline as Code
Jenkinsfile示例(声明式):
groovy
pipeline {
agent {
label 'java-agent' // 指定Agent
}
// 环境变量
environment {
MAVEN_HOME = '/usr/local/maven'
DOCKER_REGISTRY = 'registry.example.com'
APP_NAME = 'my-app'
}
// 构建阶段
stages {
stage('Checkout') {
steps {
echo '1. 拉取代码'
git branch: 'master',
url: 'https://github.com/example/my-app.git',
credentialsId: 'github-credentials'
}
}
stage('Build') {
steps {
echo '2. Maven构建'
sh """
mvn clean package -DskipTests
"""
}
}
stage('Test') {
steps {
echo '3. 运行测试'
sh """
mvn test
"""
}
post {
always {
junit '**/target/surefire-reports/*.xml'
}
}
}
stage('SonarQube Analysis') {
steps {
echo '4. 代码质量分析'
withSonarQubeEnv('SonarQube Server') {
sh """
mvn sonar:sonar \
-Dsonar.projectKey=${APP_NAME} \
-Dsonar.host.url=http://sonarqube:9000
"""
}
}
}
stage('Docker Build') {
steps {
echo '5. 构建Docker镜像'
script {
def imageTag = "${env.BUILD_NUMBER}"
sh """
docker build -t ${DOCKER_REGISTRY}/${APP_NAME}:${imageTag} .
docker tag ${DOCKER_REGISTRY}/${APP_NAME}:${imageTag} \
${DOCKER_REGISTRY}/${APP_NAME}:latest
"""
}
}
}
stage('Docker Push') {
steps {
echo '6. 推送镜像'
script {
docker.withRegistry("https://${DOCKER_REGISTRY}", 'docker-credentials') {
sh """
docker push ${DOCKER_REGISTRY}/${APP_NAME}:${env.BUILD_NUMBER}
docker push ${DOCKER_REGISTRY}/${APP_NAME}:latest
"""
}
}
}
}
stage('Deploy to Dev') {
steps {
echo '7. 部署到开发环境'
sh """
kubectl set image deployment/${APP_NAME} \
${APP_NAME}=${DOCKER_REGISTRY}/${APP_NAME}:${env.BUILD_NUMBER} \
-n dev
kubectl rollout status deployment/${APP_NAME} -n dev
"""
}
}
}
post {
success {
echo '✅ 构建成功!'
dingtalk(
robot: 'jenkins-dingtalk',
type: 'MARKDOWN',
title: '构建成功',
text: [
"### 构建成功 ✅",
"**项目**: ${APP_NAME}",
"**分支**: ${env.GIT_BRANCH}",
"**构建号**: ${env.BUILD_NUMBER}",
"**持续时间**: ${currentBuild.durationString}"
]
)
}
failure {
echo '❌ 构建失败!'
dingtalk(
robot: 'jenkins-dingtalk',
type: 'MARKDOWN',
title: '构建失败',
text: [
"### 构建失败 ❌",
"**项目**: ${APP_NAME}",
"**分支**: ${env.GIT_BRANCH}",
"**构建号**: ${env.BUILD_NUMBER}",
"**查看日志**: [点击这里](${env.BUILD_URL}console)"
]
)
}
}
}
Jenkins最佳实践
1. 使用Pipeline而不是Freestyle Job
优势:
✅ 代码化,可版本管理
✅ 支持复杂逻辑
✅ 可重用
✅ 更好的可视化
2. 合理使用Shared Library
groovy
// vars/buildJava.groovy(共享库)
def call(Map config) {
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "mvn clean package"
}
}
}
}
}
// Jenkinsfile(使用共享库)
@Library('my-shared-library') _
buildJava(
appName: 'my-app',
registry: 'registry.example.com'
)
3. 凭证管理
groovy
// 使用Jenkins凭证管理
withCredentials([
usernamePassword(
credentialsId: 'docker-registry',
usernameVariable: 'DOCKER_USER',
passwordVariable: 'DOCKER_PASS'
)
]) {
sh """
echo $DOCKER_PASS | docker login -u $DOCKER_USER --password-stdin
"""
}
3.2 GitLab CI详解
GitLab CI架构
GitLab Server
↓ (触发)
GitLab Runner
↓ (执行)
Docker Executor / Shell Executor / K8s Executor
.gitlab-ci.yml示例
yaml
# 定义阶段
stages:
- build
- test
- sonar
- docker
- deploy
# 全局变量
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
DOCKER_REGISTRY: "registry.example.com"
APP_NAME: "my-app"
# 缓存配置
cache:
paths:
- .m2/repository/
- target/
# 构建阶段
build-job:
stage: build
image: maven:3.8-openjdk-11
script:
- echo "开始构建"
- mvn clean package -DskipTests
artifacts:
paths:
- target/*.jar
expire_in: 1 hour
only:
- master
- develop
# 测试阶段
test-job:
stage: test
image: maven:3.8-openjdk-11
script:
- echo "运行测试"
- mvn test
coverage: '/Total.*?([0-9]{1,3})%/'
artifacts:
when: always
reports:
junit:
- target/surefire-reports/TEST-*.xml
# SonarQube分析
sonar-job:
stage: sonar
image: maven:3.8-openjdk-11
script:
- mvn sonar:sonar
-Dsonar.projectKey=$APP_NAME
-Dsonar.host.url=$SONAR_URL
-Dsonar.login=$SONAR_TOKEN
only:
- master
# Docker构建
docker-build-job:
stage: docker
image: docker:latest
services:
- docker:dind
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $DOCKER_REGISTRY
script:
- echo "构建Docker镜像"
- docker build -t $DOCKER_REGISTRY/$APP_NAME:$CI_COMMIT_SHORT_SHA .
- docker tag $DOCKER_REGISTRY/$APP_NAME:$CI_COMMIT_SHORT_SHA
$DOCKER_REGISTRY/$APP_NAME:latest
- docker push $DOCKER_REGISTRY/$APP_NAME:$CI_COMMIT_SHORT_SHA
- docker push $DOCKER_REGISTRY/$APP_NAME:latest
only:
- master
# 部署到开发环境
deploy-dev:
stage: deploy
image: bitnami/kubectl:latest
script:
- echo "部署到开发环境"
- kubectl set image deployment/$APP_NAME
$APP_NAME=$DOCKER_REGISTRY/$APP_NAME:$CI_COMMIT_SHORT_SHA
-n dev
- kubectl rollout status deployment/$APP_NAME -n dev
environment:
name: development
url: https://dev.example.com
only:
- develop
# 部署到生产环境(需要手动触发)
deploy-prod:
stage: deploy
image: bitnami/kubectl:latest
script:
- echo "部署到生产环境"
- kubectl set image deployment/$APP_NAME
$APP_NAME=$DOCKER_REGISTRY/$APP_NAME:$CI_COMMIT_SHORT_SHA
-n prod
- kubectl rollout status deployment/$APP_NAME -n prod
environment:
name: production
url: https://www.example.com
when: manual # 手动触发
only:
- master
3.3 GitHub Actions
Workflow示例
yaml
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [ master, develop ]
pull_request:
branches: [ master ]
env:
DOCKER_REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up JDK 11
uses: actions/setup-java@v3
with:
java-version: '11'
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn clean package -DskipTests
- name: Run tests
run: mvn test
- name: Upload test results
uses: actions/upload-artifact@v3
if: always()
with:
name: test-results
path: target/surefire-reports/
- name: Code coverage
uses: codecov/codecov-action@v3
with:
file: ./target/site/jacoco/jacoco.xml
docker-build-push:
needs: build-and-test
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v2
with:
registry: ${{ env.DOCKER_REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
deploy:
needs: docker-build-push
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/master'
steps:
- name: Deploy to Kubernetes
uses: azure/k8s-deploy@v4
with:
manifests: |
k8s/deployment.yaml
k8s/service.yaml
images: |
${{ env.DOCKER_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
namespace: production
四、容器化技术
4.1 Docker核心概念
Docker架构
┌─────────────────────────────────────────┐
│ Docker Client │
│ (docker命令行工具) │
└──────────────┬──────────────────────────┘
│ (REST API)
↓
┌─────────────────────────────────────────┐
│ Docker Daemon │
│ - 镜像管理 │
│ - 容器管理 │
│ - 网络管理 │
│ - 存储管理 │
└──────────────┬──────────────────────────┘
│
↓
┌──────────────┴──────────────────────────┐
│ 容器运行时 │
│ ┌──────────┐ ┌──────────┐ │
│ │Container1│ │Container2│ │
│ └──────────┘ └──────────┘ │
└─────────────────────────────────────────┘
Dockerfile最佳实践
dockerfile
# 使用官方基础镜像
FROM openjdk:11-jre-slim
# 维护者信息
LABEL maintainer="your-email@example.com"
LABEL version="1.0"
LABEL description="My Spring Boot Application"
# 设置工作目录
WORKDIR /app
# 安装必要的工具(如果需要)
RUN apt-get update && apt-get install -y \
curl \
&& rm -rf /var/lib/apt/lists/*
# 复制jar包(利用Docker缓存)
COPY target/my-app.jar /app/app.jar
# 创建非root用户(安全实践)
RUN groupadd -r appuser && useradd -r -g appuser appuser
RUN chown -R appuser:appuser /app
USER appuser
# 暴露端口
EXPOSE 8080
# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8080/actuator/health || exit 1
# 启动命令
ENTRYPOINT ["java"]
CMD ["-Xmx512m", "-Xms256m", "-jar", "app.jar"]
Dockerfile优化技巧:
- 多阶段构建(减小镜像体积)
dockerfile
# 第一阶段:构建
FROM maven:3.8-openjdk-11 AS builder
WORKDIR /build
COPY pom.xml .
COPY ../src ./src
RUN mvn clean package -DskipTests
# 第二阶段:运行
FROM openjdk:11-jre-slim
WORKDIR /app
COPY --from=builder /build/target/my-app.jar ./app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]
-
利用.dockerignore
.dockerignore
target/
.git/
.idea/
*.log
node_modules/ -
合并RUN命令(减少层数)
dockerfile
# ❌ 不好的写法
RUN apt-get update
RUN apt-get install -y curl
RUN apt-get install -y vim
# ✅ 好的写法
RUN apt-get update && apt-get install -y \
curl \
vim \
&& rm -rf /var/lib/apt/lists/*
4.2 Docker Compose
docker-compose.yml示例(本地开发环境):
yaml
version: '3.8'
services:
# 应用服务
app:
build:
context: .
dockerfile: Dockerfile
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=dev
- MYSQL_HOST=mysql
- REDIS_HOST=redis
depends_on:
- mysql
- redis
volumes:
- ./logs:/app/logs
networks:
- app-network
restart: unless-stopped
# MySQL数据库
mysql:
image: mysql:8.0
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: root123
MYSQL_DATABASE: myapp
MYSQL_USER: appuser
MYSQL_PASSWORD: apppass
volumes:
- mysql-data:/var/lib/mysql
- ./init-scripts:/docker-entrypoint-initdb.d
networks:
- app-network
restart: unless-stopped
# Redis缓存
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis-data:/data
networks:
- app-network
restart: unless-stopped
# Nginx反向代理
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- app
networks:
- app-network
restart: unless-stopped
volumes:
mysql-data:
redis-data:
networks:
app-network:
driver: bridge
使用命令:
bash
# 启动所有服务
docker-compose up -d
# 查看日志
docker-compose logs -f app
# 停止所有服务
docker-compose down
# 停止并删除卷
docker-compose down -v
五、容器编排
5.1 Kubernetes核心概念
K8s架构
┌─────────────────────────────────────────────────────────┐
│ Control Plane (Master) │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ API Server │ │ Scheduler │ │ Controller │ │
│ └──────────────┘ └──────────────┘ │ Manager │ │
│ └──────────────┘ │
│ ┌──────────────┐ │
│ │ etcd │ │
│ └──────────────┘ │
└─────────────────────────────────────────────────────────┘
↓ (管理)
┌─────────────────────────────────────────────────────────┐
│ Worker Nodes │
│ ┌──────────────────────┐ ┌──────────────────────┐ │
│ │ Node 1 │ │ Node 2 │ │
│ │ ┌────────────────┐ │ │ ┌────────────────┐ │ │
│ │ │ Kubelet │ │ │ │ Kubelet │ │ │
│ │ ├────────────────┤ │ │ ├────────────────┤ │ │
│ │ │ Kube-proxy │ │ │ │ Kube-proxy │ │ │
│ │ ├────────────────┤ │ │ ├────────────────┤ │ │
│ │ │ Container │ │ │ │ Container │ │ │
│ │ │ Runtime │ │ │ │ Runtime │ │ │
│ │ │ (Docker) │ │ │ │ (containerd) │ │ │
│ │ └────────────────┘ │ │ └────────────────┘ │ │
│ │ ┌─────┐ ┌─────┐ │ │ ┌─────┐ ┌─────┐ │ │
│ │ │ Pod │ │ Pod │ │ │ │ Pod │ │ Pod │ │ │
│ │ └─────┘ └─────┘ │ │ └─────┘ └─────┘ │ │
│ └──────────────────────┘ └──────────────────────┘ │
└─────────────────────────────────────────────────────────┘
5.2 K8s YAML配置详解
1. Deployment(部署)
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: my-app
namespace: production
labels:
app: my-app
version: v1.0.0
spec:
# 副本数
replicas: 3
# 选择器
selector:
matchLabels:
app: my-app
# 滚动更新策略
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # 最多可以多创建1个Pod
maxUnavailable: 0 # 最多允许0个Pod不可用
# Pod模板
template:
metadata:
labels:
app: my-app
version: v1.0.0
spec:
# 容器配置
containers:
- name: my-app
image: registry.example.com/my-app:1.0.0
imagePullPolicy: Always
# 端口
ports:
- containerPort: 8080
name: http
protocol: TCP
# 环境变量
env:
- name: SPRING_PROFILES_ACTIVE
value: "prod"
- name: MYSQL_HOST
valueFrom:
configMapKeyRef:
name: app-config
key: mysql-host
- name: MYSQL_PASSWORD
valueFrom:
secretKeyRef:
name: app-secret
key: mysql-password
# 资源限制
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
# 健康检查
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 60
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 30
periodSeconds: 5
timeoutSeconds: 3
failureThreshold: 3
# 挂载卷
volumeMounts:
- name: logs
mountPath: /app/logs
- name: config
mountPath: /app/config
# 卷定义
volumes:
- name: logs
emptyDir: {}
- name: config
configMap:
name: app-config
# 镜像拉取凭证
imagePullSecrets:
- name: registry-secret
2. Service(服务)
yaml
apiVersion: v1
kind: Service
metadata:
name: my-app-service
namespace: production
spec:
type: ClusterIP # 内部服务
selector:
app: my-app
ports:
- port: 80
targetPort: 8080
protocol: TCP
name: http
sessionAffinity: ClientIP # 会话保持
3. Ingress(入口)
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: my-app-ingress
namespace: production
annotations:
kubernetes.io/ingress.class: "nginx"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/ssl-redirect: "true"
spec:
tls:
- hosts:
- www.example.com
secretName: example-tls
rules:
- host: www.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: my-app-service
port:
number: 80
4. HPA(水平自动扩缩容)
yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: my-app-hpa
namespace: production
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: my-app
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
behavior:
scaleDown:
stabilizationWindowSeconds: 300 # 稳定窗口5分钟
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 30
5.3 Helm包管理
Chart结构
my-app/
├── Chart.yaml # Chart元数据
├── values.yaml # 默认配置值
├── charts/ # 依赖的其他Charts
├── templates/ # 模板文件
│ ├── deployment.yaml
│ ├── service.yaml
│ ├── ingress.yaml
│ ├── configmap.yaml
│ ├── secret.yaml
│ ├── hpa.yaml
│ ├── _helpers.tpl # 模板辅助函数
│ └── NOTES.txt # 安装后的提示信息
└── .helmignore
values.yaml示例
yaml
# values.yaml
replicaCount: 3
image:
repository: registry.example.com/my-app
tag: "1.0.0"
pullPolicy: Always
service:
type: ClusterIP
port: 80
targetPort: 8080
ingress:
enabled: true
host: www.example.com
tls:
enabled: true
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
autoscaling:
enabled: true
minReplicas: 2
maxReplicas: 10
targetCPUUtilizationPercentage: 70
env:
- name: SPRING_PROFILES_ACTIVE
value: "prod"
configMap:
data:
application.yaml: |
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://mysql:3306/mydb
使用Helm
bash
# 安装Chart
helm install my-app ./my-app -n production
# 使用自定义值
helm install my-app ./my-app -f custom-values.yaml
# 升级
helm upgrade my-app ./my-app
# 回滚
helm rollback my-app 1
# 查看历史
helm history my-app
# 卸载
helm uninstall my-app
六、监控与日志
6.1 Prometheus + Grafana监控体系
Prometheus架构
┌──────────────────────────────────────────────────────┐
│ Prometheus Server │
│ ┌────────────────┐ ┌────────────────┐ │
│ │ Time Series │ │ Retrieval │ │
│ │ Database │ │ (Pull Metrics)│ │
│ └────────────────┘ └────────────────┘ │
└──────────────┬──────────────┬────────────────────────┘
│ │
│ (查询) │ (抓取指标)
↓ ↓
┌──────────────────┐ ┌─────────────────────────┐
│ Grafana │ │ Target Applications │
│ (可视化仪表板) │ │ - Spring Boot Actuator │
└──────────────────┘ │ - Node Exporter │
│ - MySQL Exporter │
└─────────────────────────┘
↓
┌──────────────────────────────────────┐
│ AlertManager │
│ (告警管理和路由) │
└──────────────────────────────────────┘
↓
钉钉/邮件/短信
Prometheus配置
yaml
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
# 告警规则文件
rule_files:
- "/etc/prometheus/rules/*.yml"
# AlertManager配置
alerting:
alertmanagers:
- static_configs:
- targets: ['alertmanager:9093']
# 抓取配置
scrape_configs:
# Prometheus自身
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
# Spring Boot应用
- job_name: 'spring-boot-app'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['my-app:8080']
# K8s服务发现
- job_name: 'kubernetes-pods'
kubernetes_sd_configs:
- role: pod
relabel_configs:
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
action: keep
regex: true
- source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
action: replace
target_label: __metrics_path__
regex: (.+)
- source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
action: replace
regex: ([^:]+)(?::\d+)?;(\d+)
replacement: $1:$2
target_label: __address__
告警规则
yaml
# rules/app-alerts.yml
groups:
- name: application_alerts
interval: 30s
rules:
# CPU使用率告警
- alert: HighCPUUsage
expr: rate(process_cpu_seconds_total[5m]) * 100 > 80
for: 5m
labels:
severity: warning
annotations:
summary: "CPU使用率过高"
description: "应用 {{ $labels.instance }} 的CPU使用率超过80%(当前值:{{ $value }}%)"
# 内存使用率告警
- alert: HighMemoryUsage
expr: (jvm_memory_used_bytes / jvm_memory_max_bytes) * 100 > 85
for: 5m
labels:
severity: warning
annotations:
summary: "内存使用率过高"
description: "应用 {{ $labels.instance }} 的内存使用率超过85%"
# 接口响应时间告警
- alert: SlowAPIResponse
expr: rate(http_server_requests_seconds_sum[5m]) / rate(http_server_requests_seconds_count[5m]) > 1
for: 5m
labels:
severity: warning
annotations:
summary: "接口响应慢"
description: "接口 {{ $labels.uri }} 的平均响应时间超过1秒"
# 错误率告警
- alert: HighErrorRate
expr: rate(http_server_requests_seconds_count{status=~"5.."}[5m]) / rate(http_server_requests_seconds_count[5m]) * 100 > 5
for: 5m
labels:
severity: critical
annotations:
summary: "错误率过高"
description: "应用错误率超过5%"
# 服务不可用告警
- alert: ServiceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "服务不可用"
description: "服务 {{ $labels.job }} 已经下线超过1分钟"
6.2 ELK日志系统
ELK架构
应用服务器
↓ (输出日志)
Filebeat
↓ (采集)
Logstash
↓ (过滤、解析)
Elasticsearch
↓ (存储、索引)
Kibana
↓ (可视化查询)
用户
Filebeat配置
yaml
# filebeat.yml
filebeat.inputs:
- type: log
enabled: true
paths:
- /app/logs/*.log
fields:
app: my-app
env: production
multiline.pattern: '^[0-9]{4}-[0-9]{2}-[0-9]{2}'
multiline.negate: true
multiline.match: after
output.logstash:
hosts: ["logstash:5044"]
processors:
- add_host_metadata: ~
- add_cloud_metadata: ~
Logstash配置
ruby
# logstash.conf
input {
beats {
port => 5044
}
}
filter {
# 解析JSON格式日志
if [fields][app] == "my-app" {
json {
source => "message"
}
# 提取时间戳
date {
match => [ "timestamp", "yyyy-MM-dd HH:mm:ss.SSS" ]
target => "@timestamp"
}
# 提取异常堆栈
if [exception] {
mutate {
add_field => { "has_exception" => "true" }
}
}
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "app-logs-%{+YYYY.MM.dd}"
}
}
七、配置管理
7.1 Nacos配置中心
Spring Boot集成
yaml
# bootstrap.yml
spring:
application:
name: my-app
cloud:
nacos:
config:
server-addr: nacos:8848
namespace: production
group: DEFAULT_GROUP
file-extension: yaml
shared-configs:
- dataId: common-config.yaml
group: DEFAULT_GROUP
refresh: true
java
// 动态刷新配置
@RefreshScope
@RestController
public class ConfigController {
@Value("${my.config.value}")
private String configValue;
@GetMapping("/config")
public String getConfig() {
return configValue;
}
}
7.2 Apollo配置中心
对比Nacos和Apollo:
| 特性 | Nacos | Apollo |
|---|---|---|
| 开源公司 | 阿里巴巴 | 携程 |
| 功能 | 配置中心 + 注册中心 | 配置中心 |
| 配置格式 | Properties, YAML, JSON | Properties, YAML, JSON, XML |
| 配置推送 | 长轮询 | 长轮询 + HTTP短轮询 |
| 灰度发布 | 支持 | 支持(更完善) |
| 权限管理 | 基础 | 完善 |
| 审计日志 | 基础 | 完善 |
| 学习曲线 | 简单 | 中等 |
八、工具选型指南
8.1 CI/CD工具选型
| 场景 | 推荐工具 | 理由 |
|---|---|---|
| 中小团队 | GitLab CI | 集成度高,配置简单 |
| 大型企业 | Jenkins | 插件丰富,灵活性高 |
| 开源项目 | GitHub Actions | 免费,社区强大 |
| 云原生 | ArgoCD + Tekton | K8s原生,GitOps理念 |
8.2 容器编排选型
| 场景 | 推荐 | 理由 |
|---|---|---|
| 生产环境 | Kubernetes | 事实标准,生态完善 |
| 本地开发 | Docker Compose | 轻量级,配置简单 |
| 小规模部署 | Docker Swarm | 简单易用 |
8.3 监控方案选型
| 需求 | 推荐方案 | 特点 |
|---|---|---|
| 指标监控 | Prometheus + Grafana | 云原生标准 |
| 日志监控 | ELK Stack | 功能强大 |
| 链路追踪 | SkyWalking | 国产,支持自动埋点 |
| 一体化 | Datadog / 阿里云ARMS | 商业产品,开箱即用 |