开源软件和工具的使用文档与参考手册。
Apache HTTP Server(简称 Apache 或 httpd)是世界上最流行的 Web 服务器软件之一,由 Apache 软件基金会开发和维护。
在 Debian/Ubuntu 系统中,Apache 软件包名为 apache2,配置文件结构有所不同:
| 方面 | 上游 Apache | Debian apache2 |
|---|---|---|
| 主配置 | httpd.conf |
apache2.conf |
| 站点配置 | 直接编辑主配置 | sites-available/ + sites-enabled/ |
| 模块配置 | 直接编辑主配置 | mods-available/ + mods-enabled/ |
| 启动命令 | apachectl |
systemctl apache2 |
| 默认文档根 | /usr/local/apache2/htdocs |
/var/www/html |
| 用户/组 | 编译时指定 | www-data:www-data |
# 虚拟主机配置
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog ${APACHE_LOG_DIR}/example_error.log
CustomLog ${APACHE_LOG_DIR}/example_access.log combined
</VirtualHost>
# SSL 配置
<VirtualHost *:443>
ServerName secure.example.com
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.crt
SSLCertificateKeyFile /etc/ssl/private/example.key
</VirtualHost>
# 反向代理
ProxyPass /api http://backend:8080/api
ProxyPassReverse /api http://backend:8080/api
# 启用压缩
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
# 启用缓存
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
</IfModule>
# MPM Event 配置(推荐高并发场景)
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 400
MaxConnectionsPerChild 0
</IfModule>
RabbitMQ 和 Apache Kafka 是两种广泛使用的消息中间件,但设计理念和适用场景有显著差异。
| 特性 | RabbitMQ | Apache Kafka |
|---|---|---|
| 设计模式 | 传统消息队列(MQ) | 分布式流处理平台 |
| 消息模型 | 队列(点对点)、发布/订阅 | 发布/订阅(分区日志) |
| 消息持久化 | 可选(内存/磁盘) | 强制持久化(磁盘) |
| 消息顺序 | 单队列内有序 | 分区内有序 |
| 吞吐量 | 万级/秒 | 百万级/秒 |
| 消息回溯 | 消费即删除 | 保留策略可配置 |
| 协议支持 | AMQP、MQTT、STOMP、HTTP | 自定义协议(TCP) |
| 集群模式 | 镜像队列、联邦 | 分区复制、ISR |
| 延迟消息 | 原生支持(死信交换机) | 需自行实现 |
选择 RabbitMQ 当:
选择 Kafka 当:
Producer → Exchange → [Binding] → Queue → Consumer
direct:精确匹配 routing keytopic:模式匹配(order.*、payment.#)fanout:广播到所有绑定队列headers:基于消息头属性匹配Producer → Topic(Partition 0, Partition 1...) → Consumer Group
| 场景 | RabbitMQ | Kafka |
|---|---|---|
| 单节点吞吐量 | 10K-50K msg/s | 100K-1M msg/s |
| 延迟(空载) | 1ms | 2-5ms |
| 延迟(满载) | 10-100ms | 5-20ms |
| 消息保留 | 消费后删除 | 默认 7 天,可配置 |
ElasticSearch 是一个基于 Lucene 的分布式搜索和分析引擎,广泛应用于全文搜索、日志分析、指标监控等场景。
// 全文搜索
{
"query": {
"multi_match": {
"query": "分布式系统",
"fields": ["title^3", "content", "tags"],
"type": "best_fields"
}
},
"highlight": {
"fields": {
"content": {}
}
}
}
// 聚合分析
{
"aggs": {
"status_stats": {
"terms": {
"field": "status"
},
"aggs": {
"avg_response_time": {
"avg": {
"field": "response_time"
}
}
}
}
}
}
# 查看集群健康状态
curl -X GET "localhost:9200/_cluster/health?pretty"
# 查看索引状态
curl -X GET "localhost:9200/_cat/indices?v"
# 查看节点信息
curl -X GET "localhost:9200/_cat/nodes?v"
# 强制合并段(维护操作)
curl -X POST "localhost:9200/my-index/_forcemerge?max_num_segments=1"
Mapping 优化:
"index": false"doc_values": false索引策略:
logs-2024.01.01)查询优化:
filter 上下文替代 must(可缓存)search_after_sourcePrometheus 是云原生时代最流行的监控和告警工具,采用拉取(Pull)模式采集指标。
metric_name{label1="value1", label2="value2"} value timestamp
# 瞬时向量选择器
http_requests_total{job="api", status="200"}
# 范围向量(过去5分钟)
http_requests_total[5m]
# 聚合操作
sum(rate(http_requests_total[5m])) by (job)
# 计算错误率
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m]))
# 百分位数
histogram_quantile(0.99,
sum(rate(http_request_duration_seconds_bucket[5m])) by (le))
# 同比(与1天前比较)
http_requests_total - http_requests_total offset 1d
groups:
- name: api_alerts
rules:
- alert: HighErrorRate
expr: |
sum(rate(http_requests_total{status=~"5.."}[5m]))
/ sum(rate(http_requests_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "High error rate detected"
description: "Error rate is {{ $value humanizePercentage }}"
- alert: ServiceDown
expr: up{job="api"} == 0
for: 1m
labels:
severity: critical
┌─────────────┐ ┌─────────────┐
│ Prometheus │◄────┤ Exporters │
│ (Primary) │ │ (Node, App)│
└──────┬──────┘ └─────────────┘
│
▼
┌─────────────┐ ┌─────────────┐
│ Thanos/ │────►│ Grafana │
│ Cortex │ │ (可视化) │
│ (长期存储) │ └─────────────┘
└─────────────┘
Grafana 是开源的可视化和分析平台,支持多种数据源,是监控系统的标准可视化层。
数据源 适用场景
------------------
Prometheus 指标监控
ElasticSearch 日志分析
InfluxDB 时序数据
MySQL/PostgreSQL 业务数据
Loki 日志聚合
Jaeger/Tempo 链路追踪
-- 数据源变量
$prometheus
-- 查询变量(动态下拉)
label_values(kube_pod_info, namespace)
-- 级联变量
label_values(kube_pod_info{namespace="$namespace"}, pod)
-- 在查询中使用
sum(rate(container_cpu_usage_seconds_total{namespace="$namespace", pod="$pod"}[5m]))
Grafana 8.0+ 引入统一告警系统:
# 告警规则(Provisioning)
apiVersion: 1
contactPoints:
- orgId: 1
name: 'slack-alerts'
receivers:
- uid: 'slack'
type: slack
settings:
url: 'https://hooks.slack.com/...'
policies:
- orgId: 1
receiver: 'slack-alerts'
group_by: ['alertname', 'grafana_folder', 'job']
InfluxDB 是专为时序数据设计的数据库,在 IoT、监控、金融等领域广泛应用。
特性 InfluxDB 1.x InfluxDB 2.x/3.x
-------------------------------------
查询语言 InfluxQL Flux / InfluxQL
集成 TICK Stack 内置 UI、任务、告警
存储引擎 TSM IOx (Apache Arrow)
性能 百万级写入/秒 千万级写入/秒
-- 基本查询
SELECT mean("value") FROM "temperature"
WHERE "location" = 'room1'
AND time > now() - 1h
GROUP BY time(5m)
-- 连续查询(降采样)
CREATE CONTINUOUS QUERY "cq_5m" ON "mydb"
BEGIN
SELECT mean("value") INTO "mydb"."rp_5m"."temperature"
FROM "mydb"."autogen"."temperature"
GROUP BY time(5m)
END
-- 保留策略
CREATE RETENTION POLICY "rp_7d" ON "mydb"
DURATION 7d REPLICATION 1 DEFAULT
场景 InfluxDB Prometheus
----------------------------
长期存储 ✅ 内置 需 Thanos/Cortex
高基数数据 ✅ 支持标签 基数过高影响性能
告警能力 ✅ 内置 Kapacitor 需 Alertmanager
生态集成 TICK Stack Kubernetes 原生
查询灵活性 InfluxQL/Flux PromQL
Docker 是容器化技术的标准,实现了应用及其依赖的打包和隔离运行。
# 使用多阶段构建减小镜像
FROM golang:1.21 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o server
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/server .
CMD ["./server"]
# 安全实践
USER nonroot
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s \
CMD curl -f http://localhost:8080/health exit 1
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- DB_HOST=db
depends_on:
db:
condition: service_healthy
deploy:
replicas: 2
resources:
limits:
cpus: '0.5'
memory: 512M
db:
image: postgres:15-alpine
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 5s
retries: 5
volumes:
pgdata:
镜像安全:
docker scan 或 Trivy)运行时安全:
--read-only--privileged=false网络安全:
Kubernetes(K8s)是容器编排平台的事实标准,提供自动化部署、扩展和管理容器化应用的能力。
资源 用途
------------
Pod 最小部署单元,包含一个或多个容器
Deployment 声明式管理 Pod 副本
StatefulSet 有状态应用(数据库、消息队列)
DaemonSet 每个节点运行一个 Pod(日志采集、监控)
Service 服务发现和负载均衡
Ingress HTTP/HTTPS 路由
ConfigMap/Secret 配置和敏感数据管理
PersistentVolume 持久化存储
# 资源管理
kubectl get pods -o wide --all-namespaces
kubectl describe pod <pod-name>
kubectl logs <pod-name> --previous # 查看崩溃前日志
kubectl exec -it <pod-name> -- /bin/sh
# 调试
kubectl port-forward svc/my-service 8080:80
kubectl top pod --sort-by=cpu
kubectl debug <pod-name> -it --image=busybox --target=my-app
# 高级操作
kubectl apply -f manifest.yaml --dry-run=client
kubectl rollout status deployment/my-app
kubectl rollout undo deployment/my-app
kubectl scale deployment my-app --replicas=5
# 资源配额
kubectl get resourcequota -n my-namespace
kubectl top node
# 添加仓库
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# 安装 Chart
helm install my-release bitnami/postgresql \
--set auth.postgresPassword=secret \
--set persistence.size=10Gi
# 自定义 values
helm upgrade my-release bitnami/postgresql -f custom-values.yaml
# 模板调试
helm template my-release ./my-chart --debug
GitLab 是完整的 DevOps 平台,提供代码托管、CI/CD、项目管理等功能。
stages:
- build
- test
- deploy
variables:
DOCKER_REGISTRY: registry.gitlab.com
IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
build:
stage: build
image: docker:latest
services:
- docker:dind
script:
- docker build -t $IMAGE_TAG .
- docker push $IMAGE_TAG
only:
- main
test:
stage: test
image: $IMAGE_TAG
script:
- pytest --cov=app --cov-report=xml
artifacts:
reports:
coverage_report:
coverage_format: cobertura
path: coverage.xml
deploy:
stage: deploy
image: bitnami/kubectl:latest
script:
- kubectl set image deployment/app app=$IMAGE_TAG
environment:
name: production
url: https://app.example.com
only:
- main
# 获取项目信息
curl -H "PRIVATE-TOKEN: <token>" \
"https://gitlab.example.com/api/v4/projects/42"
# 创建合并请求
curl -X POST -H "PRIVATE-TOKEN: <token>" \
-H "Content-Type: application/json" \
-d '{
"source_branch": "feature/new-api",
"target_branch": "main",
"title": "Add new API endpoint",
"description": "Implements user authentication"
}' \
"https://gitlab.example.com/api/v4/projects/42/merge_requests"
Gradle 是现代化的构建工具,采用基于 Groovy/Kotlin DSL 的配置方式,支持增量构建和构建缓存。
plugins {
java
application
id("org.springframework.boot") version "3.2.0"
id("io.spring.dependency-management") version "1.1.4"
}
group = "com.example"
version = "1.0.0"
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(21))
}
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
runtimeOnly("org.postgresql:postgresql")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.testcontainers:junit-jupiter:1.19.0")
testImplementation("org.testcontainers:postgresql:1.19.0")
}
tasks.test {
useJUnitPlatform()
testLogging {
events("passed", "skipped", "failed")
}
}
// 自定义任务
tasks.register<Zip>("packageDist") {
from(tasks.bootJar)
from("src/main/resources/config")
archiveFileName.set("${project.name}-${version}.zip")
}
# 启用构建缓存
gradle build --build-cache
# 并行构建
gradle build --parallel
# 配置守护进程
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configureondemand=true
Maven 是 Java 项目的主流构建工具,采用声明式配置和约定优于配置的理念。
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-service</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<!-- 父 POM -->
<modules>
<module>common</module>
<module>service-api</module>
<module>service-impl</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>common</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
Jupyter Notebook 是交互式计算环境,支持代码、文档、可视化的混合编排。
# 性能分析
%timeit sum(range(10000))
# 内存分析
%memit large_operation()
# 加载外部代码
%load script.py
# 环境信息
%env
%pwd
%ls
# 调试
%debug
%pdb on
代码组织:
%run utils.py 加载版本控制:
.ipynb 转换为 .py 或 .mdjupyter nbconvert --clear-output生产化:
jupyter nbconvert --to scriptSSL/TLS 证书是 HTTPS 通信的基础,正确管理证书对安全至关重要。
| 类型 | 验证级别 | 适用场景 |
|---|---|---|
| DV(域名验证) | 低 | 个人网站、博客 |
| OV(组织验证) | 中 | 企业官网 |
| EV(扩展验证) | 高 | 金融、电商 |
| Wildcard | - | 同一域名下所有子域 |
| SAN(多域名) | - | 多个不同域名 |
# 使用 Certbot
sudo certbot certonly --standalone -d example.com -d www.example.com
# 自动续期(systemd timer)
sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer
# Nginx 集成
sudo certbot --nginx -d example.com
# PEM to PFX
openssl pkcs12 -export -out cert.pfx \
-inkey private.key -in certificate.crt -certfile ca.crt
# PFX to PEM
openssl pkcs12 -in cert.pfx -out cert.pem -nodes
# 查看证书信息
openssl x509 -in certificate.crt -text -noout
openssl s_client -connect example.com:443 -servername example.com
Debian 系统安全基线是服务器部署的基础要求。
# 1. 系统更新
sudo apt update && sudo apt upgrade -y
sudo apt install -y unattended-upgrades
# 2. 时区配置
sudo timedatectl set-timezone Asia/Shanghai
sudo apt install -y ntp
# 3. 防火墙
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
# 4. SSH 加固
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config
sudo systemctl restart sshd
# 5. fail2ban
sudo apt install -y fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo systemctl enable fail2ban
# 6. 日志审计
sudo apt install -y auditd
sudo auditctl -w /etc/passwd -p wa -k identity_changes
# LVM 基础操作
sudo pvcreate /dev/sdb
sudo vgcreate vg_data /dev/sdb
sudo lvcreate -L 100G -n lv_app vg_data
sudo mkfs.ext4 /dev/vg_data/lv_app
# 挂载配置
sudo mkdir /app
sudo mount /dev/vg_data/lv_app /app
echo '/dev/vg_data/lv_app /app ext4 defaults 0 2' | sudo tee -a /etc/fstab
# 磁盘监控
df -h
lsblk
sudo lvs
sudo vgs
Grimoire 是开源项目健康度分析平台,基于 CHAOSS 指标评估社区和项目状态。
| 类别 | 指标 | 说明 |
|---|---|---|
| 代码开发 | 提交频率 | 代码变更活跃度 |
| 代码审查 | PR/MR 审查参与度 | |
| 问题处理 | 问题响应时间 | Bug/Feature 处理效率 |
| 问题解决率 | 关闭/创建比率 | |
| 社区 | 贡献者多样性 | 新/老贡献者比例 |
| elephant factor | 50% 贡献由多少开发者完成 | |
| 治理 | 决策透明度 | 公开讨论比例 |
# projects.json
{
"projects": {
"my-project": {
"git": ["https://github.com/org/repo.git"],
"github": ["https://github.com/org/repo"],
"gitlab:issue": ["https://gitlab.com/org/repo"]
}
}
}
GrimoireLab 提供 Kibana 预配置面板:
OpenSearch 是 ElasticSearch 的开源分支,由 AWS 主导维护,保持完全开源协议。
| 方面 | OpenSearch | ElasticSearch 7.x+ |
|---|---|---|
| 许可证 | Apache 2.0 | SSPL/Elastic |
| 安全功能 | 开源内置 | X-Pack 商业版 |
| 告警 | 开源内置 | Watcher 商业版 |
| 机器学习 | 开源插件 | X-Pack ML 商业版 |
| 兼容性 | 兼容 ES 7.10 | 后续版本不兼容 |
# docker-compose.yml
version: '3'
services:
opensearch:
image: opensearchproject/opensearch:2.11.0
environment:
- discovery.type=single-node
- plugins.security.disabled=true # 开发环境禁用安全
- "OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m"
ports:
- 9200:9200
volumes:
- opensearch-data:/usr/share/opensearch/data
dashboards:
image: opensearchproject/opensearch-dashboards:2.11.0
ports:
- 5601:5601
environment:
- 'OPENSEARCH_HOSTS=["http://opensearch:9200"]'
volumes:
opensearch-data:
| 需求场景 | 推荐方案 | 备选方案 |
|---|---|---|
| Web 服务器 | Nginx | Apache |
| 消息队列(低延迟) | RabbitMQ | NATS |
| 消息队列(高吞吐) | Kafka | Pulsar |
| 搜索引擎 | ElasticSearch | OpenSearch |
| 日志分析 | ELK/EFK | Loki + Grafana |
| 指标监控 | Prometheus + Grafana | InfluxDB + Grafana |
| 容器编排 | Kubernetes | Docker Swarm |
| CI/CD | GitLab CI | GitHub Actions |
| Java 构建 | Maven | Gradle |
| 数据科学 | Jupyter + Python | RStudio |
| 证书管理 | Let's Encrypt | 商业 CA |