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

The narration of this post was created with Bespoken plugin for Craft CMS.

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’ll expand on this starter set­up by includ­ing Redis to han­dle your cache.

Why Would You Want Redis in Your Local Dev Environment?

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

We will fol­low the instruc­tions in the DDEV Redis repo.

Install Redis into your DDEV project.

ddev get ddev/ddev-redis
ddev restart

This process cre­ates a 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

Then, mod­i­fy the config/app.php file in your Craft CMS instal­la­tion. 

See the orig­i­nal arti­cle for the full code block.

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. I have omit­ted the vari­able 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, not ddev-myproject-redis. I men­tion this because I’ve seen con­fu­sion about the host­name used 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 Running, But the Craft Queue Isn’t

If you ddev restart your Craft site should still be work­ing, but the queue may not 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.

Note: If you did­n’t set any of this up, but your queue jobs are clear­ing, 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 the Craft doc­u­men­ta­tion for more infor­ma­tion. I sug­gest set­ting this val­ue to false because hav­ing the queue run auto­mat­i­cal­ly in our dev envi­ron­ment with­out requir­ing a page reload is the goal.

We must set up some­thing sim­i­lar to a dae­mon 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, i.e., in the same direc­to­ry as your craft, composer.json, and oth­er files. Here’s the con­tent of the file.

See the orig­i­nal arti­cle for the full code block.

#!/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.

The PHP_IDE_CONFIG envi­ron­men­tal vari­able tells PHP­Storm, the code edi­tor I use, 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 must 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.

See the orig­i­nal arti­cle for the full code block.

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

What Is This File Doing?

Look­ing at the con­tents above, 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 test if my post-start hooks were work­ing. I’ve left it in this exam­ple so you can quick­ly check if it also works for you. You can use ddev ssh to go into the web con­tain­er and type ll. If you see the files list­ed, you know your hooks are work­ing.

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.

There is a prob­lem when using sudo, though. Craft does not want you to run the craft com­mand as the root user, but we need to here. Update the .env file in your project to tell Craft not to warn you about the sudo com­mand usage. (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 supe­ruser equals true.

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 Working

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

ddev redis see el eye.

ddev redis-cli

Once 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 watch 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!