optimize-docker-startup

优化 PHP 应用的 Docker 容器启动时间,重点通过预加载、缓存和入口点优化来减少初始化开销。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "optimize-docker-startup":https://skillpi.com/zh/skills/deepskill-647787246a0cb06b275dd2661ba05bebcb5832d7b4f3ff35e2d1ffe4dd072b43。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

优化 PHP 应用的 Docker 容器启动时间,重点通过预加载、缓存和入口点优化来减少初始化开销。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: optimize-docker-startup
description: Optimizes Docker container startup time for PHP applications. Reduces initialization overhead through preloading, caching, and entrypoint optimization.

Docker Container Startup Optimization

Reduces cold start and initialization time for PHP applications in Docker containers.

Startup Time Breakdown

┌─────────────────────────────────────────────────────────────────┐
│              TYPICAL PHP CONTAINER STARTUP TIMELINE              │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Container create:  ██░░░░░░░░░░░░░░░░░░░░░░░░  0.5s  (3%)    │
│  Entrypoint script: ████████░░░░░░░░░░░░░░░░░░  3.0s  (20%)   │
│  Migrations check:  ██████░░░░░░░░░░░░░░░░░░░░  2.0s  (13%)   │
│  Cache warmup:      ████████████░░░░░░░░░░░░░░  4.0s  (27%)   │
│  OPcache preload:   ██████░░░░░░░░░░░░░░░░░░░░  2.0s  (13%)   │
│  PHP-FPM start:     ████░░░░░░░░░░░░░░░░░░░░░░  1.0s  (7%)    │
│  Health check pass: ██████░░░░░░░░░░░░░░░░░░░░  2.5s  (17%)   │
│                                                                 │
│  Total unoptimized: ████████████████████████████ ~15s           │
│  Target optimized:  ██████████░░░░░░░░░░░░░░░░  ~5s  (-67%)   │
└─────────────────────────────────────────────────────────────────┘

OPcache Preloading for Startup

; Preload critical classes at PHP-FPM startup (not per-request)
opcache.preload = /app/config/preload.php
opcache.preload_user = www-data

Preload Strategy

<?php
// config/preload.php
// Preload hot-path classes to eliminate first-request compilation

$directories = [
    '/app/src/Domain/',
    '/app/src/Application/',
    '/app/vendor/symfony/http-kernel/',
    '/app/vendor/symfony/routing/',
    '/app/vendor/symfony/dependency-injection/',
    '/app/vendor/doctrine/orm/src/',
];

foreach ($directories as $dir) {
    if (!is_dir($dir)) continue;
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($iterator as $file) {
        if ($file->getExtension() === 'php') {
            opcache_compile_file($file->getRealPath());
        }
    }
}

Impact: Eliminates 200-500ms first-request compilation latency.

Composer Autoloader Optimization

# ❌ SLOW: PSR-4 autoloading (filesystem lookups per class)
RUN composer dump-autoload

# ✅ FAST: Classmap authoritative (single array lookup)
RUN composer dump-autoload --optimize --classmap-authoritative
Mode Startup Runtime Use Case
Default (PSR-4) Fast Slow (file scan) Development
--optimize Medium Fast (classmap + PSR-4 fallback) Staging
--classmap-authoritative Slow (once) Fastest (classmap only) Production

Impact: Reduces autoload time by 60-80% on each request.

Framework Cache Warmup

Symfony

# Warm up cache at build time (not at startup)
RUN php bin/console cache:warmup --env=prod --no-debug

# Pre-compile DI container, routes, templates
RUN php bin/console cache:clear --env=prod --no-debug \
    && php bin/console cache:warmup --env=prod --no-debug

Laravel

# Cache configuration, routes, and views at build time
RUN php artisan config:cache \
    && php artisan route:cache \
    && php artisan view:cache \
    && php artisan event:cache
Command What It Caches Time Saved
config:cache All config files into single file 50-100ms
route:cache Route registrations 100-300ms
view:cache Blade template compilation 50-200ms
event:cache Event-listener mappings 20-50ms

Impact: Eliminates 300-600ms of startup/first-request overhead.

Entrypoint Optimization

Anti-Pattern: Sequential Blocking Entrypoint

#!/bin/bash
# ❌ SLOW: Everything runs sequentially, blocks startup

# Wait for database (blocks for 5-10s)
until mysql -h db -u root -p$PASS -e "SELECT 1" > /dev/null 2>&1; do
    sleep 1
done

# Run migrations (blocks for 2-5s)
php bin/console doctrine:migrations:migrate --no-interaction

# Clear and warm cache (blocks for 3-5s)
php bin/console cache:clear --env=prod
php bin/console cache:warmup --env=prod

# Start PHP-FPM
php-fpm

Optimized: Parallel and Background Tasks

#!/bin/sh
# ✅ FAST: Parallel init, non-blocking tasks in background

set -e

# Run non-critical tasks in background
{
    # Wait for DB and run migrations (non-blocking)
    /app/bin/wait-for-it.sh db:3306 --timeout=30
    php bin/console doctrine:migrations:migrate --no-interaction 2>&1 | logger -t migrations
} &

# Cache should be warmed at build time, but verify
if [ ! -d "/app/var/cache/prod" ]; then
    php bin/console cache:warmup --env=prod --no-debug
fi

# Start PHP-FPM immediately
exec php-fpm

Impact: Reduces startup from 15s to 3-5s by parallelizing non-critical init.

Wait-for-It Pattern

#!/bin/sh
# /app/bin/wait-for-it.sh - lightweight dependency check
HOST=$(echo "$1" | cut -d: -f1)
PORT=$(echo "$1" | cut -d: -f2)
TIMEOUT=${3:-30}

