Laravel 大型应用架构部署指南
构建大型 Laravel 应用需要精心设计的架构和部署策略。以下是针对高流量、高可用性 Laravel 应用的完整架构方案。
一、架构设计
1. 分层架构
┌─────────────────────────────────────────────────┐
│ 客户端层 │
│ (Web/移动端/API消费者) │
└───────────────┬─────────────────┬───────────────┘
│ │
┌───────────────▼─────┐ ┌─────────▼───────────────┐
│ 负载均衡层 │ │ CDN │
│ (Nginx/Haproxy/ALB) │ │ (CloudFront/Cloudflare) │
└───────────────┬─────┘ └─────────┬───────────────┘
│ │
┌───────────────▼─────────────────▼───────────────┐
│ 应用服务器层 │
│ (多节点Laravel应用+PHP-FPM集群) │
└───────────────┬─────────────────────────────────┘
│
┌───────────────▼─────────────────────────────────┐
│ 服务层 │
│ (Redis集群/Elasticsearch/消息队列/微服务) │
└───────────────┬─────────────────────────────────┘
│
┌───────────────▼─────────────────────────────────┐
│ 数据层 │
│ (MySQL集群/读写分离/分库分表) │
└─────────────────────────────────────────────────┘
二、基础设施部署
1. 容器化部署 (Kubernetes)
# deployment.yaml 示例
apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
spec:
replicas: 6
selector:
matchLabels:
app: laravel
template:
metadata:
labels:
app: laravel
spec:
containers:
- name: app
image: your-registry/laravel-app:1.0.0
ports:
- containerPort: 9000
envFrom:
- configMapRef:
name: laravel-config
resources:
requests:
cpu: "500m"
memory: "512Mi"
limits:
cpu: "1000m"
memory: "1024Mi"
livenessProbe:
httpGet:
path: /health
port: 9000
initialDelaySeconds: 30
periodSeconds: 10
---
# Horizontal Pod Autoscaler
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: laravel-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: laravel-app
minReplicas: 4
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
2. 服务网格集成 (Istio)
# 虚拟服务配置
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: laravel-vs
spec:
hosts:
- "yourdomain.com"
gateways:
- laravel-gateway
http:
- route:
- destination:
host: laravel-app
port:
number: 9000
weight: 100
retries:
attempts: 3
perTryTimeout: 2s
timeout: 5s
三、关键组件配置
1. 数据库架构
// config/database.php
'mysql' => [
'read' => [
'host' => [
env('DB_READ_HOST_1', 'read1.db.cluster'),
env('DB_READ_HOST_2', 'read2.db.cluster'),
],
],
'write' => [
'host' => env('DB_WRITE_HOST', 'write.db.cluster'),
],
'sticky' => true,
'driver' => 'mysql',
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
// ...
],
2. Redis 集群配置
// config/database.php
'redis' => [
'cluster' => env('REDIS_CLUSTER', true),
'default' => [
[
'host' => env('REDIS_HOST_1', 'redis1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
[
'host' => env('REDIS_HOST_2', 'redis2'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', 6379),
'database' => 0,
],
],
'cache' => [
// 单独配置缓存Redis
],
],
四、性能优化
1. 缓存策略
// 使用多级缓存
$value = Cache::remember('key', $seconds, function () {
return DB::table(...)->get();
});
// 标签缓存
Cache::tags(['people', 'authors'])->put('John', $john, $seconds);
2. 队列优化
// 配置多个队列连接
'connections' => [
'default' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
],
'processing' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX'),
'queue' => env('SQS_QUEUE'),
'region' => env('AWS_DEFAULT_REGION'),
],
],
五、监控与日志
1. Prometheus 监控配置
# prometheus.yml
scrape_configs:
- job_name: 'laravel'
metrics_path: '/metrics'
static_configs:
- targets: ['laravel-app:9000']
relabel_configs:
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
2. 集中式日志 (ELK)
// config/logging.php
'stacks' => [
'elastic' => [
'driver' => 'custom',
'via' => \App\Logging\ElasticsearchLogger::class,
'level' => 'debug',
'hosts' => [
[
'host' => env('ELASTICSEARCH_HOST', 'elasticsearch'),
'port' => env('ELASTICSEARCH_PORT', 9200),
'scheme' => env('ELASTICSEARCH_SCHEME', 'https'),
]
],
],
],
六、CI/CD 流程
1. GitLab CI 示例
stages:
- test
- build
- deploy
unit_tests:
stage: test
image: php:8.1
script:
- apt-get update && apt-get install -y git unzip
- curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
- composer install --prefer-dist --no-ansi --no-interaction --no-progress --no-scripts
- vendor/bin/phpunit
build_image:
stage: build
image: docker:latest
services:
- docker:dind
script:
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
- docker build -t $CI_REGISTRY_IMAGE:latest .
- docker push $CI_REGISTRY_IMAGE:latest
deploy_production:
stage: deploy
image: bitnami/kubectl:latest
script:
- kubectl apply -f kubernetes/deployment.yaml
- kubectl rollout status deployment/laravel-app
environment:
name: production
url: https://yourdomain.com
when: manual
七、安全最佳实践
-
网络安全:
- 使用 WAF (Web Application Firewall)
- 配置 VPC 网络隔离
- 启用 DDoS 防护
-
应用安全:
// 强制 HTTPS URL::forceScheme('https'); // CSP 头 header("Content-Security-Policy: default-src 'self'");
-
密钥管理:
- 使用 Vault 或 KMS 管理密钥
- 定期轮换数据库凭证
八、扩展策略
-
水平扩展:
- 无状态应用层自动扩展
- 数据库读写分离
-
垂直扩展:
- 数据库优化 (索引、分表)
- 查询缓存
-
功能解耦:
// 使用事件驱动架构 event(new OrderShipped($order)); // 微服务通信 Http::post('inventory-service/api/update', [...]);
这套架构可以支持日 PV 千万级的大型 Laravel 应用,根据实际业务需求可进一步调整优化。
No Comments