Install and Setup Redis as a Cache with PHP on Ubuntu 20.04

Redis is an in-memory key-value store known for its flexibility, performance, and wide language support.

To initiate the setup you need access to an Ubuntu 20.04 server that has user access with sudo privileges.

Installing and Configuring Redis

Begin by updating your local packages

sudo apt update

Then install Redis server

sudo apt install redis-server php-redis

Confirm the installation and restart the Apache web server to load the extension:

sudo systemctl restart apache2

Edit the file /etc/redis/redis.conf and add the following lines at the bottom:

sudo nano /etc/redis/redis.conf

Add these lines at the end of the file:

maxmemory 256mb
maxmemory-policy allkeys-lru

Restart Redis server:

sudo systemctl restart redis-server

After that, restart PHP FPM and Nginx.

sudo systemctl restart php7.4-fpm

If PHP FPM not been installed then install same by using (install necessary version based on your PHP version. Here I have installed for PHP 7.4)

sudo apt install php7.4-fpm

As with any newly-installed software, it’s a good idea to ensure that Redis is functioning as expected before making any further changes to its configuration. We will go over a handful of ways to check that Redis is working correctly in this step.

Start by checking that the Redis service is running:

sudo systemctl status redis

If it is running without any errors, this command will produce output similar to the following:

Output
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2023-01-06 13:24:54 UTC; 4 days ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
    Process: 349527 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS)
   Main PID: 349528 (redis-server)
      Tasks: 4 (limit: 2309)
     Memory: 27.1M
     CGroup: /system.slice/redis-server.service
             └─349528 /usr/bin/redis-server 127.0.0.1:6379

....

To test that Redis is functioning correctly, connect to the server using redis-cli, Redis’s command-line client:

redis-cli

In the prompt that follows, test connectivity with the ping command:

ping
Output
PONG