for i in $(seq 1 "$TIMEOUT"); do
    nc -z "$HOST" "$PORT" 2>/dev/null && exit 0
    sleep 1
done
echo "Timeout waiting for $HOST:$PORT" >&2
exit 1

Health Check Configuration

start_period Tuning

services:
  php-fpm:
    healthcheck:
      test: ["CMD", "php-fpm-healthcheck"]
      interval: 10s
      timeout: 5s
      start_period: 15s
      retries: 3
Parameter Purpose Recommendation
start_period Grace period before health checks count Set to expected startup time
interval Time between checks 10-30s (lower = faster detection)
timeout Max wait for check response 3-5s
retries Failures before unhealthy 2-3

Lightweight Health Check

#!/bin/sh
# /usr/local/bin/php-fpm-healthcheck
# Fast check: just verify PHP-FPM responds

# Option 1: TCP check (fastest, ~1ms)
nc -z 127.0.0.1 9000 2>/dev/null || exit 1

# Option 2: FPM ping (verifies PHP works, ~5ms)
SCRIPT_NAME=/ping SCRIPT_FILENAME=/ping REQUEST_METHOD=GET \
    cgi-fcgi -bind -connect 127.0.0.1:9000 2>/dev/null | grep -q pong || exit 1

Lazy Service Initialization

Symfony Lazy Services

# config/services.yaml
services:
    App\Infrastructure\Database\HeavyConnection:
        lazy: true  # Proxy created instantly, real init on first use

    App\Infrastructure\Cache\RedisAdapter:
        lazy: true  # Don't connect to Redis until actually needed

Laravel Deferred Providers

// Defer provider registration until service is actually needed
class HeavyServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function provides(): array
    {
        return [HeavyService::class];
    }
}

Impact: Reduces container bootstrap by 100-500ms per heavy service.

Build-Time vs Runtime Init

Task Build Time Runtime Recommendation
Composer install Yes No Build only
Autoloader optimize Yes No Build only
Config cache Yes No Build only
Route cache Yes No Build only
View cache Yes No Build only
Migrations No Yes (background) Background at startup
DB connection check No Yes (background) Background at startup
Cache warmup Yes Verify only Build, verify at startup
OPcache preload No Yes (automatic) PHP-FPM handles it

Optimized Dockerfile Pattern

FROM php:8.4-fpm-alpine AS production

# Install extensions and runtime deps
RUN apk add --no-cache libzip icu-libs

COPY --from=builder /usr/local/lib/php/extensions/ /usr/local/lib/php/extensions/
COPY --from=builder /usr/local/etc/php/conf.d/ /usr/local/etc/php/conf.d/

WORKDIR /app

# Copy vendor (pre-built)
COPY --from=deps /app/vendor ./vendor

# Copy source
COPY . .

# BUILD-TIME: All cacheable operations
RUN composer dump-autoload --optimize --classmap-authoritative \
    && php bin/console cache:warmup --env=prod --no-debug

# Copy optimized entrypoint
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

# Health check
COPY docker/php-fpm-healthcheck /usr/local/bin/php-fpm-healthcheck
RUN chmod +x /usr/local/bin/php-fpm-healthcheck

HEALTHCHECK --interval=10s --timeout=5s --start_period=10s --retries=3 \
    CMD php-fpm-healthcheck

ENTRYPOINT ["entrypoint.sh"]
CMD ["php-fpm"]

Before/After Startup Time Comparison

Phase Before After Technique
Entrypoint script 3.0s 0.5s Parallel, background tasks
Migration check 2.0s 0s (background) Non-blocking
Cache warmup 4.0s 0.2s (verify only) Build-time warmup
OPcache preload 2.0s 2.0s Unavoidable, but worth it
PHP-FPM start 1.0s 1.0s Minimal improvement
Health check pass 2.5s 1.0s Lightweight check + start_period
Total ~15s ~5s -67%

Generation Instructions

  1. Audit current startup: Measure time from container start to first healthy response
  2. Move to build time: Config cache, route cache, autoloader optimization
  3. Optimize entrypoint: Parallelize, background non-critical tasks
  4. Configure preloading: Preload domain and framework hot-path classes
  5. Tune health checks: Set appropriate start_period and use lightweight checks
  6. Defer heavy services: Use lazy proxies for services not needed immediately
  7. Measure improvement: Compare container ready time before and after

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 Docker 容器启动时间优化的完整端到端方案
  • 覆盖 OPcache 预加载、Composer 优化、缓存预热、入口点并行化等关键技术
  • 面向 PHP 应用生产部署的高频痛点,实用价值高
触发精准95/100

亮点

  • 触发词精准描述优化 PHP 应用的 Docker 容器启动时间
  • 明确指出通过预加载、缓存和入口点优化减少初始化开销
  • 边界清晰,无歧义
结构规范90/100

待提升项

  • 文档过长 原报告严重程度:轻微

    SKILL.md 文件约 600 行,内容详尽但可能影响阅读体验

    改进建议:建议适当拆分章节或增加目录导航以提升可读性

亮点

  • Phase/步骤清晰,涵盖从分析到实施的全流程
  • 包含完整的端到端示例(Dockerfile、entrypoint、preload.php 等)
  • frontmatter 完整,结构规范
执行可靠90/100

亮点

  • 工具和命令来源明确(Docker、PHP、Composer、Symfony/Laravel 官方实践)
  • 参数正确,覆盖主要异常(如 wait-for-it 超时、缓存目录检查)
  • 不可逆操作(如迁移)置于后台非阻塞执行,降低风险
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。