Write down Docker-Compose file for PHP and MySQL application
Here's an easy example of a Docker Compose file for an app with PHP and MySQL. In this case, we use PHP as the web server and MySQL as the database.
- Create a directory structure for your project:
/myphpapp
|-- app
| `-- index.php
|-- docker-compose.yml
`-- Dockerfile
- Create the PHP application file (
app/index.php
):
<?php
$host = 'mysql';
$user = 'root';
$pass = 'password';
$db = 'mydatabase';
$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected to MySQL successfully!";
?>
- Create the Dockerfile (
Dockerfile
):
FROM php:7.4-apache
COPY app/ /var/www/html
- Create the Docker Compose file (
docker-compose.yml
):
version: '3'
services:
web:
build: .
ports:
- "8080:80"
depends_on:
- mysql
mysql:
image: mysql:5.7
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: mydatabase
MYSQL_USER: user
MYSQL_PASSWORD: password
ports:
- "3306:3306"
Explanation:
The
web
service uses the official PHP 7.4 Apache image, builds the Dockerfile in the current directory, and maps port 8080 on the host to port 80 on the container.The
mysql
service uses the official MySQL 5.7 image. It sets environment variables for the root password, database name, and user credentials.The
depends_on
attribute ensures that theweb
service starts only after themysql
service has started.
- Run the application:
Navigate to the directory containing your docker-compose.yml
file and run the following commands:
# Build and start the services
docker-compose up
# Access the PHP application at http://localhost:8080
This is a simple example to help you begin. In a real-world setting, you would probably want to protect your MySQL login details and think about more settings for both PHP and MySQL services, depending on your needs.