How to Install Redis on Ubuntu 24.04, 22.04 or 20.04

Redis is a powerful in-memory data structure store widely used as a database, cache, and message broker. Known for its high performance and versatility, Redis supports various data structures like strings, hashes, lists, sets, and more, making it a popular choice for applications requiring fast data access and real-time analytics.

On Ubuntu 24.04, 22.04, or 20.04, Redis can be installed using two main methods. The first method is via the Ubuntu default repository, which provides a stable version that is well-integrated with the system’s package management. Alternatively, for users who require the latest version with the most recent features and updates, Redis can be installed using the Redis APT mirror repository. This guide will walk you through both installation methods, helping you choose the best approach for your needs.

Method 1: Install Redis via APT Default Repository

Update Ubuntu Before Redis Installation

Before installing Redis, ensuring that your system’s packages are up-to-date is essential. This step helps avoid any conflicts that may arise during the installation process. To update your Ubuntu system, execute the following command:

sudo apt update && sudo apt upgrade

This command will fetch the latest package information from the repositories and upgrade any outdated packages on your system.

Install Redis via APT Command

By default, the Redis package is included in the Ubuntu repository, which you can install with the following command:

sudo apt install redis

This command will download and install the Redis package and its dependencies on your system.

Verify Redis Installation

Now that you have installed Redis, verifying the installation is crucial, as you need to check the installed version. This step ensures that Redis has been installed correctly and functions as expected.

To verify the Redis installation, execute the following command:

redis-cli --version

This command will display the Redis version installed on your system. If the output displays the Redis version, it confirms the installation succeeded.

Method 2: Install Redis via Redis.io APT PPA

Update Ubuntu Before Redis Installation with Redis.io

Before proceeding with the Redis installation, update your system’s packages to ensure compatibility and prevent conflicts:

sudo apt update && sudo apt upgrade

Install Initial Packages For Redis.io PPA

To complete the installation, you must install some prerequisite software packages. Execute the following command to install them:

sudo apt install software-properties-common apt-transport-https curl ca-certificates curl -y

These packages are required to add the Redis.io repository and securely fetch package information.

Import Redis.io APT Repository

First, import the GPG Key to authenticate the packages:

curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

Next, add the Redis.io repository to your system:

echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

Update Packages List After Redis.io PPA Import

Update your sources list to include the newly added Redis.io repository:

sudo apt update

Finalize Redis PPA Installation via Terminal Command

Now, you can install Redis from the Redis.io repository. If you have Redis already installed, this command will upgrade it:

sudo apt install redis-server redis-tools

Verifying Redis Installation

To ensure you have installed the Redis.io version, use the apt-cache policy command:

apt-cache policy redis-server

Verify that the output indicates the correct version.

Next, enable and start the Redis service:

sudo systemctl enable redis-server --now

Check the status of the Redis service and ensure it is running without errors:

systemctl status redis-server

Redis should be actively listening on localhost at the default port 6379. To confirm this, execute the following command:

ps -ef | grep redis

Example output:

redis       4171       1  0 23:35 ?        00:00:00 /usr/bin/redis-server 127.0.0.1:6379
joshua      4702    4691  0 23:36 pts/0    00:00:00 grep --color=auto redis

Test Redis Connection

To test your Redis installation, connect to the Redis service using the redis-cli command:

redis-cli

Once connected, your terminal will display 127.0.0.1:6379. Perform a ping test to ensure proper communication with the Redis service:

ping
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> 

The output should be “PONG”, indicating a successful connection. To exit the Redis instance, type:

exit

Congratulations! You have successfully installed Redis on your system and verified that it is operational. You can now proceed to configure Redis as needed.

Quick Rundown on Configuring Redis

Redis is a versatile tool that can be configured in various ways to suit different use cases. This section will guide you through configuring Redis for caching, network access, and setting a password for enhanced security.

Edit the Redis Configuration File

To start configuring Redis, open the /etc/redis/redis.conf file using the nano editor:

sudo nano /etc/redis.conf

Configure Max Memory For Redis

One of the primary reasons people use Redis is for caching purposes. To allocate a specific amount of memory for Redis caching, add the following lines at the end of the configuration file:

maxmemory 500mb 
maxmemory-policy allkeys-lru

In this example, we have dedicated 500 MB of memory to Redis. You can adjust this value based on your server’s hardware and application requirements. Once the allocated memory is exhausted, Redis will remove keys based on the Least Recently Used (LRU) algorithm.

Configure Network Access For Redis

By default, Redis only listens to the localhost interface. You can configure it to listen on all network interfaces or specific IP addresses/subnets.

First, locate line 69 in the configuration file.

Option 1: Listen on all network interfaces

To listen on all network interfaces, comment out the “bind” line by adding a # at the beginning:

# bind 127.0.0.1 ::1

Option 2: Bind to a specific IP address or subnet

To bind Redis to a specific IP address or subnet, replace the “bind” line with the desired IP or subnet:

bind 0.0.0.0/0

or

bind 192.150.5.0/24

Note: When binding Redis to an IP address or subnet, setting a password for added security is strongly recommended.

Configure Password For Redis

To further secure your Redis instance, set a password for authentication.

