How to Install Redis on Debian Linux

Redis is an open-source, in-memory data structure store that serves as a database, cache, and message broker. Whether you need to speed up your web application with session caching, implement real-time messaging with publish/subscribe patterns, or store frequently accessed data for instant retrieval, Redis provides the performance and flexibility to handle these workloads efficiently. Consequently, by the end of this guide, you will have a fully configured Redis installation with optional password authentication, memory limits for caching, and firewall rules for secure network access.

This guide covers two installation methods: Debian’s default repository for a stable, distribution-tested version, and the official Redis.io repository for the latest features. Importantly, both approaches work on Debian 11 Bullseye, Debian 12 Bookworm, and Debian 13 Trixie.

Update System and Install Prerequisites

Update Debian System Packages

Before installing Redis or any other software, the initial step is to ensure your system’s packages are up-to-date. Additionally, this critical preliminary step helps mitigate potential conflicts during the subsequent installation process. Furthermore, it ensures that all system dependencies are current, minimizing potential issues arising from outdated software packages.

In a Debian system, you can do this by running the following command in the terminal:

sudo apt update && sudo apt upgrade

Install Prerequisites

Next, install the packages required for adding the Redis.io repository. Specifically, these provide SSL certificate validation, file downloading, GPG key handling, and release codename detection:

sudo apt install curl ca-certificates gnupg lsb-release -y

Choose Your Redis Installation Method

You can install Redis using Debian’s default repositories or the official Redis.io repository. To help you decide, the following table summarizes the key differences:

MethodChannelVersionUpdatesBest For
Debian RepositoryDebian PackagesDistribution defaultAutomatic via apt upgradeUsers who prefer stable, distribution-tested packages
Redis.io RepositoryOfficial RedisLatest stableAutomatic via apt upgradeUsers who need the latest features and security patches

For most users, the Redis.io repository is recommended because it provides the latest stable releases with up-to-date security patches. On the other hand, the Debian default packages are suitable for environments where distribution-level stability testing is a priority.

Redis versions vary across Debian releases: Debian 11 includes Redis 6.0.x, Debian 12 includes Redis 7.0.x, and Debian 13 includes Redis 8.0.x. The Redis.io repository provides Redis 7.4.x on Debian 11 and Redis 8.4.x on Debian 12/13, giving you access to newer features than the default packages.

Option 1: Install Redis from Debian Repository

The Debian default repository provides a stable, distribution-tested version of Redis. Moreover, this method requires no additional repository configuration and receives security updates through standard system upgrades.

To begin, install Redis using the default repository:

sudo apt install redis-server

After installation, verify the package source and version:

apt-cache policy redis-server
redis-server:
  Installed: 5:x.x.x
  Candidate: 5:x.x.x
  Version table:
 *** 5:x.x.x 500
        500 http://deb.debian.org/debian [your-release]/main amd64 Packages

Next, enable and start the Redis service:

sudo systemctl enable redis-server --now

Option 2: Install Redis from Redis.io Repository

The Redis.io repository provides the latest stable releases directly from the Redis project. As a result, this method gives you access to new features and security patches as soon as they are released.

Import the GPG Key

First, download and store the GPG key used to verify package authenticity:

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

Add the Repository

Next, create the repository configuration using the modern DEB822 .sources format:

cat <<EOF | sudo tee /etc/apt/sources.list.d/redis.sources
Types: deb
URIs: https://packages.redis.io/deb
Suites: $(lsb_release -cs)
Components: main
Architectures: $(dpkg --print-architecture)
Signed-By: /usr/share/keyrings/redis-archive-keyring.gpg
EOF

Debian 13 defaults to DEB822 .sources for APT entries. Debian 12 and Debian 11 fully support .sources, though legacy .list files remain common on older installations.

Update Package Index and Install Redis

After adding the repository, refresh the package index and install Redis:

sudo apt update
sudo apt install redis

The Redis.io repository provides a redis metapackage that depends on redis-server. Both package names work for installation; the service name is redis-server regardless of which package you install.

Verify the Installation Source

Confirm that Redis was installed from the Redis.io repository rather than the Debian default:

apt-cache policy redis
redis:
  Installed: 6:x.x.x-1rl1~[your-release]1
  Candidate: 6:x.x.x-1rl1~[your-release]1
  Version table:
 *** 6:x.x.x-1rl1~[your-release]1 500
        500 https://packages.redis.io/deb [your-release]/main amd64 Packages

The output confirms installation from packages.redis.io. Next, enable the Redis service to start automatically at boot:

sudo systemctl enable redis-server --now

Finally, verify that Redis is running:

systemctl status redis-server
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; preset: enabled)
     Active: active (running)
   Main PID: 1234 (redis-server)
      Tasks: 5 (limit: 4644)
     Memory: 7.2M
        CPU: 123ms
     CGroup: /system.slice/redis-server.service
             └─1234 /usr/bin/redis-server 127.0.0.1:6379

