Write down Docker-Compose file for PHP and MySQL application

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.

  1. Create a directory structure for your project:
|-- app
|   `-- index.php
|-- docker-compose.yml
`-- Dockerfile
  1. Create the PHP application file (app/index.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!";
  1. Create the Dockerfile (Dockerfile):
FROM php:7.4-apache
COPY app/ /var/www/html
  1. Create the Docker Compose file (docker-compose.yml):
version: '3'
    build: .
      - "8080:80"
      - mysql
    image: mysql:5.7
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: mydatabase
      MYSQL_USER: user
      MYSQL_PASSWORD: password
      - "3306:3306"


  • 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 the web service starts only after the mysql service has started.

  1. 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.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!