15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
31.10.2024
1 +1

How to Install and Configure Redis on Linux: A Complete Step-by-Step Guide

Redis is a powerful, open-source, in-memory data structure store widely used as a database, cache, and message broker. Renowned for its exceptional performance and versatility, Redis is a go-to solution for developers looking to dramatically speed up applications by caching frequently requested data, managing sessions, and handling real-time analytics. Whether you're running a high-traffic web application on a VPS Hosting plan or managing a dedicated infrastructure, this comprehensive guide walks you through every step of installing, configuring, and securing Redis on a Linux system.

What Is Redis and Why Should You Use It?

Before diving into the installation process, it's worth understanding what makes Redis so popular:

  • In-memory storage: Redis stores data in RAM, making read and write operations extremely fast — often completing in under a millisecond.
  • Versatile data structures: Supports strings, hashes, lists, sets, sorted sets, bitmaps, and more.
  • Persistence options: Despite being in-memory, Redis can persist data to disk to survive restarts.
  • Pub/Sub messaging: Redis supports publish/subscribe messaging patterns for real-time communication between services.
  • Wide language support: Official client libraries exist for Python, PHP, Node.js, Java, Ruby, Go, and many more.

Redis is especially valuable in environments where application performance is critical — for example, when your backend is hosted on a Dedicated Server serving millions of requests per day.

Prerequisites

Before you begin, make sure you have:

  • A Linux server running Ubuntu/Debian or CentOS/RHEL
  • Root or sudo access to the server
  • A basic understanding of the Linux command line
  • An active internet connection for downloading packages

Step 1: Update Your System

Always start by updating your system's package index and upgrading installed packages to their latest versions. This ensures compatibility and security:

sudo apt update && sudo apt upgrade -y

For CentOS/RHEL systems:

sudo yum update -y

Keeping your server up to date is a fundamental security practice, especially on production environments.

Step 2: Install Redis

Most major Linux distributions include Redis in their official package repositories, making installation straightforward.

On Ubuntu / Debian

sudo apt install redis-server -y

On CentOS / RHEL

CentOS/RHEL systems require the EPEL (Extra Packages for Enterprise Linux) repository to be enabled first:

sudo yum install epel-release -y
sudo yum install redis -y

> Note: On newer versions of CentOS/RHEL (8+), you can use dnf instead of yum:

> “`bash

> sudo dnf install redis -y

> “`

Step 3: Verify the Installation

Once the installation completes, confirm that Redis was installed correctly by checking its version:

redis-server --version

Expected output (example):

Redis server v=7.0.12 sha=00000000:0 malloc=jemalloc-5.3.0 bits=64 build=...

If you see a version number, Redis has been successfully installed on your system.

Step 4: Start and Enable the Redis Service

After installation, you need to start the Redis service and configure it to launch automatically on system boot.

On Ubuntu / Debian

sudo systemctl start redis
sudo systemctl enable redis

On CentOS / RHEL

sudo systemctl start redis
sudo systemctl enable redis

Verify Redis Is Running

sudo systemctl status redis

Expected output:

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

A green active (running) status confirms that Redis is operating correctly.

Step 5: Configure Redis

Redis's behavior is controlled by its main configuration file:

  • Ubuntu/Debian: /etc/redis/redis.conf
  • CentOS/RHEL: /etc/redis.conf

Open the configuration file with a text editor:

sudo nano /etc/redis/redis.conf

Below are the most important configuration options you should review and adjust.

5.1 Set a Password (Authentication)

By default, Redis does not require authentication. For any production environment, setting a strong password is essential:

Find the line containing # requirepass and update it:

requirepass your_strong_password_here

Choose a long, randomly generated password. Redis is extremely fast, meaning brute-force attacks can attempt hundreds of thousands of guesses per second without rate limiting.

5.2 Bind IP Address

By default, Redis binds only to 127.0.0.1 (localhost), which prevents external access. This is the safest default setting.

