Redis is an open-source in-memory cache and storage system, also referred to as a data structure server. It offers advanced support for several data types, such as hashes, lists, sets, bitmaps, and many more. Because of its excellent performance, Redis finds its popularity in leading industries and top MNCs.
Benefits of Redis
When it comes to speed, there is no match to Redis servers. As a NoSQL database server, it offers a fantastic speed of storing and retrieving data. Besides, Redis has stand-out functionalities that make it seamless to work with different data, including complex ones. The ease of use and sophisticated functionalities of Redis have not only made it stand out but have allowed its increasing standardisation as a mainstream database for corporate and individual users.
Below, we will detail the steps to help you install Redis on Ubuntu 20.04 software. In this tutorial, you will get all the information you need from installing to configuring an external Redis server to be used as a session handler for a PHP application running on Ubuntu 20.04.
Getting Started
To go over the steps, you will need two different database servers (droplets) located in the same data centre with private network enabled. These include:
-
A PHP web server running LAMP and LEMP on Ubuntu 20.04 – we will refer to this server as web.
-
A second, clean Ubuntu 20.04 server where Redis will be installed – we will refer to this server as redis.
Step 1 — Redis Server Installation
Our first step is to install the Redis server on Ubuntu 20.04. Once done, make sure the server is up and running on our redis Droplet.
In this tutorial, we will use Personal Package Archives (PPAs). We highly suggest going with PPAs due to security reasons. Compared to other third-party repositories, PPAs are stable, easy to install, and above all, the repository is designed for Ubuntu users. PPA allows you to get the latest software version available, even for the software you do not find in the official Ubuntu repositories.
Using PPAs from an unauthorised source is a big no-no. Make sure you get the PPAs from authentic and verified sources only. You can add the PPA repository using the command:
1 |
sudo add-apt-repository ppa:chris-lea/redis-server |
Press the Enter key to confirm. After confirmation, we will update the package manager cache using the following command:
1 |
sudo apt-get update |
Next, we will install Redis using the command:
1 |
sudo apt-get install redis-server |
Once you execute the command, you will have Redis installed on your server. Let’s test the installation using the command:
1 |
redis-cli ping |
Once you hit the command, you will see a Redis instance running on the localhost on port 6379. Also, there will be a response named PONG. If you see these, it means you have successfully completed the first step. For a detailed guide on installing and securing Redis, you can take a look at our tutorial How to Install and Secure Redis on Ubuntu 18.04.
Next, let’s move on to the next step- configuring Redis.
Step 2 — Redis Configuration to Accept External Connections
The main goal of configuring Redis is to accept connections coming externally. Why? Because Redis – by default, allows connections only to localhost, and there is a restriction to connect from anywhere else. In simpler terms, you´ll have access from inside the server where you have installed Redis.
First, get a detailed insight on your network interfaces using the ifconfig command:
1 |
sudo ifconfig |
You will get the output below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
eth0 Link encap:Ethernet HWaddr 04:01:63:7e:a4:01 inet addr:188.166.77.33 Bcast:188.166.127.255 Mask:255.255.192.0 inet6 addr: fe80::601:63ff:fe7e:a401/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3497 errors:0 dropped:0 overruns:0 frame:0 TX packets:3554 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:4895060 (4.8 MB) TX bytes:619070 (619.0 KB) eth1 Link encap:Ethernet HWaddr 04:01:63:7e:a4:02 inet addr:10.133.14.9 Bcast:10.133.255.255 Mask:255.255.0.0 inet6 addr: fe80::601:63ff:fe7e:a402/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:8 errors:0 dropped:0 overruns:0 frame:0 TX packets:7 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:648 (648.0 B) TX bytes:578 (578.0 B) |
At the eth1 interface, you will find the inet_addr. Here we have 10.133.14.9. We will use this IP address in the upcoming steps to connect the redis server from the web server.
Step 3— Localhost Binding
You are free to use the code editor of your choice (Atom and Visual Studio Code are the most popular ones).
Now, open the file /etc/redis/redis.conf and look for the line that contains the bind definition. You should add your private network IP address to the line:
1 |
sudo vim /etc/redis/redis.conf |
1 |
bind localhost 10.133.14 |
You may see localhost, instead of 127.0.0.1. No worries, you just need to add your private IP address. Next, restart the Redis service to apply the changes. Use the command below to restart the redis server:
1 |
sudo service redis-server restart |
For those users who have installed Redis using the one-click application, you will follow the command mentioned below to restart your server:
1 |
sudo service redis restart |
Once you restart the redis server, any server present in the same private network will automatically connect to this Redis instance, without the need to do it individually.
Step 4— Redis Server Password Set Up
You can skip this step if you are using the Redis installation for practice or training purposes. However, setting up the password for the redis server is highly recommended if you want to add an extra layer of security to your Redis installation. Let us modify the same configuration file as we did in the previous step. Use the command to edit:
1 |
sudo vim /etc/redis/redis.conf |
Uncomment the line that contains requirepass, and set a strong password:
1 |
requirepass StrongPassword |
Restart the Redis service to reflect the changes you have made. Use the command to restart:
1 |
sudo service redis-server restart |
Step 5 — Redis Connection and Authentication Testing
In this step, we will connect to the Redis service from inside the redis machine to make sure all the changes made are working seamlessly as expected. To connect, use the below command:
1 |
redis-cli -h 10.133.14.9 |
Here, even if you skip to mention the hostname, it will still run. Our primary aim is to make sure the Redis service accepts the connections seamlessly:
1 |
10.133.14.9:6379> |
It is possible that you get an AUTH error when trying to access the data from the defined password:
1 |
10.133.14.9:6379> keys * |
Your output will look similar to this:
1 2 |
OUTPUT: (error) NOAUTH Authentication required. |
To authenticate, run the AUTH command along with the same password you defined in the /etc/redis/redis.conf file:
1 |
10.133.14.9:6379> AUTH StrongPassword |
Next, run the command again:
1 |
10.133.14.9:6379> keys * |
This time, you will get an OK as a response instead of an error. You will get the output as below:
1 2 |
OUTPUT: (empty list or set) |
The output empty list or set means the Redis server is empty. That’s because we have not yet configured the web server as a session handler.
Note: Before we move forward, make sure the SSH session is opened and connected to the redis-cli. In the upcoming steps, we will get back to the redis-cli prompt to verify if the session data was stored properly after we make the necessary changes to the web server.
Step 6 — Redis Extension Installation on the Web Server
The next steps should be executed on the web server. We need to install the PHP Redis extension for PHP to connect to the Redis server.
First, update your package manager cache by running the command:
1 |
sudo apt-get update |
Next, install the php5-redis package:
1 |
sudo apt-get install php5-redis |
You are all set to connect to Redis.
Step 7 — Redis Set-up as the Default Session Handler on the Web Server
PHP has a default session handler. In this step, we will edit the php.ini file on the web server to change the default settings. The php.ini file location depends on the current stack:
-
For a LAMP stack on Ubuntu 20.04, use: /etc/php5/apache2/php.ini.
-
For a LEMP stack on Ubuntu 20.04, the path is usually /etc/php5/fpm/php.ini.
If you are unsure about the location of your main php.ini file, take help of the function phpinfo(). Place the following code in a file named info.php inside your web root directory:
1 2 |
<?php phpinfo(); |
When you are trying to access the script from your browser, search for the row containing “Loaded Configuration File.”You will find the exact location of the main php.ini loaded. Make sure to remove the info.php file as it has all the sensitive content of your environment.
After that, open the php.ini file and look for the line containing session.save_handler. The default value will be files, make sure to change to redis.
On LAMP environments:
1 |
$ sudo vim /etc/php5/apache2/php.ini |
On LEMP environments:
1 |
$ sudo vim /etc/php5/fpm/php.ini |
1 |
session.save_handler = redis |
Next, uncomment the session.save_path and modify the value to contain the Redis connection string. The content must follow the format below:
1 |
tcp://IPADDRESS:PORT?auth=REDISPASSWORD |
1 |
session.save_path = "tcp://10.133.14.9:6379?auth=yourverycomplexpasswordhere" |
Use the password we have set up in Step- 4. In case, you are not using the set password, then provide the parameter auth when configuring Redis. Now, save the file and restart the php service on both environments.
On LAMP environments:
1 |
sudo service apache2 restart |
On LEMP environments:
1 |
sudo service php5-fpm restart |
Step 8 — Testing Redis Session Handling
In the final step, we need a PHP script or application to make sure your sessions are now handled by Redis. We will use a simple script that implements a counter – each time you reload the page, the printed number is incremented.
Create a file named demo.php on the web server and keep it inside your document root folder:
1 |
sudo sudo vim /usr/share/nginx/html/test.php |
Then, change the /usr/share/nginx/html to reflect your document root path:
1 2 3 4 5 6 7 |
<?php //simple counter to test sessions. should increment on each page reload. session_start(); $count = isset($_SESSION['count']) ? $_SESSION['count'] : 1; echo $count; $_SESSION['count'] = ++$count; |
Next, you have to point your browser to http://web/demo.php to access the script. The program will increment the number every time you reload the page.
Now you will have session information stored on the Redis server. To verify, you have to go back to your SSH session on the redis machine using the redis-cli. Get the content once again with keys *:
1 |
10.133.14.9:6379> keys * |
You will see the output below:
1 2 |
OUTPUT: 1) "PHPREDIS_SESSION:j9rsgtde6st2rqb6lu5u6f4h83" |
The output verifies that all the information is stored securely on the redis server. If you want to connect additional web servers, you can follow the same fashion.
Conclusion
Redis is a NoSQL database that allows the storage of numerous unstructured data. Very few databases can compare to the functionalities and simplicity of the redis server. Its increasing popularity continually makes it a must-have with few substitutes compared to its broad features.
To further deepen your knowledge of PHP applications and how to use them, you can take a look at the following tutorials from our blog:
- Deploy a PHP Application on a Kubernetes Cluster with Ubuntu 18.04
- Installing phpBB on Ubuntu 20.04
- Installing and Securing phpMyAdmin on Ubuntu 18.04
Happy Computing!
- How To Set Up GitHub Continuous Integration Pipelines With Self-Hosted Runners on Ubuntu 22.04. - March 20, 2023
- Managing CSV in Node.js using Node-CSV - March 15, 2023
- Containerize A Python App using Docker - March 7, 2023
- Using GitLab for Managing Projects - September 15, 2022
- Creating Drag and Drop Elements with Pure, Vanilla JavaScript - August 4, 2022