ikasama over technology

忘れたくないことを忘れないために

CakePHP を Docker 上の Nginx + PHP-FPM + MySQL にインストールして動かす

仕事でもりもりつかっている CakePHP ですが、ようやく自宅の環境にもインストールしてみました。

github.com

ハマったところ

intl PHP 拡張がなくて CakePHP のインストールにコケる

エラーメッセージ

$ docker-compose run --rm composer create-project --prefer-dist cakephp/app .
Current working directory: '/home/ikasamak/work/docker-cake'
Installing cakephp/app (3.5.1)
  - Installing cakephp/app (3.5.1)
    Downloading: 100%

Created project in my_app_name
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - cakephp/cakephp 3.5.9 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.5.8 requires ext-intl * -> the requested PHP extension intl is missing from your system.
    - cakephp/cakephp 3.5.7 requires ext-intl * -> the requested PHP extension intl is missing from your system.
...

対策

composer, php-fpm イメージに intl PHP 拡張をインストールする

  • Dockerfile (抜粋)
RUN apk update && apk --update add icu-dev
RUN docker-php-ext-install pdo_mysql mysqli mbstring intl

注意: icu-dev パッケージがないと intl PHP 拡張のインストールに失敗するのでインストールしておく。

CakePHP インストール後にアクセスすると 404 エラーが返ってくる

原因

  • Nginx と PHP-FPM を別のコンテナで動作させている
  • Nginx の conf に try_files $uri =404; が設定されている

CakePHP のインストールガイドには Nginx の設定例が載っています。

https://book.cakephp.org/3.0/ja/installation.html#nginx

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_intercept_errors on;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

しかし、今回のように Nginx と PHP-FPM を別のコンテナで動作させている環境ではうまく動きません。 try_files $uri =404; は Nginx 上で該当のファイルが見つからなければ 404 エラーを返します。 PHP-FPM と別コンテナである Nginx 上には CakePHP のソースはないため、この設定が入っていると 404 エラーになってしまいます。

対策

  • Nginx の conf から try_files $uri =404; を消す