If your application needs to connect to Redis from another server, you can bind to an additional IP address:

bind 127.0.0.1 192.168.1.100

> Security Warning: Never bind Redis to 0.0.0.0 (all interfaces) on a public-facing server without proper firewall rules. Exposed Redis instances are a common attack vector.

5.3 Change the Default Port

Redis listens on port 6379 by default. Changing this port adds a layer of obscurity:

port 6380

Remember to update your firewall rules and application connection strings if you change the port.

5.4 Apply Configuration Changes

After editing redis.conf, restart the Redis service to apply all changes:

sudo systemctl restart redis

Step 6: Test the Redis Installation

Use the built-in Redis CLI (Command Line Interface) to verify that Redis is working correctly:

redis-cli

If you set a password, authenticate first:

AUTH your_strong_password_here

Run a Ping Test

ping

Expected response:

PONG

Set and Retrieve a Key-Value Pair

SET mykey "Hello, Redis!"
GET mykey

Expected response:

"Hello, Redis!"

If Redis returns the stored value correctly, your installation is fully functional and the database is storing and retrieving data as expected.

Exit the CLI

exit

Step 7: Configure Redis as a Background Daemon (Optional)

If you want Redis to run as a background daemon process (rather than a foreground process), configure the daemonize option in redis.conf:

daemonize yes

After saving the file, restart Redis:

sudo systemctl restart redis

Verify the service is running in the background:

sudo systemctl status redis

You can also confirm the Redis process is active using:

ps aux | grep redis

By default, Redis stores data only in memory, which means data is lost if the server restarts. Redis provides two persistence mechanisms to address this:

Option 1: RDB (Redis Database Backup) — Snapshotting

RDB creates point-in-time snapshots of your dataset at specified intervals. Configure it in redis.conf:

# Save a snapshot if at least 1 key changed in 900 seconds (15 minutes)
save 900 1

# Save a snapshot if at least 10 keys changed in 300 seconds (5 minutes)
save 300 10

# Save a snapshot if at least 10,000 keys changed in 60 seconds
save 60 10000

RDB is efficient for backups and disaster recovery but may lose data written between snapshots.

Option 2: AOF (Append Only File) — Write Logging

AOF logs every write operation to a file, providing much stronger durability guarantees:

appendonly yes

You can also configure the AOF sync policy:

# Options: always, everysec, no
appendfsync everysec
  • always — Safest, but slowest (syncs after every write)
  • everysec — Good balance of performance and safety (syncs every second)
  • no — Fastest, but relies on the OS flush schedule

> Best Practice: For production environments, use both RDB and AOF together for maximum data durability.

Step 9: Securing Redis — Best Practices

Security is critical for any Redis deployment. Follow these best practices to harden your Redis instance:

1. Enable Password Authentication

As described in Step 5.1, always set a strong requirepass value in redis.conf.

2. Restrict Network Access

  • Bind Redis to 127.0.0.1 unless remote access is explicitly required.
  • Use a private network or VPN for inter-server Redis communication.

3. Configure Firewall Rules

Allow Redis traffic only from trusted IP addresses. Using ufw on Ubuntu:

sudo ufw allow from 192.168.1.0/24 to any port 6379
sudo ufw deny 6379

Using firewalld on CentOS/RHEL:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" port protocol="tcp" port="6379" accept'
sudo firewall-cmd --reload

4. Rename or Disable Dangerous Commands

Redis has powerful administrative commands (like FLUSHALL, CONFIG, DEBUG) that could be exploited. Rename or disable them in redis.conf:

rename-command FLUSHALL ""
rename-command CONFIG "SECURE_CONFIG_XYZ123"
rename-command DEBUG ""

5. Run Redis as a Non-Root User

The Redis package on most distributions already creates a dedicated redis system user. Ensure Redis is never run as root.

6. Keep Redis Updated

