🦁

LaravelアプリをPHARにパッケージングしてDocker + PHP-FPMで動かす

に公開

はじめに

Laravelアプリケーションを単一のPHARファイルにパッケージングし、Docker環境で動かす方法を紹介します。

PHARを使うメリットは以下の通りです。

  • 単一ファイルで配布できる
  • PHPさえあればどこでも実行可能
  • バージョン管理が容易

ただし、LaravelをPHARで動かすには少し工夫が必要です。本記事では、実際に動く構成を一から構築していきます。

プロジェクト構成

最終的なディレクトリ構成は以下のようになります。

laravel-phar-app/
├── app/
├── bootstrap/
│   └── app.php                  # storageパス外部化
├── config/
│   └── view.php                 # viewパス外部化
├── docker/
│   └── nginx/
│       └── default.conf         # nginx設定
├── public/
│   └── index-fpm.php            # PHP-FPM用エントリーポイント
├── .dockerignore
├── .env
├── box.json                     # PHARビルド設定
├── docker-compose.yml
├── Dockerfile
└── phar-server.php              # ビルトインサーバー用エントリーポイント

環境構築

前提条件

  • PHP 8.1以上
  • Composer
  • Docker / Docker Compose

Laravelプロジェクト作成

composer create-project laravel/laravel laravel-phar-app
cd laravel-phar-app

Boxのインストール

PHARビルドにはhumbug/boxを使用します。

composer require humbug/box --dev

設定ファイルの作成

box.json

PHARビルドの設定ファイルを作成します。

box.json
{
    "main": "phar-server.php",
    "output": "laravel-app.phar",
    "directories": [
        "app",
        "bootstrap",
        "config",
        "database",
        "public",
        "resources",
        "routes",
        "vendor"
    ],
    "files": [
        "artisan",
        "phar-server.php",
        ".env",
        "composer.json"
    ],
    "compression": "GZ",
    "dump-autoload": false,
    "check-requirements": false
}

dump-autoloadとcheck-requirementsはfalseにしないとビルドエラーになります。

phar-server.php

PHPビルトインサーバー用のエントリーポイントです。

phar-server.php
<?php

define('PHAR_RUNNING', true);

$storagePath = getenv('LARAVEL_STORAGE_PATH') ?: sys_get_temp_dir() . '/laravel-phar-storage';
$_ENV['LARAVEL_STORAGE_PATH'] = $storagePath;
$_SERVER['LARAVEL_STORAGE_PATH'] = $storagePath;
putenv("LARAVEL_STORAGE_PATH={$storagePath}");

$directories = [
    $storagePath,
    $storagePath . '/app',
    $storagePath . '/app/public',
    $storagePath . '/framework',
    $storagePath . '/framework/cache',
    $storagePath . '/framework/cache/data',
    $storagePath . '/framework/sessions',
    $storagePath . '/framework/views',
    $storagePath . '/logs',
];

foreach ($directories as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
}

$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH));
if ($uri !== '/' && file_exists(__DIR__ . '/public' . $uri)) {
    return false;
}

require __DIR__ . '/public/index.php';

public/index-fpm.php

PHP-FPM用のエントリーポイントです。PHARファイルを読み込んで実行します。

public/index-fpm.php
<?php

define('PHAR_RUNNING', true);

$storagePath = getenv('LARAVEL_STORAGE_PATH') ?: '/app/storage';
$_ENV['LARAVEL_STORAGE_PATH'] = $storagePath;
$_SERVER['LARAVEL_STORAGE_PATH'] = $storagePath;
putenv("LARAVEL_STORAGE_PATH={$storagePath}");

$directories = [
    $storagePath,
    $storagePath . '/app',
    $storagePath . '/app/public',
    $storagePath . '/framework',
    $storagePath . '/framework/cache',
    $storagePath . '/framework/cache/data',
    $storagePath . '/framework/sessions',
    $storagePath . '/framework/views',
    $storagePath . '/logs',
];

foreach ($directories as $dir) {
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
}

$pharPath = dirname(__DIR__) . '/laravel-app.phar';

if (!file_exists($pharPath)) {
    http_response_code(500);
    echo "PHAR file not found: {$pharPath}";
    exit(1);
}

require 'phar://' . $pharPath . '/public/index.php';

config/view.php

Bladeビューを外部化するための設定です。

config/view.php
<?php

$resourcesPath = env('LARAVEL_RESOURCES_PATH', '/app/external/resources');

return [
    'paths' => [
        $resourcesPath . '/views',
    ],
    'compiled' => env(
        'VIEW_COMPILED_PATH',
        realpath(storage_path('framework/views')) ?: storage_path('framework/views')
    ),
];

bootstrap/app.php

storageパスを外部化できるように修正します。

bootstrap/app.php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

$app = Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        //
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        //
    })->create();

// PHAR用: storageパスを外部化
if (isset($_ENV['LARAVEL_STORAGE_PATH'])) {
    $app->useStoragePath($_ENV['LARAVEL_STORAGE_PATH']);
}

