Laravel: Laravel生产部署实战

最后更新:2026-08-26

部署是把作品交给世界的最后一步——一次失误就可能让所有用户看到 500 错误页。

1. 你将学到


2. 一个上线夜的真实故事

(1) 痛点:手动部署每次都出问题

Bob 每次部署 ShopMetrics 都要:SSH 上服务器 → git pull → composer install → php artisan migrate → php artisan config:cache → 重启 queue worker → 重启 PHP-FPM。5 台服务器,手动操作 40 分钟,上个月有一次忘记跑 migrate 导致全站 500 错误,损失 2 千 USD。Charlie 说:"你这是用 1990 年的方式部署 2024 年的 SaaS。"

(2) Docker + CI/CD 的解法

Docker 容器化让每个环境完全一致,CI/CD 流水线让部署变成 git push 一条命令——测试、构建、部署全自动。

TEXT 📖 仅展示
git push → GitHub Actions → Test → Build Docker → Deploy → Health Check → Done

(3) 收益

Bob 上线 CI/CD 后,部署时间从 40 分钟降到 3 分钟,出错率从 10% 降到 0%,再也不用半夜 SSH 上服务器。


3. Docker 容器化

(1) 多阶段 Dockerfile

DOCKERFILE
# Dockerfile
# Stage 1: Build dependencies
FROM composer:2.7 AS build
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --no-progress
COPY . .
RUN php artisan route:cache && \
    php artisan config:cache && \
    php artisan view:cache

# Stage 2: Production image
FROM php:8.3-fpm-alpine AS production
WORKDIR /var/www/html

RUN apk add --no-cache \
    nginx \
    supervisor \
    pdo_mysql \
    gd \
    zip \
    redis

RUN docker-php-ext-install pdo_mysql gd zip opcache redis

COPY --from=build /app /var/www/html
COPY docker/opcache.ini /usr/local/etc/php/conf.d/opcache.ini
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/supervisord.conf /etc/supervisord.conf

RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

EXPOSE 8080
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]

(2) Docker Compose 编排

YAML
# docker-compose.prod.yml
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    ports:
      - "8080:8080"
    env_file:
      - .env.production
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy
    volumes:
      - storage:/var/www/html/storage
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
      interval: 30s
      timeout: 5s
      retries: 3

  queue:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    command: php artisan queue:work --queue=high,default --sleep=3 --tries=3
    env_file:
      - .env.production
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy
    volumes:
      - storage:/var/www/html/storage

  scheduler:
    build:
      context: .
      dockerfile: Dockerfile
    restart: unless-stopped
    command: php artisan schedule:work
    env_file:
      - .env.production
    depends_on:
      mysql:
        condition: service_healthy
      redis:
        condition: service_healthy

  mysql:
    image: mysql:8.0
    restart: unless-stopped
    environment:
      MYSQL_DATABASE: ${DB_DATABASE}
      MYSQL_USER: ${DB_USERNAME}
      MYSQL_PASSWORD: ${DB_PASSWORD}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    volumes:
      - mysql_data:/var/lib/mysql
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
      interval: 10s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    restart: unless-stopped
    command: redis-server --requirepass ${REDIS_PASSWORD}
    volumes:
      - redis_data:/data
    healthcheck:
      test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  mysql_data:
  redis_data:
  storage:

▶ 示例:ShopMetrics Docker 开发环境

YAML
# docker-compose.yml (Development)
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile.dev
    ports:
      - "8000:8000"
    volumes:
      - .:/var/www/html
    environment:
      DB_HOST: mysql
      REDIS_HOST: redis
    depends_on:
      - mysql
      - redis
      - mailpit

  mysql:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      MYSQL_DATABASE: shopmetrics
      MYSQL_USER: shopmetrics
      MYSQL_PASSWORD: secret
      MYSQL_ROOT_PASSWORD: secret
    volumes:
      - mysql_dev:/var/lib/mysql

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  mailpit:
    image: axllent/mailpit
    ports:
      - "1025:1025"   # SMTP
      - "8025:8025"   # Web UI

