Kritim Yantra
Apr 13, 2025
Introduction
In this comprehensive guide, we'll create a complete PHP 8.4 and MySQL development environment using Docker. This setup includes:
php-mysql-docker/
│
├── index.php # PHP application code
├── Dockerfile # PHP/Apache container configuration
└── docker-compose.yml # Orchestration for both services
<?php
$servername = "db"; // name of the mysql container
$username = "root";
$password = "secret";
$database = "testdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully!";
Security Note: In production, always:
Our Dockerfile builds a custom PHP 8.4 + Apache image:
FROM php:8.4-apache
# Install MySQL extension
RUN docker-php-ext-install mysqli
# Copy our PHP file
COPY index.php /var/www/html/
# Recommended: Enable Apache rewrite module
RUN a2enmod rewrite
Key Components:
php:8.4-apache
(PHP 8.4 with Apache)The docker-compose.yml
defines our multi-container application:
version: '3.8'
services:
web:
build: .
ports:
- "8000:80"
volumes:
- .:/var/www/html
depends_on:
- db
db:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: secret
MYSQL_DATABASE: testdb
volumes:
- db_data:/var/lib/mysql
volumes:
db_data:
Service | Purpose | Key Configurations |
---|---|---|
web | PHP/Apache | Port mapping, volume mount, build context |
db | MySQL 8.0 | Root password, initial database, persistent volume |
Important Features:
.:/var/www/html
enables live code reloadingdb_data
volume preserves database between restartsdepends_on
ensures db starts firstBuild and start containers:
docker-compose up --build
Access the application:
Connected successfully!
Table 'products' checked/created successfully.
Dummy data inserted successfully.
Product List:
- Product A - $10.99
- Product B - $20.50
- Product C - $5.75
Management commands:
docker-compose down
docker-compose down -v
docker-compose logs -f
index.php
are immediately reflected (thanks to volume mounting)Access MySQL CLI:
docker-compose exec db mysql -u root -psecret testdb
Persistent Data:
db_data
Connection Issues:
docker-compose ps
docker-compose logs db
Permission Problems:
:z
to volume mounts:volumes:
- .:/var/www/html:z
For production deployments:
php-fpm
with Nginx for better performanceThis setup provides a perfect local development environment with:
✅ PHP 8.4 + Apache
✅ MySQL 8.0 with persistence
✅ Real-time code synchronization
✅ Automatic database initialization
To get started:
docker-compose up --build
http://localhost:8000
This approach gives you a professional-grade development environment that mirrors production while being easy to manage. Happy coding! 🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google