return $app;

.env

ファイルベースのドライバを使用します。

.env
DB_CONNECTION=sqlite
DB_DATABASE=:memory:

SESSION_DRIVER=file
CACHE_STORE=file
QUEUE_CONNECTION=sync

Docker環境の構築

Dockerfile

マルチステージビルドでPHARを作成し、PHP-FPMで実行します。

Dockerfile
FROM php:8.3-fpm-alpine AS builder

RUN apk add --no-cache zlib libzip-dev \
    && docker-php-ext-install pdo_mysql zip opcache

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

WORKDIR /app
COPY . /app/

RUN mkdir -p /app/storage/app/public \
    /app/storage/framework/cache/data \
    /app/storage/framework/sessions \
    /app/storage/framework/views \
    /app/storage/logs \
    && chmod -R 777 /app/storage

RUN if [ ! -d "vendor" ]; then composer install --no-dev --optimize-autoloader; fi

ENV LARAVEL_STORAGE_PATH=/app/storage
ENV LARAVEL_RESOURCES_PATH=/app/external/resources

RUN php artisan config:clear \
    && php artisan route:clear \
    && php artisan view:clear \
    && php artisan config:cache \
    && php artisan route:cache

RUN php -d phar.readonly=0 vendor/bin/box compile

# ----- 本番イメージ -----
FROM php:8.3-fpm-alpine

RUN apk add --no-cache zlib && docker-php-ext-install opcache

WORKDIR /app

COPY --from=builder /app/laravel-app.phar /app/laravel-app.phar
COPY --from=builder /app/public/index-fpm.php /app/public/index-fpm.php
COPY --from=builder /app/resources /app/external/resources
COPY --from=builder /app/public /app/external/public

RUN mkdir -p /app/storage/app/public \
    /app/storage/framework/cache/data \
    /app/storage/framework/sessions \
    /app/storage/framework/views \
    /app/storage/logs \
    && chmod -R 777 /app/storage

ENV LARAVEL_STORAGE_PATH=/app/storage
ENV LARAVEL_RESOURCES_PATH=/app/external/resources

EXPOSE 9000
CMD ["php-fpm"]

ポイントは、Docker内でconfig:cacheとPHARビルドを行うことです。これにより、ビルド環境と実行環境でパスが一致します。

docker-compose.yml

docker-compose.yml
services:
  app:
    build: .
    container_name: laravel-phar-app
    environment:
      - LARAVEL_STORAGE_PATH=/app/storage
      - LARAVEL_RESOURCES_PATH=/app/external/resources
    volumes:
      - app_storage:/app/storage
      - public_files:/app/external/public
    networks:
      - laravel-network

  nginx:
    image: nginx:alpine
    container_name: laravel-phar-nginx
    ports:
      - "80:80"
    volumes:
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
      - public_files:/app/external/public:ro
    depends_on:
      - app
    networks:
      - laravel-network

networks:
  laravel-network:

volumes:
  app_storage:
  public_files:

docker/nginx/default.conf

docker/nginx/default.conf
server {
    listen 80;
    server_name localhost;

    root /app/external/public;
    index index.php;

    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 30d;
        try_files $uri =404;
    }

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

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_param SCRIPT_FILENAME /app/public/index-fpm.php;
        fastcgi_param SCRIPT_NAME /index.php;
        fastcgi_param REQUEST_URI $request_uri;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param CONTENT_TYPE $content_type;
        fastcgi_param CONTENT_LENGTH $content_length;
        fastcgi_param SERVER_NAME $server_name;
        fastcgi_param HTTP_HOST $http_host;
    }

    location ~ /\. {
        deny all;
    }
}

nginxはPHARを直接配信するわけではなく、PHP-FPMに処理を委譲します。PHP-FPM側でindex-fpm.phpがPHARを読み込んで実行します。

.dockerignore

.dockerignore
.git
.gitignore
.gitattributes
.env.example
tests/
node_modules/
.idea/
.vscode/
laravel-app.phar
docs/
*.md
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*

起動と動作確認

ビルド&起動

docker compose up -d --build

動作確認

curl http://localhost

Laravelのウェルカムページが表示されれば成功です。

ログ確認

docker compose logs -f

停止

docker compose down

まとめ

本記事で行ったことをまとめます。

  • humbug/boxを使ってLaravelアプリをPHARにパッケージング
  • config:cacheの絶対パス問題をDocker内ビルドで解決
  • storageとviewsを外部化して書き込み・パス問題に対応
  • PHP-FPM + nginx構成でPHARを実行

LaravelをPHARで動かすにはconfig:cacheが必須ですが、その際にパスがハードコードされてしまいます。これを回避するため、Docker内でビルドから実行まで同じパス構成で行うのがポイントです。

おわりに

PHARでLaravelを動かすのは一般的ではありませんが、単一ファイルで配布したいケースでは有用です。

参考

Discussion