Using Docker Compose with PHP & Redis (2023 Code Examples)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Use Docker Compose with PHP & Redis

Setting up Docker Compose with PHP & Redis consists of creating a custom PHP app dockerfile & a docker-compose yaml file. You’ll need to integrate Redis into the PHP app & set up the necessary environment variables.

  • Docker Compose is a tool for defining and running multi-container Docker applications.
  • PHP is a widely-used server-side scripting language for web development.
  • Redis is an open-source, in-memory data structure store used as a database, cache, and message broker.

Combining these technologies allows you to streamline your development and deployment process, ultimately building more scalable and efficient web applications.

Docker Compose with PHP & Redis YAML Code Example

version: '3.8'services:
php:
image: php:7.4-apache
ports:
- "80:80"
volumes:
- ./src:/var/www/html
depends_on:
- redis redis:
image: redis:6.2-alpine
ports:
- "6379:6379"

Steps to Setup Docker with PHP & Redis

  • The php service uses the official PHP 7.4 image with Apache web server.
  • The application’s source code is mapped to the /var/www/html directory in the container.
  • The php service depends on the redis service.
  • The redis service uses the official Redis 6.2 Alpine image.
  • PHP and Redis services expose their default ports (80 for PHP and 6379 for Redis).

Article Highlights

  • The benefits of using Docker Compose for PHP and Redis applications
  • How to set up a Docker Compose environment with PHP and Redis
  • Step-by-step instructions for configuring and launching PHP and Redis containers
  • Code examples demonstrating how to use Redis with PHP
  • Best practices for using Docker Compose with PHP and Redis, including security and optimization tips

Whether you’re a web developer or a DevOps engineer, this guide will show you how to take full advantage of Docker Compose, PHP, and Redis in your projects. Let’s dive in!

how to use docker compose with PHP & Redis

Benefits of Docker Compose for PHP and Redis applications.

Using Docker Compose with PHP and Redis offers several advantages for web developers and DevOps engineers:

  • Simplifying development and deployment: Docker Compose allows you to define your entire application stack, including PHP and Redis, in a single docker-compose.yml file. This simplifies both development and deployment, as you can start or stop your entire application stack with just a few commands.
  • Ensuring consistency across environments: Docker containers ensure that your PHP and Redis environments are consistent across development, testing, and production. This helps prevent issues caused by differences in software versions or configurations.
  • Enhancing application scalability: Docker Compose simplifies scaling your PHP and Redis services, allowing you to handle increased traffic or load on your application.
  • Facilitating collaboration: By using a single docker-compose.yml, your team members can easily understand the entire application stack and collaborate on development, testing, and deployment.

Setting up a Docker Compose environment with PHP and Redis

To set up a Docker Compose environment with PHP and Redis, follow these steps:

Prerequisites: PHP, Docker, and Redis installation

Ensure that you have the following software installed on your machine:

  1. Docker: Install Docker
  2. Docker Compose: Install Docker Compose
  3. PHP (locally, for development purposes): Install PHP

Creating a Docker Compose file for PHP and Redis

  1. Create a new directory for your project: mkdir php-redis-app && cd php-redis-app
  2. Create a src Directory for your PHP application code: mkdir src
  3. Create a docker-compose.yml File in the project directory with the following content:
version: '3.8'

services:
  php:
    image: php:7.4-apache
    ports:
      - "80:80"
    volumes:
      - ./src:/var/www/html
    depends_on:
      - redis

  redis:
    image: redis:6.2-alpine
    ports:
      - "6379:6379"

Configuring PHP and Redis containers

  1. Add your PHP application code to the src directory.
  2. Optionally, you can customize the PHP and Redis container configurations by creating custom Dockerfiles or configuration files. For example, you can install additional PHP extensions, configure Apache settings, or set Redis options.

Launching the environment with Docker Compose

  1. In the project directory, run docker-compose up -d to start your PHP and Redis containers.
  2. Access your PHP application at http://localhost in your web browser.
  3. To stop the containers, run docker-compose down.

Code examples for using Redis with PHP

Now that you have an environment set up with PHP and Redis let’s explore some code examples that demonstrate how to use Redis with PHP:

Caching data with Redis

Caching is one of the most common use cases for Redis. Here’s an example of how to cache data using Redis and PHP:

  1. Install the PHP Redis extension in your PHP container by updating your Dockerfile:
FROM php:7.4-apache

# Install Redis extension
RUN pecl install redis \
  && docker-php-ext-enable redis

2. Create a new PHP file in the src directory called cache_example.php with the following content:

<?php
$redis = new Redis();
$redis->connect
('localhost', 6379);

