Docker Compose is a tool used to manage Docker container applications and bring multiple containers together. It includes multiple services defined in a YAML file, along with their configurations. This file contains information on all the containers required by an application and how these containers will work together.
On the other hand, a Dockerfile is a file format used to build Docker containers. The Dockerfile contains step-by-step instructions to create an image. An image is a package containing the environment in which a container runs and the application code.
Below is an example docker-compose.yml file for creating a PHP application environment using Docker Compose with PHP, Apache, MySQL, and phpMyAdmin. This file includes an Apache server hosting a PHP application, a MySQL database, and a phpMyAdmin interface.
version: '3.8' services: # Apache and PHP service web: image: php:8-apache container_name: php-apache-container ports: - "8080:80" volumes: - .:/var/www/html # MySQL service mysql: image: mysql:8.0 networks: - my-network container_name: mysql-container ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: root_password MYSQL_DATABASE: your_database MYSQL_USER: your_user MYSQL_PASSWORD: your_password volumes: - ./mysql-data:/var/lib/mysql # phpMyAdmin service phpmyadmin: image: phpmyadmin/phpmyadmin networks: - my-network container_name: phpmyadmin-container ports: - "8081:80" environment: PMA_HOST: mysql MYSQL_ROOT_PASSWORD: root_password depends_on: - mysql # Define networks networks: my-network:
This file defines three services (web, mysql, and phpmyadmin). It uses depends_on
to ensure that the phpMyAdmin service starts after the MySQL service has started.
Additionally, two volumes connected to the host machine’s file system are added using volumes
. These volumes represent the folder where Apache will host the PHP code (./
) and the folder where MySQL will store its database files (./mysql-data
). This way, your data will not be lost even if the containers are stopped.
The networks
section in Docker Compose defines the networks that allow communication between containers within the application. These networks enable containers to communicate with each other and allow specific services to operate on specific networks. This is useful when you want to isolate services running in different network segments for security or performance requirements.
After completing the configurations, you can bring up the services with the following command:
docker-compose up -d
Now, you can open your browser and view your PHP application at http://localhost:8080. Access the phpMyAdmin interface at http://localhost:8081/