PHP
PHP with Docker
Learn to set up a PHP development environment with a Dockerfile and docker-compose.
Dockerfile and php:8.3-fpm
A Dockerfile is the recipe for a Docker image: which base, which files, which command to run. Each line starts with a directive.
For PHP the official php:8.3-fpm base image is common; PHP-FPM runs out of the box. FROM picks the base, COPY copies source files in, EXPOSE 9000 declares the FastCGI port.
To generate a Dockerfile from PHP code you can write the text to disk with file_put_contents.
COPY, EXPOSE and CMD
The COPY directive copies source files into a directory inside the image. COPY . /var/www/html moves your current folder into /var/www/html in the image.
EXPOSE 9000 declares that the image listens on port 9000; this is the default FastCGI port for PHP-FPM and is reachable from outside.
In a multi-step Dockerfile each line carries one directive; blank lines and lines starting with # count as comments. CMD tells which command runs when the image starts.
Exercise Generate and write a Dockerfile
Build a Dockerfile text with PHP: lines FROM php:8.3-fpm, COPY . /var/www/html, EXPOSE 9000 and CMD ["php-fpm"]. Write it to a file named Dockerfile via file_put_contents and echo the text.
Show example solution
Build $dockerfile with single-quoted parts joined by "\n". Then call file_put_contents("Dockerfile", $dockerfile); and echo $dockerfile;.
Example solution:
<?php
// Generate Dockerfile content
$dockerfile = 'FROM php:8.3-fpm' . "\n" .
'COPY . /var/www/html' . "\n" .
'EXPOSE 9000' . "\n" .
'CMD ["php-fpm"]' . "\n";
file_put_contents("Dockerfile", $dockerfile);
echo $dockerfile;
Test yourself
-
Which Dockerfile directive picks the base image?
Show answer
FROM — Correct. The FROM directive sets the base image; it goes first.
-
Complete the FROM line
<?php
$df = ["line" => "____ php:8.3-fpm\n"];
print_r($df);
Show answer
<?php
$df = ["line" => "FROM php:8.3-fpm\n"];
print_r($df);
-
Match the Dockerfile directives
- FROM
- Picks the base image
- COPY
- Copies source files
- EXPOSE
- Declares a port
- CMD
- Start command
Next lesson: PHP-FPM configuration