How To Setup and Test Redis on Debian 10/Ubuntu 20.04

One of the most popular key-value store is Redis, it’s often as replacement of Memcached. On Laravel world, redis supported by default for caching. Redis is an open-source, the source code available on Github The data model is key-value, but many different kinds of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps.

This tutorial designed for beginner, even the if this your first Redis instalation, you should not worry because we guide you step-by-step. At the end this tutorial, we include script to interact with Redis server using PHP.

Update Ubuntu 20.04 / Debian 10

Udate apt metadata, then upgrade to latest available version

sudo apt update; sudo apt upgrade -y

Install Redis

To install redis, we’ll use apt, redis 5 already included in Debian 10 official repository.

sudo apt install redis -y

Redis Configuration

Redis configuration stored at /etc/redis/redis.conf

Securing Redis Server

To securing Redis server, set the password to login. At the bottom of /etc/redis/redis.conf add

requirepass STRONG-PASSWORD

set redis password debian
after save the changes, restart redis services

sudo systemctl restart redis

IP Binding

It’s dangerous to bind Redis to public IP without password protection and firewall in place, to able access Redis from a remote server we can bind the ip to the public IP.

bind PUBLIC-IP

To listen to IPv6, change the bind line to server IPv6

bind IPv6

Instead of binding to one IP only, we can bind Redis to multiple IP (both IPv6 and IPv4), take a look at following example

bind IPv4 IPv6

redis change ip bind

Change Port

Redis using port 6397 by default, only one port can use at any time

port 6379

open the configuration file then change these value to your desired value. Since a lot of client expected redis on port 6379, you’ll need to set port manually.

Check Redis Service

Verify Redis services by using systemctl

sudo systemctl status redis

check redis status linux

To verify the port used by redis use ss -tunlp | grep 6379
redis open port

Testing Redis

To test our installation, first, use CLI to connect to the Redis server.

redis-cli

By default redis bind to 127.0.0.1/localhost and without password protection.
atetux redis server

Testing using PHP

This step we’ll create a simple script to test connection to Redis from PHP application. We’ll insert timestamp into redis, the get the value from redis instead of PHP date() itself.

<?php
// redis.php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
 
$timestamp = date('Y-m-d H:i:s');
$getDate = $redis->get("timestamp");
 
if ($getDate) {
    echo "Cached: " . $getDate . "\n";
} else {
    echo "Not cached yet: " . $timestamp . "\n";
    $redis->set("timestamp", $timestamp);
}

our script similiar to connecting PHP to memcached

Leave a Comment