Additionally, confirm the installed Redis version:

redis-server --version
Redis server v=8.x.x sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=...

Test the Redis Connection

Check Listening Ports

By default, Redis listens on localhost port 6379. To confirm this, verify that Redis is actively listening:

ss -tlnp | grep redis
LISTEN 0      511        127.0.0.1:6379       0.0.0.0:*    users:(("redis-server",pid=1234,fd=6))

Ping the Redis Server

The simplest way to verify Redis is responding to commands is with a ping test. To do this, connect to Redis using the command-line interface:

redis-cli

Once connected, send a ping command:

ping
PONG

The PONG response confirms Redis is running and accepting connections. When finished, exit the Redis CLI:

exit

Configure Redis

Redis provides flexible configuration options for caching, network access, and authentication. The following sections cover the most common settings.

Open the Configuration File

Redis stores its configuration in /etc/redis/redis.conf. To begin editing, open this file with a text editor:

sudo nano /etc/redis/redis.conf

Set Memory Limits for Caching

When using Redis as a cache, set a memory limit to prevent unbounded growth. To do this, add or modify these directives in the configuration file:

maxmemory 500mb
maxmemory-policy allkeys-lru

This example allocates 500 MB of memory for Redis. Adjust this value based on your server’s specifications and your application’s requirements.

Subsequently, once the assigned memory reaches capacity, Redis will remove keys following the Least Recently Used (LRU) policy.

Configure Network Binding

By default, Redis listens only on the localhost interface. However, you can modify the bind directive to allow connections from other addresses.

Option 1: Bind to All Interfaces

To allow Redis to listen on all network interfaces, simply modify the bind directive:

bind 0.0.0.0

Binding Redis to all interfaces exposes it to network access. Therefore, always enable password authentication before making Redis accessible from other hosts.

Option 2: Bind to a Specific IP Address

To bind Redis to a specific IP address, simply specify the address directly:

bind 192.168.1.100

Alternatively, you can also bind to multiple addresses by listing them:

bind 127.0.0.1 192.168.1.100

Enable Password Authentication

For added security, require password authentication for Redis connections. To do this, locate the requirepass directive, uncomment it by removing the leading #, and set a strong password:

requirepass YourStrongPasswordHere

Replace YourStrongPasswordHere with a strong password that includes a mix of uppercase and lowercase letters, numbers, and special symbols.

Apply Configuration Changes

After making changes, save the file (Ctrl + O) and exit nano (Ctrl + X). Next, restart Redis to apply the new settings:

sudo systemctl restart redis-server

Finally, verify that Redis restarted successfully:

sudo systemctl status redis-server

Configure a Firewall for Redis with UFW

If Redis needs to accept connections from other hosts, you should configure UFW (Uncomplicated Firewall) to control which IP addresses can access the Redis port.

Install UFW

If UFW is not already installed, add it with APT. Additionally, for detailed configuration options, see the UFW installation guide for Debian.

sudo apt install ufw -y

Enable UFW with SSH Access

First, before enabling UFW, allow SSH connections to prevent being locked out of your server:

sudo ufw allow OpenSSH

If you are managing a remote server via SSH, always run sudo ufw allow OpenSSH before sudo ufw enable. Enabling UFW without allowing SSH first will disconnect your session and lock you out.

With SSH access secured, enable the firewall:

sudo ufw enable

Add Redis Firewall Rules

Configure UFW to allow Redis connections only from trusted sources. Specifically, the following examples show common configurations.

Allow a Single IP Address

For instance, to allow Redis connections from a specific server (for example, your application server at 192.168.1.50):

sudo ufw allow proto tcp from 192.168.1.50 to any port 6379

Allow a Subnet

Alternatively, for a cluster where multiple servers need Redis access, allow an entire subnet (for example, 192.168.1.0/24):

sudo ufw allow proto tcp from 192.168.1.0/24 to any port 6379

Allowing subnet access trusts all devices on that network. Therefore, only use this option on secured internal networks.

Verify Firewall Rules

After adding rules, verify the UFW configuration:

sudo ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] OpenSSH                    ALLOW IN    Anywhere
[ 2] 6379/tcp                   ALLOW IN    192.168.1.50

Next, test Redis connectivity from an allowed host:

redis-cli -h 192.168.1.100 ping
PONG

As expected, a PONG response confirms that the firewall rules are working and Redis is accepting connections.

Additional Configuration Options

Redis provides additional configuration options for performance tuning and monitoring. In particular, the following examples cover common settings.

Configure Key Eviction Policy

When Redis reaches its memory limit, the maxmemory-policy setting controls how keys are evicted. Additionally, the maxmemory-samples setting determines how many keys Redis samples when making eviction decisions. To configure these settings, open the configuration file:

sudo nano /etc/redis/redis.conf

