在最近一次部署一個新的 PHP 容器時殖侵,我編寫了一個 dockerfile 文件浸策,其配置如下:
FROM php:8.2.23-fpm-alpine3.20
RUN apk add autoconf \
gd \
composer \
freetype-dev \
libjpeg-turbo \
libjpeg-turbo-dev \
libpng-dev \
gcc \
make \
g++ \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd \
&& docker-php-ext-install -j$(nproc) pdo_mysql
EXPOSE 9000
WORKDIR /var/www/html
在鏡像創(chuàng)建成功后娘摔,啟動了容器,這時候我去通過 composer 安裝一個項目拴驮,但是 composer 卻報錯了春瞬,提示缺少 PHP 擴展:
Your requirements could not be resolved to an installable set of packages.
Problem 1
- laravel/framework[v10.10.0, ..., v10.48.22] require ext-session * -> it is missing from your system. >Install >or enable PHP's session extension.
- Root composer.json requires laravel/framework ^10.10 -> satisfiable by laravel/framework[v10.10.0, ..., >v10.48.22].
To enable extensions, verify that they are enabled in your .ini files:
- /etc/php83/php.ini
- /etc/php83/conf.d/00_curl.ini
- /etc/php83/conf.d/00_iconv.ini
- /etc/php83/conf.d/00_mbstring.ini
- /etc/php83/conf.d/00_openssl.ini
- /etc/php83/conf.d/00_zip.ini
- /etc/php83/conf.d/01_phar.ini
You can also run php --ini in a terminal to see which files are used by PHP in CLI mode.
Alternatively, you can run Composer with --ignore-platform-req=ext-session to temporarily ignore these required extensions.
我通過 php -m 查看擴展,該有的擴展都有套啤,嘗試了很多方法宽气,不限于重新安裝 PHP 擴展、清除 composer 緩存潜沦、重新生成鏡像等萄涯,都沒有效果。在重新閱讀了報錯信息后唆鸡,發(fā)現(xiàn)了一個關(guān)于 php83 這個目錄的提示涝影,這里就很奇怪,我的鏡像是基于 php8.2 來做的争占,怎么會冒出一個 php8.3 版本的信息燃逻,最后在詢問了 GPT 之后,還是將問題聚焦在了 composer 上臂痕。首先檢查 composer 依賴的 PHP 版本伯襟,執(zhí)行命令:
composer show --platform | grep php
php 8.3.10 The PHP interpreter
php-64bit 8.3.10 The PHP interpreter, 64bit
php-ipv6 8.3.10 The PHP interpreter, with IPv6 support
到了這里突然想到了,這次的 composer 是通過 apk 直接以獨立的軟件包形式下載的握童,composer 依賴 PHP 姆怪,默認下載的 PHP 版本肯定都是最新的,這樣就造成了鏡像用到的 PHP 和 composer 依賴的 PHP 完全不是一個版本的澡绩,只需要更改 composer 的安裝方式稽揭,根據(jù)已有的 PHP 版本來下載對應(yīng)的 composer 版本。
FROM php:8.2.23-fpm-alpine3.20
RUN apk add autoconf \
gd \
freetype-dev \
libjpeg-turbo \
libjpeg-turbo-dev \
libpng-dev \
gcc \
make \
g++ \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd \
&& docker-php-ext-install -j$(nproc) pdo_mysql \
&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
EXPOSE 9000
WORKDIR /var/www/html