volumes:
  mysql_dev:

输出:

TEXT 📖 仅展示
CONTAINER ID   IMAGE          STATUS         PORTS
abc123         nginx:latest   Up 2 hours     0.0.0.0:80->80/tcp

4. Nginx + PHP-FPM 配置

(1) Nginx 配置

NGINX
# docker/nginx.conf
server {
    listen 8080;
    server_name shopmetrics.io api.shopmetrics.io;
    root /var/www/html/public;
    index index.php;

    charset utf-8;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    add_header X-XSS-Protection "1; mode=block";
    add_header Referrer-Policy "strict-origin-when-cross-origin";

    # Max upload size
    client_max_body_size 20M;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_hide_header X-Powered-By;

        # Buffers for large payloads
        fastcgi_buffer_size 128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size 256k;

        # Timeouts
        fastcgi_connect_timeout 60s;
        fastcgi_send_timeout 60s;
        fastcgi_read_timeout 60s;
    }

    # Deny access to static content
    location ~ /\.(?!well-known).* {
        deny all;
    }
}

(2) SSL 配置(Let's Encrypt)

NGINX
# SSL termination at reverse proxy or load balancer
server {
    listen 443 ssl http2;
    server_name shopmetrics.io;

    ssl_certificate /etc/letsencrypt/live/shopmetrics.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/shopmetrics.io/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name shopmetrics.io;
    return 301 https://$server_name$request_uri;
}

▶ 示例:ShopMetrics Nginx 多租户子域名路由

NGINX
# Route tenant subdomains
server {
    listen 443 ssl http2;
    server_name ~^(?<tenant>[^\.]+)\.shopmetrics\.io$;

    ssl_certificate /etc/letsencrypt/live/shopmetrics.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/shopmetrics.io/privkey.pem;

    # Pass tenant slug to Laravel
    location / {
        proxy_pass http://app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Tenant $tenant;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

输出:

TEXT 📖 仅展示
// 执行成功

5. CI/CD 流水线

(1) GitHub Actions 工作流

YAML
# .github/workflows/deploy.yml
name: Deploy ShopMetrics

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      mysql:
        image: mysql:8.0
        env:
          MYSQL_DATABASE: shopmetrics_test
          MYSQL_USER: test
          MYSQL_PASSWORD: test
          MYSQL_ROOT_PASSWORD: test
        ports: ['3306:3306']
      redis:
        image: redis:7-alpine
        ports: ['6379:6379']
    steps:
      - uses: actions/checkout@v4
      - uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          coverage: xdebug
      - name: Install dependencies
        run: composer install --no-progress --prefer-dist
      - name: Copy .env
        run: cp .env.example .env && php artisan key:generate
      - name: Run tests
        run: php artisan test --parallel --coverage-text
      - name: Check code style
        run: vendor/bin/pint --test

  build:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - name: Log in to Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.PROD_HOST }}
          username: ${{ secrets.PROD_USER }}
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            cd /var/www/shopmetrics
            docker compose -f docker-compose.prod.yml pull
            docker compose -f docker-compose.prod.yml up -d --remove-orphans
            docker compose -f docker-compose.prod.yml exec app php artisan migrate --force
            docker compose -f docker-compose.prod.yml exec app php artisan config:cache
            docker compose -f docker-compose.prod.yml exec app php artisan queue:restart
            sleep 5
            curl -sf http://localhost:8080/health || exit 1
            echo "Deploy successful!"

(2) 部署流程图

100%
flowchart LR
    A[git push main] --> B[GitHub Actions]
    B --> C[Run Tests]
    C -->|Pass| D[Build Docker Image]
    C -->|Fail| E[Notify + Block]
    D --> F[Push to Registry]
    F --> G[SSH to Production]
    G --> H[docker compose pull]
    H --> I[docker compose up -d]
    I --> J[php artisan migrate]
    J --> K[Cache + Queue Restart]
    K --> L[Health Check]
    L -->|OK| M[Deploy Done]
    L -->|Fail| N[Auto Rollback]

▶ 示例:ShopMetrics 部署健康检查端点

PHP
// routes/web.php
Route::get('/health', function () {
    $checks = [
        'database' => fn () => DB::connection()->getPdo() ? 'ok' : 'fail',
        'redis' => fn () => Cache::put('health_check', 'ok', 10) ? 'ok' : 'fail',
        'storage' => fn () => Storage::put('health_check', 'ok') ? 'ok' : 'fail',
    ];

    $results = collect($checks)->map(fn ($check) => $check());

    if ($results->contains('fail')) {
        return response()->json([
            'status' => 'unhealthy',
            'checks' => $results,
        ], 503);
    }

    return response()->json([
        'status' => 'healthy',
        'checks' => $results,
        'timestamp' => now()->toIso8601String(),
        'version' => config('app.version', 'unknown'),
    ]);
});

输出:

TEXT 📖 仅展示
// 执行成功

6. 部署检查清单

(1) 上线前检查清单

步骤 命令/操作 说明
1 .env 配置检查 APP_ENV=production, APP_DEBUG=false
2 php artisan key:generate 确认 APP_KEY 已设置
3 php artisan migrate --force 执行数据库迁移
4 php artisan config:cache 缓存配置
5 php artisan route:cache 缓存路由
6 php artisan view:cache 缓存视图
7 php artisan storage:link 创建 storage 链接
8 php artisan queue:restart 重启队列 Worker
9 权限检查 storage/ + bootstrap/cache/ 可写
10 健康检查 /health 返回 200

▶ 示例:ShopMetrics 自动化部署脚本

BASH
#!/bin/bash
# deploy.sh — Zero-downtime deployment script
set -e

APP_DIR="/var/www/shopmetrics"
RELEASES_DIR="/var/www/releases"
CURRENT_LINK="/var/www/current"
NEW_RELEASE=$(date +%Y%m%d%H%M%S)

echo "=== Deploying ShopMetrics ==="

# 1. Create release directory
mkdir -p "$RELEASES_DIR/$NEW_RELEASE"
cd "$RELEASES_DIR/$NEW_RELEASE"

# 2. Clone/pull code
git clone --depth 1 --branch main git@github.com:bob/shopmetrics.git .
echo "→ Code pulled"

# 3. Install dependencies
composer install --no-dev --optimize-autoloader --no-progress
echo "→ Dependencies installed"

# 4. Copy environment file
cp "$APP_DIR/.env.production" .env

# 5. Optimize
php artisan config:cache
php artisan route:cache
php artisan view:cache
echo "→ Caches built"

# 6. Switch symlink (atomic)
ln -sfn "$RELEASES_DIR/$NEW_RELEASE" "$CURRENT_LINK"
echo "→ Symlink switched"

# 7. Run migrations
cd "$CURRENT_LINK"
php artisan migrate --force
echo "→ Migrations done"

# 8. Restart queue workers
php artisan queue:restart
echo "→ Queue workers restarting"

# 9. Health check
sleep 3
if curl -sf http://localhost:8080/health > /dev/null; then
    echo "✓ Health check passed"
else
    echo "✗ Health check failed! Rolling back..."
    ln -sfn "$RELEASES_DIR/$(ls -t $RELEASES_DIR | sed -n '2p')" "$CURRENT_LINK"
    echo "✗ Rolled back"
    exit 1
fi

# 10. Cleanup old releases (keep last 5)
ls -t "$RELEASES_DIR" | tail -n +6 | xargs -r rm -rf
echo "→ Old releases cleaned"

echo "=== Deploy complete! ==="

输出:

TEXT 📖 仅展示
{"status":"ok","data":{}}

7. 零停机部署

(1) 部署策略对比

策略 停机时间 资源消耗 复杂度 适用场景
直接部署 5-30 秒 低流量/可接受短暂停机
Blue-Green 0 2x 高可用要求
Rolling Update 0 1.5x 多实例部署
Canary 0 1.1x 大规模/需灰度验证

(2) Blue-Green 部署

100%
flowchart LR
    subgraph Blue["Blue (Current)"]
        B1[App v1.0]
        B2[DB v1.0]
    end
    subgraph Green["Green (New)"]
        G1[App v1.1]
        G2[DB v1.1]
    end
    LB[Load Balancer] -->|"100%"| B1
    LB -.->|"0%"| G1
    
    LB -->|"Switch after health check"| G1
BASH
# Blue-Green deployment with Docker
# Current: blue is live, green is idle
docker compose -f docker-compose.blue.yml up -d
# Health check green
curl -sf http://green:8080/health || exit 1
# Switch traffic (update nginx upstream)
echo "server green:8080;" > /etc/nginx/conf.d/upstream.conf
nginx -s reload
# Stop old blue
docker compose -f docker-compose.blue.yml down

▶ 示例:ShopMetrics GitHub Actions 零停机部署

YAML
# .github/workflows/zero-downtime-deploy.yml
name: Zero-Downtime Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - name: Determine active slot
        uses: appleboy/ssh-action@v1
        id: slot
        with:
          host: ${{ secrets.PROD_HOST }}
          username: deploy
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            if docker compose -f docker-compose.blue.yml ps | grep -q "Up"; then
              echo "ACTIVE=blue" >> $GITHUB_OUTPUT
              echo "DEPLOY=green" >> $GITHUB_OUTPUT
            else
              echo "ACTIVE=green" >> $GITHUB_OUTPUT
              echo "DEPLOY=blue" >> $GITHUB_OUTPUT
            fi

      - name: Deploy to inactive slot
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.PROD_HOST }}
          username: deploy
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            DEPLOY=${{ steps.slot.outputs.DEPLOY }}
            docker compose -f docker-compose.${DEPLOY}.yml pull
            docker compose -f docker-compose.${DEPLOY}.yml up -d
            docker compose -f docker-compose.${DEPLOY}.yml exec app php artisan migrate --force
            docker compose -f docker-compose.${DEPLOY}.yml exec app php artisan config:cache

      - name: Health check & switch traffic
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.PROD_HOST }}
          username: deploy
          key: ${{ secrets.PROD_SSH_KEY }}
          script: |
            DEPLOY=${{ steps.slot.outputs.DEPLOY }}
            ACTIVE=${{ steps.slot.outputs.ACTIVE }}
            # Wait for health check
            for i in $(seq 1 10); do
              if curl -sf http://localhost:8080/health; then break; fi
              sleep 2
            done
            # Switch nginx upstream
            echo "server ${DEPLOY}:8080;" > /etc/nginx/conf.d/upstream.conf
            nginx -s reload
            # Stop old slot
            docker compose -f docker-compose.${ACTIVE}.yml down
            echo "Zero-downtime deploy complete!"

