Docker 安装 PHP

PHP + Apache 镜像、PHP-FPM + Nginx 组合,以及扩展怎么装。

Beginner
Key Points图省事用 php:8.3-apache;要性能就用 php:8.3-fpm 配 Nginx。扩展用 docker-php-ext-install 装。

最快跑起来

Bash
docker run -d --name php -p 8080:80 \
  -v "$PWD:/var/www/html" \
  php:8.3-apache

装扩展

Dockerfile
FROM php:8.3-fpm

RUN apt-get update && apt-get install -y --no-install-recommends \
      libpng-dev libzip-dev libonig-dev \
 && docker-php-ext-install -j$(nproc) pdo_mysql gd zip mbstring opcache \
 && pecl install redis && docker-php-ext-enable redis \
 && apt-get purge -y --auto-remove \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /var/www/html
CommandUse
docker-php-ext-installBuilt-in extensions (pdo_mysql, gd…)
pecl install + docker-php-ext-enablePECL extensions (redis, xdebug)
docker-php-ext-configureExtra flags before install

PHP-FPM + Nginx

YAML
services:
  php:
    build: .
    volumes:
      - ./src:/var/www/html
  nginx:
    image: nginx:1.27-alpine
    ports:
      - "8080:80"
    volumes:
      - ./src:/var/www/html:ro
      - ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
    depends_on:
      - php
NGINX
server {
    listen 80;
    root /var/www/html;
    index index.php index.html;

    location ~ \.php$ {
        fastcgi_pass php:9000;          # 服务名:9000
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
Point fastcgi_pass at the service name (php:9000), not 127.0.0.1 — which requires both containers on the same user-defined network.

Friends & Partners