$key = 'popular_articles';

// Check if the key exists in Redis
if ($redis->exists($key)) {
// Fetch data from Redis cache
$popularArticles = json_decode($redis->get($key), true);
echo "Data fetched from cache:<br>";
} else {
// Fetch data from the database or another source
$popularArticles = [
'Article 1',
'Article 2',
'Article 3',
];

// Cache the data in Redis for 1 hour (3600 seconds)
$redis->set($key, json_encode($popularArticles), 3600);
echo "Data fetched from the source and cached:<br>";

}

// Display the popular articles
foreach ($popularArticles as $article) {
echo $article . "<br>";
}
This example demonstrates how to use Redis to cache popular articles. The data is fetched from the source (e.g., a database) and cached in Redis if it's not already there. When the data is requested again, it's fetched from the cache instead of the source, improving performance.

### Managing sessions with Redis

Redis can also be used to manage PHP sessions. To do this, update your PHP container configuration to use Redis as the session handler:

1. Create a new PHP configuration file called `redis-session.ini` in the project directory:

```ini
session.save_handler = redis
session.save_path = "tcp://localhost:6379"
  1. Update your Dockerfile to copy the redis-session.ini file to the PHP container:
FROM php:7.4-apache

# Install Redis extension
RUN pecl install redis \
  && docker-php-ext-enable redis

# Configure Redis as the session handler
COPY redis-session.ini /usr/local/etc/php/conf.d/
  1. Create a new PHP file in the src directory called session_example.php with the following content:
<?php
session_start();

// Increment the counter
$_SESSION['counter'] = isset($_SESSION['counter']) ? $_SESSION['counter'] + 1 : 1;

echo "You have visited this page " . $_SESSION['counter'] . " times.";

This example demonstrates how to use Redis to store session data. The counter value is stored in the session and incremented every time the page is visited.

Implementing a message queue with Redis

Redis can be used to implement a message queue for the asynchronous processing of tasks. Here’s an example of a simple message queue using Redis and PHP:

  1. Create two new PHP files in the src directory called producer.php and consumer.php.
  2. In producer.php, add the following content:
<?php
$redis = new Redis();
$redis->connect('localhost', 6379);

// Add a message to the queue
$message = 'Hello, Redis!';
$redis->rPush('message_queue', $message);

echo "Message added to the queue: " . $message;
  1. In consumer.php, add the following content:
<?php
$redis = new Redis();
$redis->connect('localhost', 6379);

// Process a message from the queue
$message = $redis->lPop('message_queue');

if ($message) {
    echo "Message processed from the queue: " . $message;
} else {
    echo "No messages in the queue.";
}

This example demonstrates a simple message queue implementation using Redis. The producer adds a message to the queue, and the consumer processes messages from the queue.

Other use cases

Redis can be used for a variety of other use cases in web applications, such as:

  • Rate limiting: Limit the number of requests per user or IP address within a specific time frame.
  • Leaderboards: Maintain a sorted set of users based on their scores in a game or application.
  • Real-time analytics: Track and analyze user behavior, clicks, and other real-time events.
  • Pub/Sub messaging: Implement a publish/subscribe messaging pattern for real-time service communication.

Best practices for using Docker Compose with PHP and Redis

To ensure that your applications run smoothly with Docker Compose, follow these best practices:

Security tips

  • Avoid using default Redis and PHP container configurations in production environments. Always customize configurations to meet your application’s security requirements.
  • Use strong passwords for Redis authentication and consider using TLS for encrypted communication between your PHP application and Redis.
  • Keep your Docker images and software up to date, and apply security patches as needed.

Performance optimization

  • Monitor the resource usage of your PHP and Redis containers to ensure that they have adequate resources (CPU, memory, and storage) to handle the application workload.
  • Use Redis data structures efficiently to optimize memory usage and minimize the impact on performance.
  • Consider using Redis clustering for improved scalability and performance.

Container maintenance and updates

  • Regularly update your PHP and Redis containers to use the latest stable software versions.
  • Perform regular backups of your Redis data and test your backup and restore procedures.
  • Use rolling updates or blue-green deployment strategies to minimize downtime during updates.

Managing application logs

  • Configure PHP and Redis to output logs to Docker’s logging system, so you can easily view and manage logs using Docker’s built-in logging commands.
  • Consider using centralized log management solutions to aggregate logs from multiple containers and simplify log analysis.

Setting Up Docker Compose with PHP & Redis

Docker Compose with PHP and Redis can simplify your development and deployment processes while building scalable and reliable web applications. With this article’s examples and best practices, you can now integrate these technologies into your projects.

For further learning and exploration, check out the following resources:

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.