Look for the maxmemory-policy setting and configure it to your liking. For instance, if you wish to establish a policy that expires keys according to the Least Recently Used (LRU) algorithm, then update the configuration as such:

maxmemory-policy volatile-lru

Next, locate the maxmemory-samples setting. Importantly, this will dictate the number of samples that Redis should review to arrive at the eviction decision:

maxmemory-samples 5

Enable TCP Keepalive

Activating TCP keepalive can aid in detecting and closing idle connections, which in turn releases valuable system resources. To enable it, locate 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. However, you should adjust this figure according to your server’s requirements and conditions.

Configure Slow Log Monitoring

Slow logs provide a valuable mechanism for pinpointing performance issues. Specifically, they do so by logging queries that exceed a specified duration. 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

The above example sets the slowlog threshold to 10,000 microseconds (equivalent to 10 milliseconds). Additionally, the slow log will maintain the 128 most recent entries. However, you should adjust these values to match your specific requirements and conditions.

Enable Event Notifications

Redis can create notifications for specific events, providing a powerful tool for monitoring and debugging. To activate event notifications, locate the notify-keyspace-events setting in the /etc/redis/redis.conf file:

notify-keyspace-events ExA

Here, we configure Redis to dispatch notifications for expired and evicted keys. For more information, the official Redis documentation is a comprehensive resource on event notifications and available choices.

Adjust the Logging Level

To better troubleshoot and monitor Redis, change its logging level. Specifically, you can do this in the /etc/redis/redis.conf file by adjusting the loglevel setting:

loglevel notice

The default logging level is set to ‘notice’. Other available options include ‘debug’, ‘verbose’, and ‘warning’. Choose the level that best suits your monitoring needs.

Apply Configuration Changes

After modifying any of the above settings, save the configuration file and restart Redis to apply the changes:

sudo systemctl restart redis-server

Next, verify that Redis restarted successfully and is running with the updated configuration:

systemctl status redis-server
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; preset: enabled)
     Active: active (running)

Troubleshoot Common Redis Issues

Despite careful configuration, issues can arise. Therefore, this section covers common Redis problems and their solutions.

Redis Service Fails to Start After Config Changes

If Redis fails to start after editing the configuration file, the most common cause is a syntax error. To diagnose this, check the Redis logs for details:

sudo journalctl -u redis-server --no-pager -n 20

Look for lines containing “Fatal” or “Error” in the log output. Typically, common issues include invalid directive names, missing quotation marks around values with spaces, or incorrect memory size formats.

Once identified, fix any reported errors in the configuration file, and then restart Redis:

sudo systemctl restart redis-server
systemctl status redis-server

Connection Refused from Remote Hosts

If remote clients receive “Connection refused” errors, check the bind address. By default, Redis only listens on localhost (127.0.0.1). Therefore, to verify the current bind setting:

grep "^bind" /etc/redis/redis.conf

To allow remote connections, update the bind directive to include the server’s IP address or 0.0.0.0 for all interfaces. Importantly, remember to enable password authentication before exposing Redis to the network, and then add appropriate UFW firewall rules as shown earlier in this guide.

Authentication Errors After Enabling Password

If you receive NOAUTH Authentication required errors after enabling password authentication, simply connect to Redis with the password:

redis-cli -a YourPasswordHere

Alternatively, you can authenticate after connecting:

redis-cli
AUTH YourPasswordHere
OK

Remove Redis from Debian

If you no longer need Redis, you can remove it completely from your system. First, stop the Redis service:

sudo systemctl stop redis-server
sudo systemctl disable redis-server

Next, remove Redis and its associated packages:

sudo apt remove --purge redis redis-server redis-tools -y
sudo apt autoremove -y

Additionally, if you installed Redis from the Redis.io repository, remove the repository configuration and GPG key:

sudo rm /etc/apt/sources.list.d/redis.sources
sudo rm /usr/share/keyrings/redis-archive-keyring.gpg
sudo apt update

Warning: The following command permanently deletes the Redis data directory (/var/lib/redis), log directory (/var/log/redis), and configuration directory (/etc/redis). This removes all cached values, database dumps, and custom configurations. Export any important data before proceeding.

sudo rm -rf /var/lib/redis /var/log/redis /etc/redis

Finally, verify that Redis has been removed:

apt-cache policy redis-server
redis-server:
  Installed: (none)
  Candidate: x.x.x
  Version table:

The Installed: (none) status confirms Redis has been removed. However, the Candidate version may still appear if the Debian default repository is still configured.

Conclusion

You now have Redis installed and configured on Debian, with options for memory limits, password authentication, network binding, and firewall rules. Moving forward, for production environments, consider setting up SSH on Debian for secure remote management, and explore integrating Redis with web servers like Nginx on Debian or application stacks using PHP on Debian. Furthermore, for additional caching options, see the Memcached guide for Debian.

Leave a Comment