通过 Docker 容器化技术,轻松部署 PHP 运行环境(支持 PHP-FPM、Nginx/Apache、MySQL、Redis 等),实现开发、测试与生产环境的一致性。本文提供 Dockerfile 与 docker-compose.yml 配置模板,涵盖依赖安装、服务编排、多容器通信及持久化数据管理,帮助开发者快速构建高可用且可扩展的 PHP 应用环境,告别“本地正常,线上报错”的兼容性问题。适用于 Laravel、ThinkPHP 等框架项目的一键部署。
目录结构
your-project/
├── Dockerfile
├── nginx.conf
├── docker-compose.yml
├── .dockerignore
└── (其他项目文件)
Dockerfile
# 第一阶段:构建依赖
FROM php:8.2-fpm AS builder
# 安装系统依赖
RUN apt-get update && apt-get install -y git unzip libzip-dev zlib1g-dev libpng-dev libjpeg62-turbo-dev
libfreetype6-dev
libonig-dev libxml2-dev libpq-dev
# 配置并安装 GD 扩展(启用 FreeType 和 JPEG)
RUN docker-php-ext-configure gd --with-freetype
--with-jpeg
RUN docker-php-ext-install -j$(nproc) gd
zip pdo_mysql mbstring exif pcntl
# 安装 Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# 复制项目文件
COPY ./app/ /var/www/html
WORKDIR /var/www/html
# 安装生产依赖
RUN composer install --no-dev --optimize-autoloader --no-interaction
# 第二阶段:运行环境
FROM php:8.2-fpm
# 从构建阶段复制必要文件
COPY --from=builder /var/www/html /var/www/html
# 设置权限 (www-data 用户需要访问宿主机文件)
RUN chown -R www-data:www-data /var/www/html && chmod -R 775 /var/www/html/runtime && usermod -u 1000 www-data # 使容器用户ID与宿主机用户一致
docker-compose.yml
services:
php:
build:
context: .
target: builder # 锁定构建阶段
volumes:
# 仅挂载开发需要的目录(生产环境应去掉挂载)
- ./app/app:/var/www/html/app
- ./app/config:/var/www/html/config
- ./app/public:/var/www/html/public
networks:
- app-network
depends_on:
- mysql
- redis
mysql:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: 123456
MYSQL_DATABASE: db_app
MYSQL_USER: user
MYSQL_PASSWORD: 123456
volumes:
- mysql_data:/var/lib/mysql
networks:
- app-network
ports:
- "3306:3306"
nginx:
image: nginx:alpine
ports:
- "8080:80"
volumes:
# 仅挂载必要文件(生产环境应直接使用镜像内文件)
- ./nginx.conf:/etc/nginx/conf.d/default.conf
- ./app/public:/var/www/html/public
networks:
- app-network
depends_on:
- php
redis:
image: redis:alpine
command: redis-server --requirepass 123456
networks:
- app-network
ports:
- "6379:6379"
networks:
app-network:
driver: bridge
volumes:
mysql_data:
nginx.conf
server {
listen 80;
server_name api.qydev.dev;
# 重点:指向 public 目录
root /var/www/html/public;
index index.php index.html index.htm;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
location / {
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
break;
}
}
location ~ .php($|/) {
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^(.+.php)(/.+)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
location ~ /.ht {
deny all;
}
location ~* .(js|css|png|jpg|jpeg|gif|ico)$ {
expires 1y;
add_header Cache-Control "public";
}
}
.dockerignore
vendor/
.env
runtime/
*.log
进入根目录安装运行
docker-compose