Welcome to Dockerize It! In today's article, we'll dive deep into mastering Docker Compose for PHP microservices. Microservices architecture is becoming increasingly popular, allowing developers to build scalable and maintainable applications. Docker and Docker Compose are essential tools for managing microservices, providing an efficient way to deploy and orchestrate multiple containers.
Microservices architecture involves splitting an application into small, independent services that communicate over APIs. Each microservice is responsible for a specific functionality and can be developed, deployed, and scaled independently.
Docker containers are perfect for microservices because they provide isolated environments for each service. Docker Compose simplifies the management of multiple containers by allowing you to define and run multi-container applications with a single command.
Let's create a sample PHP microservices project consisting of three services:
microservices-project/
├── api/
│ ├── Dockerfile
│ └── index.php
├── auth/
│ ├── Dockerfile
│ └── index.php
├── docker-compose.yml
# api/Dockerfile
FROM php:8.0-apache
COPY . /var/www/html
EXPOSE 80
# auth/Dockerfile
FROM php:8.0-apache
COPY . /var/www/html
EXPOSE 80
Create the docker-compose.yml
file in the root of your project:
version: '3.8'
services:
api:
build:
context: ./api
dockerfile: Dockerfile
container_name: api_service
ports:
- "8081:80"
networks:
- app-network
depends_on:
- auth
- db
auth:
build:
context: ./auth
dockerfile: Dockerfile
container_name: auth_service
ports:
- "8082:80"
networks:
- app-network
db:
image: mysql:5.7
container_name: db_service
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: microservices_db
MYSQL_USER: user
MYSQL_PASSWORD: password
volumes:
- db_data:/var/lib/mysql
networks:
- app-network
networks:
app-network:
driver: bridge
volumes:
db_data:
api
directory, exposes port 8081
.auth
directory, exposes port 8082
.app-network
.db_data
to persist database data.Create api/index.php
:
<?php
echo "Welcome to the API Service";
?>
Create auth/index.php
:
<?php
echo "Welcome to the Auth Service";
?>
Start all services with:
docker-compose up -d --build
This command builds and runs all the containers in detached mode.
Visit the services in your browser:
Since the services are on the same Docker network, they can communicate using their service names. For example, the API service can make HTTP requests to the Auth service using http://auth:80
.
One of the advantages of using Docker Compose is the ability to scale services. To scale the API service to 3 instances, run:
docker-compose up -d --scale api=3
Note: You might need to set up a load balancer to distribute traffic between multiple instances.
Docker Compose is a powerful tool for orchestrating multi-container applications, especially in a microservices architecture. By mastering Docker Compose, you can efficiently manage your PHP microservices, making your applications more scalable and maintainable.