Docker Best Practices for PHP Applications
A comprehensive guide to containerizing PHP applications with Docker, including multi-stage builds, optimized images, and production-ready configurations.
Why Docker for PHP?
Docker brings consistency and reproducibility to PHP development. No more “it works on my machine” issues. Here’s how I set up Docker for production PHP applications.
1. Multi-stage Dockerfile
# Build stage
FROM composer:2 AS builder
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-dev --optimize-autoloader
# Production stage
FROM php:8.2-fpm-alpine
RUN docker-php-ext-install pdo_mysql opcache
COPY --from=builder /app/vendor ./vendor
COPY . .
RUN chown -R www-data:www-data /var/www/html
2. Optimized PHP Configuration
; opcache.ini
opcache.enable=1
opcache.memory_consumption=256
opcache.max_accelerated_files=20000
opcache.validate_timestamps=0
3. Docker Compose for Development
services:
app:
build: .
volumes:
- .:/var/www/html
depends_on:
- db
- redis
db:
image: mysql:8.0
environment:
MYSQL_DATABASE: app
MYSQL_ROOT_PASSWORD: secret
redis:
image: redis:alpine
4. Health Checks
Always add health checks to your containers:
healthcheck:
test: ["CMD", "php-fpm-healthcheck"]
interval: 30s
timeout: 5s
retries: 3
Key Takeaways
- Use multi-stage builds to reduce image size
- Configure OPcache for production
- Separate dev and prod configurations
- Always include health checks