输出:

TEXT 📖 仅展示
CONTAINER ID   IMAGE          STATUS         PORTS
abc123         nginx:latest   Up 2 hours     0.0.0.0:80->80/tcp

8. 综合示例:ShopMetrics 完整部署配置

DOCKERFILE
# ============================================
# Comprehensive: ShopMetrics Production Dockerfile
# Multi-stage build with optimization
# ============================================

# Stage 1: Build frontend assets
FROM node:20-alpine AS frontend
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY vite.config.ts tailwind.config.js postcss.config.js ./
COPY resources/ ./resources/
RUN npm run build

# Stage 2: Install PHP dependencies
FROM composer:2.7 AS backend
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-scripts --prefer-dist --no-progress --classmap-authoritative
COPY . .
COPY --from=frontend /app/public/build ./public/build
RUN php artisan route:cache && \
    php artisan config:cache && \
    php artisan view:cache && \
    php artisan event:cache

# Stage 3: Production image
FROM php:8.3-fpm-alpine AS production
WORKDIR /var/www/html

RUN apk add --no-cache \
    curl nginx supervisor mysql-client \
    && docker-php-ext-install pdo_mysql opcache pcntl

COPY docker/opcache.ini /usr/local/etc/php/conf.d/
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/supervisord.conf /etc/supervisord.conf
COPY docker/entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