Find the line starting with # requirepass (around line 507), uncomment it, and set a strong password:

requirepass YourStrongPasswordHere

Replace YourStrongPasswordHere with a robust password containing a mix of uppercase letters, lowercase letters, numbers, and special symbols.

After setting a password, you will need to use the auth command with the password when connecting to Redis using redis-cli:

redis-cli
auth YourStrongPasswordHere

Users who fail to authenticate will receive an error message: (error) NOAUTH Authentication required.. Upon successful authentication, users will see an OK message.

Save Changes and Restart Redis

After making the necessary changes to the configuration file, save your changes by pressing Ctrl + O, and then exit the nano editor by pressing Ctrl + X. Finally, restart the Redis service to apply the new settings:

Configure Redis UFW Firewall Rules

When using Redis, especially if you have configured it to listen on specific IP addresses or subnets, ensuring that your firewall allows incoming connections on the TCP port 6379 is crucial. This section will discuss configuring UFW (Uncomplicated Firewall) rules to allow Redis connections.

Ensure UFW is Installed and Enabled

First, make sure UFW is installed on your system:

sudo apt install ufw -y

Next, enable UFW if it isn’t already:

sudo ufw enable

Create UFW Rules for Redis

Depending on your requirements and network setup, you may need to create rules for a single server instance or multiple instances in a cluster.

Option 1: Allow access from a specific IP address

If you need to allow access to Redis from a single server, create a UFW rule for that specific IP address:

sudo ufw allow proto tcp from <ip address> to any port 6379

Replace <ip_address> with the appropriate IP address.

Option 2: Allow access from a subnet

If you have a cluster network with multiple instances, you can create a UFW rule to allow access from an entire subnet:

sudo ufw allow proto tcp from <ip address>/24 to any port 6379

Replace <subnet> with the appropriate subnet IP address. Before using this rule, ensure your internal network is secure and trustworthy.

Test Redis Connectivity

After configuring your UFW rules, test your Redis service to ensure it is operational and accessible from the allowed IP addresses or subnets. Use the redis-cli command with the -h flag, followed by the IP address you want to connect to:

redis-cli -h  <ip address> ping

Replace <ip_address> with the appropriate IP address. If the configuration is correct, you should receive a “pong” response.

pong

Additional Redis Configuration Options

Redis is a versatile and feature-rich in-memory data structure store primarily used for caching, message brokering, and more. In this section, we’ll explore additional configuration options for Redis that can help you tailor its performance and behavior to your specific needs by modifying the Redis configuration file.

Configure Key-Value Expiration Policy For Redis

In the Redis configuration file, you can set a default time-to-live (TTL) for keys by modifying the maxmemory-policy and maxmemory-samples settings. Open the /etc/redis/redis.conf file using nano editor:

sudo nano /etc/redis/redis.conf

Find the maxmemory-policy setting and configure it as desired. For example, to set the policy to expire keys using the least recently used (LRU) algorithm, update the configuration as follows:

maxmemory-policy volatile-lru

Now find the maxmemory-samples setting and configure the number of samples Redis should check to make the eviction decision:

maxmemory-samples 5

Configure TCP Keepalive For Redis

TCP keepalive can help detect and close idle connections, freeing up resources. To enable TCP keepalive, find the tcp-keepalive setting in the /etc/redis/redis.conf file:

tcp-keepalive 300

In this example, we set the keepalive interval to 300 seconds. Adjust the value according to your requirements.

Configure Slow Log Monitoring For Redis

Slow logs can help identify performance issues by logging queries that take longer than a specified amount of time. To configure slow logs, find the slowlog-log-slower-than and slowlog-max-len settings in the /etc/redis/redis.conf file:

slowlog-log-slower-than 10000
slowlog-max-len 128

In this example, we set the slowlog threshold to 10,000 microseconds (10 milliseconds) and limit the slow log to the 128 most recent entries. Adjust these values according to your needs.

Configure Redis Event Notifications For Redis

Redis can generate notifications for specific events, which can be helpful for monitoring and debugging. To enable event notifications, find the notify-keyspace-events setting in the /etc/redis/redis.conf file:

notify-keyspace-events ExA

In this example, we configure Redis to send notifications about expired and evicted keys. The official Redis documentation provides more information about event notifications and the available options.

Configure Redis Logging Level For Redis

Adjusting the Redis logging level can help you gather the right amount of information for troubleshooting and monitoring purposes. To set the logging level, find the loglevel setting in the /etc/redis/redis.conf file:

loglevel notice

In this example, we set the logging level to “notice”, which is the default level. You can choose from the following options: debug, verbose, notice, and warning. Adjust the logging level according to your requirements.

After configuring the desired options, save your changes and restart Redis:

sudo systemctl restart redis-server

Conclusion

With Redis installed on your Ubuntu system, you gain access to a powerful tool for managing in-memory data, providing fast and efficient storage solutions for a variety of applications. Whether you opt for the stability of the Ubuntu default repository or the cutting-edge features from the Redis APT mirror repository, both methods ensure that you have a robust installation. Regularly updating your Redis setup, especially when using the APT mirror, will keep your system running smoothly with the latest features and security improvements. Enjoy the speed and flexibility that Redis brings to your Ubuntu environment.

Leave a Comment