SuperGeekery: A blog probably of interest only to nerds by John F Morton.

A blog prob­a­bly of inter­est only to nerds by John F Mor­ton.

Set Up Redis Caching in Craft CMS with DDEV: A Step-by-Step Guide

Start­ing a Craft CMS project is easy if you fol­low the Quick Start Guide in the doc­u­men­ta­tion. You’ll quick­ly be up and run­ning with a basic serv­er set­up for local devel­op­ment with DDEV.

In this post, I’m going to expand on this starter set­up by includ­ing Redis to han­dle your cache.

Why Would You Want Redis in Your Local Dev Envi­ron­ment? #

Redis does caching in mem­o­ry and reduces the load on your data­base. While this might not sig­nif­i­cant­ly impact your local devel­op­ment, I pre­fer my local devel­op­ment envi­ron­ment to mir­ror my pro­duc­tion envi­ron­ment as close­ly as pos­si­ble. You too? Keep read­ing.

Installing Redis in DDEV #

Take a look at the GitHub repo for Redis in DDEV: https://​github​.com/​d​d​e​v​/​d​d​e​v​— redis. We’re going to fol­low these instruc­tions. 

Install Redis into your DDEV project:

  1. ddev get ddev/ddev-redis
  2. ddev restart

This will cre­ate a new file in your .ddev direc­to­ry called docker-compose.redis.yaml. You don’t need to alter it.

Installing Redis in your Craft project #

You also need to install Redis in your Craft project. 

ddev composer require yiisoft/yii2-redis

Next, you need to mod­i­fy a file in your Craft CMS instal­la­tion. Look for config/app.php. I’ve added Redis like this:

use craft\helpers\App;

return [
    'id' => App::env('CRAFT_APP_ID') ?: 'CraftCMS',
    'components' => [
        'cache' => static function() {
            $config = [
                'class' => yii\redis\Cache::class,
                'keyPrefix' => Craft::$app->id,
                'defaultDuration' => Craft::$app->config->general->cacheDuration,

                // Full Redis connection details:
                'redis' => [
                    'hostname' => App::env('REDIS_HOSTNAME') ?: 'localhost',
                    'port' => App::env('REDIS_PORT') ?: 6379,
                    'password' => App::env('REDIS_PASSWORD') ?: null,
                ],
            ];
            return Craft::createObject($config);
        },
    ],
];

You’ll also need to update your .env vari­ables. Note that I leave out REDIS_PASSWORD because my local Redis does not need a pass­word.

# Redis settings
REDIS_HOSTNAME=redis
REDIS_PORT=6379

Note that the host­name is redis and not ddev-myproject-redis. I men­tion this specif­i­cal­ly because I’ve seen some con­fu­sion about the host­name to use in your envi­ron­men­tal vari­ables. The con­tain­er name is ddev-myproject-redis, but the net­work name inside the DDEV Dock­er con­fig­u­ra­tion is redis.

Redis is Run­ning, But the Craft Queue Isn’t #

If you ddev restart at this point, your Craft site should still be work­ing, but the queue won’t run jobs auto­mat­i­cal­ly as you might expect. This is because you haven’t set up the Craft queue to run yet. In pro­duc­tion, you’d prob­a­bly set up a dae­mon to run craft queue/listen. See Robust Queue Job Han­dling in Craft CMS for details on how to do that.

A note about how the queue works: If you see your queue jobs clear­ing at this point, it might be due to the default way Craft CMS han­dles jobs. Craft will attempt to run jobs auto­mat­i­cal­ly dur­ing a page load with­in the con­trol pan­el when the runqueueautomatically is left at the default val­ue of true. See https://​craftcms​.com/​d​o​c​s​/​5​.​x​/​r​e​f​e​r​e​n​c​e​/​c​o​n​f​i​g​/​g​e​n​e​r​a​l​.​h​t​m​l​#​r​u​n​q​u​e​u​e​a​u​t​o​m​a​t​i​cally for more infor­ma­tion. I sug­gest set­ting this to false because hav­ing the queue run auto­mat­i­cal­ly with­out requir­ing a page reload is one of the goals here.

We need to set up some­thing sim­i­lar on our DDEV site to run when­ev­er we start the project. We can do that with a sim­ple bash script.

Cre­ate a new file called start_craft_queue.sh. This should live at the base of your Craft instal­la­tion, in the same direc­to­ry as your craft, composer.json, and oth­er files. Here’s the con­tent of the file:

#!/bin/bash

# Set the PHP_IDE_CONFIG environment variable to tell PHPStorm to use the correct server name
# This is necessary for debugging to work correctly
export PHP_IDE_CONFIG="serverName=craft"

# Start the Craft queue listener
php craft queue/listen &> ./storage/logs/ddev-craft-queue.log &

This script starts the queue and cre­ates a log file in the stor­age direc­to­ry where Craft keeps its oth­er log files.

There is a PHP_IDE_CONFIG envi­ron­men­tal vari­able which was added after this post was ini­tial­ly pub­lished. This tells PHP­Storm where to find the craft exe­cutable file. With­out this line, you may see errors while debug­ging with xde­bug in PHP­Storm when a new job is added to the queue.

Next this script file needs to be exe­cut­ed when you start your DDEV project. We’ll do that using hooks. Open your .ddev/config.yaml and add the fol­low­ing:

hooks:
    post-start:
    - exec: sudo echo alias ll=\"ls -lhA\" >> ~/.bashrc
    - exec: sudo chmod +x /var/www/html/start_craft_queue.sh
    - exec: sudo bash /var/www/html/start_craft_queue.sh

If you already have a hooks sec­tion, just add the post-start com­mands instead.

What Is This File Doing? #

If you looked at the con­tents above close­ly, you’ll see that it adds an alias called ll to the .bashrc file. Hav­ing the ll alias is handy in day-to-day use, but ini­tial­ly, I had it there as a sim­ple way to see if my post-start hooks were work­ing. I’ve left it in this exam­ple so that you have an easy way to test if this is work­ing for you too. You can ddev ssh into the web con­tain­er and type ll. If you see files list­ed, you know that your hooks are work­ing.

Notice that I’m run­ning the com­mands with sudo. Ini­tial­ly, I did not do this, but my script would not run as my local user. It would silent­ly fail.

Craft does not like you to run the craft com­mand as the root user, but we need to here. Update the .env in your project to allow the sudo com­mand to tell Craft not to warn you about the sudo com­mand. (Neglect­ing to set this envi­ron­men­tal vari­able is the only time I see out­put in the ddev-craft-queue.log log file.)

CRAFT_ALLOW_SUPERUSER=true

Now you can ddev restart, and your Redis queue should be run­ning auto­mat­i­cal­ly in your local envi­ron­ment.

Check to See If It’s Work­ing #

Open the Redis CLI with the fol­low­ing com­mand.

ddev redis-cli

Once you are in the con­tain­er, you can enter monitor to see what activ­i­ty is hap­pen­ing in Redis. Try nav­i­gat­ing around your Craft con­trol pan­el and keep an eye on the mon­i­tor win­dow. You should see activ­i­ty, which means your Redis set­up is work­ing as expect­ed. Good luck!