COPY --from=backend /app /var/www/html
RUN chown -R www-data:www-data storage bootstrap/cache

EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

ENTRYPOINT ["/entrypoint.sh"]
BASH
#!/bin/bash
# docker/entrypoint.sh
set -e

echo "→ Running migrations..."
php artisan migrate --force

echo "→ Starting supervisord..."
exec /usr/bin/supervisord -c /etc/supervisord.conf
INI
; docker/supervisord.conf
[supervisord]
nodaemon=true
user=root

[program:php-fpm]
command=php-fpm --nodaemonize
autorestart=true

[program:nginx]
command=nginx -g 'daemon off;'
autorestart=true

[program:queue-worker]
command=php artisan queue:work --queue=high,default --sleep=3 --tries=3 --max-time=3600
autorestart=true
user=www-data
numprocs=2
process_name=%(program_name)s_%(process_num)02d

❓ 常见问题

Q Docker 和传统部署哪个好?
A Docker 优势是环境一致、部署可重复、扩容简单。缺点是学习成本和少量性能开销(<5%)。新项目建议 Docker;已有传统部署的项目可渐进迁移。
Q SSL 证书怎么管理?
A 用 Let's Encrypt + Certbot 自动续期;或在云平台(AWS ALB/Cloudflare)终止 SSL,后端只需 HTTP。不要手动管理证书。
Q 数据库迁移在生产环境安全吗?
A 只加列/加索引是安全的;删列/改列类型需要先加新列→迁移数据→再删旧列。用 php artisan migrate --force 并在 CI 中自动执行,失败则阻断部署。
Q Docker 镜像太大怎么办?
A 用 Alpine 基础镜像、多阶段构建(不拷贝 node_modules/.git)、composer install 加 --no-dev、用 .dockerignore 排除测试文件。目标 < 200MB。
Q CI/CD 流水线怎么处理回滚?
A 保留最近 5 个版本的 Docker 镜像,回滚只需 docker compose pull <previous-version> + docker compose up -d。Blue-Green 部署回滚更快——切回旧 slot 即可。
Q queue:restart 会丢失任务吗?
A 不会。queue:restart 让 Worker 处理完当前任务后优雅退出,Supervisor 会自动重启新 Worker。未开始的任务留在队列中等待新 Worker 处理。

📖 小节


📝 作业

  1. 基础题(⭐):为 ShopMetrics 编写 Docker Compose 开发环境配置(app + mysql + redis + mailpit),确保 docker compose up -d 后可以直接访问应用。

  2. 进阶题(⭐⭐):编写 GitHub Actions 工作流,实现 push main 分支时自动:运行测试 → 构建 Docker 镜像 → 推送到 Registry → SSH 部署到服务器 → 健康检查。包含测试失败和健康检查失败的阻断逻辑。

  3. 挑战题(⭐⭐⭐):实现完整的 Blue-Green 零停机部署方案:两套 docker-compose 配置、自动检测活跃 slot、部署到非活跃 slot、健康检查、Nginx upstream 切换、旧 slot 优雅停止。编写回滚脚本,可在 30 秒内回滚到上一版本。

Web-Tutorial.com

Web-Tutorial 技术团队

由多位开发者共同维护的编程教程平台。每篇教程由对应领域的开发者编写和审核,确保内容准确可靠。如发现任何问题,欢迎向我们反馈。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