Regularly update Redis to patch known vulnerabilities:

sudo apt update && sudo apt upgrade redis-server -y

Step 10: Integrating Redis with Your Applications

With Redis installed and secured, you can now integrate it into your application stack. Here's a quick overview of popular language integrations:

Python — redis-py

pip install redis
import redis

r = redis.Redis(host='127.0.0.1', port=6379, password='your_password', decode_responses=True)
r.set('greeting', 'Hello from Python!')
print(r.get('greeting'))

PHP — phpredis Extension

sudo apt install php-redis -y
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('your_password');
$redis->set('greeting', 'Hello from PHP!');
echo $redis->get('greeting');
?>

Node.js — ioredis

npm install ioredis
const Redis = require('ioredis');
const redis = new Redis({ host: '127.0.0.1', port: 6379, password: 'your_password' });

redis.set('greeting', 'Hello from Node.js!');
redis.get('greeting').then(value => console.log(value));

Redis integrates seamlessly with virtually every modern web framework and CMS, including WordPress, Laravel, Django, and Express.js — making it an invaluable tool for any developer's stack.

Common Redis Use Cases

Understanding where Redis excels helps you get the most out of your deployment:

Use CaseDescription
Session StorageStore user sessions in Redis for fast, scalable access across multiple app servers
Database CachingCache expensive SQL query results to reduce database load
Rate LimitingTrack API request counts per user/IP using Redis counters
Real-Time LeaderboardsUse sorted sets to maintain live rankings
Message QueuingUse Redis lists or Pub/Sub for lightweight task queues
Full-Text SearchUse RediSearch module for fast search indexing

Troubleshooting Common Redis Issues

Redis Fails to Start

Check the logs for errors:

sudo journalctl -u redis -n 50

Common causes include port conflicts, incorrect redis.conf syntax, or insufficient memory.

Connection Refused Error

Verify Redis is listening on the expected address and port:

ss -tlnp | grep redis

Authentication Errors

If you receive NOAUTH Authentication required, ensure you're passing the correct password in your client connection string or via AUTH in the CLI.

High Memory Usage

Configure a memory limit in redis.conf to prevent Redis from consuming all available RAM:

maxmemory 256mb
maxmemory-policy allkeys-lru

The allkeys-lru policy evicts the least recently used keys when the memory limit is reached — ideal for caching use cases.

Hosting Redis: Choosing the Right Infrastructure

The performance of your Redis instance is directly tied to the quality of your underlying server infrastructure. For production workloads, consider:

  • VPS Hosting — An excellent starting point for small to medium applications. AlexHost VPS plans offer SSD storage, dedicated RAM, and full root access to configure Redis exactly as needed.
  • Dedicated Servers — For high-traffic applications requiring maximum Redis performance, a dedicated server provides exclusive hardware resources with no noisy-neighbor effects.
  • VPS with cPanel — If you prefer a graphical management interface alongside your Redis deployment, a cPanel VPS simplifies server management while still giving you full Redis control via SSH.

For web applications that also need fast, reliable hosting with SSL support, pairing your Redis setup with an SSL Certificate ensures your entire stack is secure from end to end.

Conclusion

Installing and configuring Redis on Linux is a straightforward process that can deliver dramatic performance improvements to your applications. By following this guide, you have:

  • ✅ Installed Redis on Ubuntu/Debian or CentOS/RHEL
  • ✅ Started and enabled Redis as a system service
  • ✅ Configured authentication, network binding, and port settings
  • ✅ Enabled persistence to protect your data
  • ✅ Applied security hardening best practices
  • ✅ Integrated Redis with Python, PHP, and Node.js applications

Redis's combination of speed, flexibility, and rich feature set makes it one of the most valuable tools in any developer's or system administrator's toolkit. With the right server infrastructure — such as a high-performance VPS or Dedicated Server from AlexHost — your Redis deployment will be ready to handle even the most demanding production workloads.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started