FedoraRHEL Based

How To Install Redis on Fedora 42

Install Redis on Fedora 42

Redis is an open-source, in-memory data structure store used as a database, cache, and message broker. This powerful tool has become essential for modern applications requiring lightning-fast data operations. On Fedora 42, Redis offers exceptional performance and reliability, making it an ideal choice for developers looking to enhance their applications with high-speed data processing capabilities.

This comprehensive guide walks you through the complete process of installing, configuring, and optimizing Redis on Fedora 42. By following these instructions, you’ll set up a robust Redis environment tailored to your specific needs.

Understanding Redis and Its Benefits

Redis (Remote Dictionary Server) functions as an in-memory key-value store that supports various data structures, making it significantly more versatile than traditional caching solutions like Memcached. Its in-memory architecture enables microsecond response times, perfect for applications requiring real-time data processing.

Redis excels in several key areas:

  • Speed: By storing data in RAM, Redis delivers exceptional performance with minimal latency
  • Versatility: Supports strings, hashes, lists, sets, sorted sets, and more advanced data structures
  • Persistence: Offers options to save data to disk for durability and recovery
  • Scalability: Provides replication, clustering, and high availability features
  • Low resource consumption: Efficiently manages memory with various eviction policies

For Fedora 42 users, Redis proves particularly valuable for web applications, real-time analytics, session management, caching layers, and message queuing systems. The combination of Fedora’s stability with Redis’s performance creates an optimal environment for data-intensive applications.

Prerequisites for Redis Installation

Before installing Redis on Fedora 42, ensure your system meets these requirements:

  • A running Fedora 42 installation with at least 1GB RAM (more recommended for production)
  • At least 5GB free disk space
  • Root or sudo privileges
  • Active internet connection

First, update your system packages to ensure you have the latest dependencies:

sudo dnf update -y

Check if Redis is already installed on your system:

rpm -qa | grep redis

If Redis is already present but you want a fresh installation, remove it first:

sudo dnf remove redis -y

Verify that no other services are using Redis’s default port (6379):

sudo ss -tuln | grep 6379

It’s also wise to create a backup of any important data before proceeding with changes to your system.

Step-by-Step Redis Installation on Fedora 42

Installing Redis from Default Repository

Fedora 42 includes Redis in its default repositories, making installation straightforward:

sudo dnf install redis -y

The -y flag automatically confirms the installation. DNF will resolve and install all necessary dependencies along with Redis.

Verify the installation by checking the Redis version:

redis-server --version

Starting and Enabling the Redis Service

After installation, start the Redis service:

sudo systemctl start redis

To ensure Redis starts automatically during system boot, enable the service:

sudo systemctl enable redis

Verify that Redis is running correctly:

systemctl status redis

You should see output indicating that Redis is “active (running)”.

Verifying Redis is Listening

Confirm that Redis is listening on its default port:

ss -antpl | grep -i redis

By default, Redis listens on port 6379, typically bound to localhost (127.0.0.1).

Alternative Installation Methods

If you need a specific Redis version, you can use the Remi RPM repository:

# Import Remi repository
sudo dnf install http://rpms.remirepo.net/fedora/remi-release-42.rpm -y

# List available Redis modules
sudo dnf module list redis:remi*

# Enable desired Redis version (e.g., 7.2)
sudo dnf module enable redis:remi-7.2 -y

# Install Redis
sudo dnf install redis

This approach provides more flexibility when specific Redis versions are required for your applications.

Basic Redis Configuration

Proper configuration is crucial for Redis performance and security. The main configuration file is located at /etc/redis/redis.conf.

Essential Configuration Parameters

Open the configuration file with your preferred text editor:

sudo nano /etc/redis/redis.conf

Here are key settings to consider adjusting:

Network Configuration

By default, Redis binds only to localhost. To allow external connections (with caution):

# Default setting (secure)
bind 127.0.0.1

# Allow connections from specific IPs
# bind 127.0.0.1 192.168.1.100

# Allow connections from any IP (less secure)
# bind 0.0.0.0

Memory Management

Configure maximum memory usage to prevent Redis from consuming all available system memory:

maxmemory 256mb
maxmemory-policy allkeys-lru

The maxmemory-policy determines how Redis removes keys when it reaches the memory limit. Common options include:

  • allkeys-lru: Removes least recently used keys
  • volatile-lru: Removes least recently used keys with an expiration set
  • noeviction: Returns errors when memory limit is reached

Persistence Settings

For data durability, configure persistence options:

# RDB persistence
save 900 1
save 300 10
save 60 10000

# AOF persistence
appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec

Logging Configuration

Adjust logging settings based on your needs:

loglevel notice
logfile /var/log/redis/redis-server.log

TCP Settings

Optimize network performance:

tcp-keepalive 60

This setting helps maintain connections and can improve performance in busy environments.

Applying Configuration Changes

After modifying the configuration, restart Redis to apply changes:

sudo systemctl restart redis

Verify the service starts correctly with your new configuration:

sudo systemctl status redis

If Redis fails to start, check the logs for errors:

sudo journalctl -u redis

Common issues include incorrect syntax, permission problems with log files, or invalid configuration values.

Securing Your Redis Installation

Redis security is critical, especially if your server is accessible over a network. Implement these security measures to protect your Redis installation.

Network Security

The first layer of security is restricting network access:

  1. Bind Redis to specific interfaces rather than all interfaces
  2. Use firewall rules to limit access to the Redis port
  3. Consider using a private network for Redis communication when possible

Update your firewall configuration to restrict access to Redis:

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

Password Authentication

Set a strong Redis password by editing redis.conf:

requirepass YourStrongPasswordHere

Choose a complex password (32+ characters recommended) to resist brute force attacks.

To connect to a password-protected Redis instance:

redis-cli -a YourStrongPasswordHere

Or authenticate after connecting:

redis-cli
127.0.0.1:6379> AUTH YourStrongPasswordHere

Protected Mode

Redis 3.2.0+ includes “protected mode” which prevents external connections when Redis has no password but is bound to all interfaces. While helpful, don’t rely solely on this feature.

Disabling Dangerous Commands

For added security, consider disabling potentially dangerous commands:

rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG ""

Setting the new name to an empty string effectively disables the command.

Running Redis as a Non-Root User

Redis should never run as root. Fedora’s package automatically configures Redis to run as the redis user. Verify this configuration:

ps aux | grep redis

The output should show Redis running as the redis user rather than root.

Testing Redis Connectivity and Functionality

After installation and configuration, verify that Redis works correctly with these basic tests.

Using redis-cli to Connect to Redis

Connect to your Redis server using the Redis command-line interface:

redis-cli

If you’ve set a password:

redis-cli -a YourStrongPasswordHere

Basic Redis Commands for Testing

Test basic functionality with these commands:

1. Verify the connection:

127.0.0.1:6379> PING
PONG

2. Set and retrieve a key:

127.0.0.1:6379> SET test_key "Hello Fedora 42"
OK
127.0.0.1:6379> GET test_key
"Hello Fedora 42"

3. Check Redis server information:

127.0.0.1:6379> INFO server

4. Try other data structures like lists:

127.0.0.1:6379> LPUSH mylist "item1" "item2" "item3"
(integer) 3
127.0.0.1:6379> LRANGE mylist 0 -1
1) "item3"
2) "item2"
3) "item1"

Testing Remote Connectivity

If you’ve configured Redis for remote access, test from another machine:

redis-cli -h your_redis_server_ip -p 6379 -a YourStrongPasswordHere

Troubleshooting Connection Issues

If you encounter connection problems, check these common areas:

1. Verify Redis is running:

systemctl status redis

2. Check if Redis is listening on the expected port:

ss -antpl | grep redis

3. Ensure firewall rules allow connections:

sudo firewall-cmd --list-all

4. Check Redis logs for errors:

sudo tail -f /var/log/redis/redis-server.log

5. Test connectivity with telnet or netcat:

nc -zv 127.0.0.1 6379

Common errors include “connection refused” (Redis not running or not listening on the right port) and “authentication required” (missing or incorrect password).

Redis Persistence Configuration

Redis provides two persistence mechanisms to prevent data loss during restarts or crashes.

Understanding Redis Persistence Options

  1. RDB (Redis Database): Takes point-in-time snapshots at specified intervals
  2. AOF (Append Only File): Logs every write operation for replay during restart

Each method has advantages:

  • RDB: Smaller files, faster restarts, good for backups
  • AOF: Better durability, minimizes data loss, easier to understand

Configuring RDB Persistence

Edit redis.conf to configure RDB snapshots:

save 900 1      # Save if at least 1 key changed in 15 minutes
save 300 10     # Save if at least 10 keys changed in 5 minutes
save 60 10000   # Save if at least 10000 keys changed in 1 minute
dbfilename dump.rdb
dir /var/lib/redis

The save directives define when Redis takes snapshots based on time elapsed and number of key changes.

Setting Up AOF Persistence

For append-only file persistence:

appendonly yes
appendfilename "appendonly.aof"
appendfsync everysec

The appendfsync options are:

  • always: Maximum safety, lowest performance
  • everysec: Good compromise (lose at most 1 second of data)
  • no: Operating system decides (faster but less safe)

Testing Persistence Configuration

After configuring persistence, verify it works:

1. Connect to Redis and set test data:

redis-cli
127.0.0.1:6379> SET persistencetest "Data should persist after restart"

2. Restart Redis:

sudo systemctl restart redis

3. Check if your data persisted:

redis-cli
127.0.0.1:6379> GET persistencetest

Creating Backup Procedures

Implement regular backups of your Redis data files:

# Create backup directory
sudo mkdir -p /var/backups/redis

# Backup RDB and AOF files
sudo cp /var/lib/redis/dump.rdb /var/backups/redis/dump.rdb.$(date +%Y%m%d)
sudo cp /var/lib/redis/appendonly.aof /var/backups/redis/appendonly.aof.$(date +%Y%m%d)

Consider automating this with a cron job for daily backups.

Performance Tuning and Benchmarking

Optimize your Redis installation for maximum performance on Fedora 42.

Memory Optimization

Redis performance is heavily tied to memory management:

1. Set appropriate maximum memory limits:

maxmemory 4gb

2. Choose the right eviction policy based on your use case:

maxmemory-policy allkeys-lru  # For general cache
maxmemory-policy volatile-lru  # When using expirations
maxmemory-policy noeviction  # When data loss is unacceptable

3. Enable memory defragmentation for Redis 4.0+:

activedefrag yes

System Tuning for Redis

Optimize your Fedora 42 system for Redis:

1. Disable transparent huge pages:

echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled

2. Set the Linux kernel overcommit memory parameter:

echo 'vm.overcommit_memory = 1' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

3. Increase maximum connections:

echo 'net.core.somaxconn = 65535' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

These settings can dramatically improve Redis performance under high load.

Using redis-benchmark

Redis includes a benchmarking tool to measure performance:

# Basic benchmark
redis-benchmark -h 127.0.0.1 -p 6379 -a YourStrongPasswordHere -q

# Detailed benchmark with 100,000 requests, 50 clients
redis-benchmark -h 127.0.0.1 -p 6379 -a YourStrongPasswordHere -n 100000 -c 50 --csv

The results show operations per second for various Redis commands.

Measure latency specifically:

redis-cli --latency

Typical results on modern hardware should show tens or hundreds of thousands of operations per second for most commands, with sub-millisecond latency.

Pipeline Optimization

Pipelining multiple commands can significantly boost performance by reducing round trips:

(redis-cli) PIPELINE
SET key1 value1
SET key2 value2
GET key1
GET key2
EXEC

This technique can increase throughput by 5-10x in high-latency environments.

Advanced Redis Features

Redis offers sophisticated features beyond basic key-value operations.

Redis Replication

Set up master-replica replication for read scaling and data redundancy:

1. On the replica server, add to redis.conf:

replicaof master_ip 6379
masterauth master_password

2. Restart the replica:

sudo systemctl restart redis

3. Verify replication status on the replica:

redis-cli
127.0.0.1:6379> INFO replication

Redis Sentinel for High Availability

Implement automatic failover with Redis Sentinel:

1. Create a sentinel configuration file (/etc/redis/sentinel.conf):

sentinel monitor mymaster 192.168.1.100 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel auth-pass mymaster MasterPassword

2. Start Sentinel:

sudo redis-sentinel /etc/redis/sentinel.conf

3. Configure it as a service:

sudo systemctl enable redis-sentinel
sudo systemctl start redis-sentinel

Redis Pub/Sub Messaging

Implement real-time messaging with Redis pub/sub:

# Publisher
PUBLISH news_channel "Breaking news: Redis rocks on Fedora 42!"

# Subscriber
SUBSCRIBE news_channel

This feature is excellent for implementing chat systems, notification services, and real-time updates.

Redis Transactions and Lua Scripting

Execute atomic operations with transactions:

MULTI
SET user:1:name "John"
SET user:1:email "john@example.com"
EXEC

For more complex atomic operations, use Lua scripts:

EVAL "local current = redis.call('GET', KEYS[1]); redis.call('SET', KEYS[1], current+ARGV[1]); return redis.call('GET', KEYS[1])" 1 counter 5

Lua scripts execute atomically, combining multiple operations into a single step.

Redis Integration with Applications

Connect Redis to your applications using client libraries for various programming languages.

Python Integration

Use redis-py to connect Python applications to Redis:

import redis

# Connect to Redis
r = redis.Redis(
    host='localhost',
    port=6379,
    password='YourStrongPasswordHere',
    decode_responses=True
)

# Basic operations
r.set('python_key', 'Hello from Python')
value = r.get('python_key')
print(value)

Node.js Integration

Connect Node.js applications using node-redis:

const redis = require('redis');

async function redisDemo() {
    // Create client
    const client = redis.createClient({
        url: 'redis://default:YourStrongPasswordHere@localhost:6379'
    });
    
    await client.connect();
    
    // Set and get values
    await client.set('nodejs_key', 'Hello from Node.js');
    const value = await client.get('nodejs_key');
    console.log(value);
    
    await client.quit();
}

redisDemo();

Java Integration

Use Jedis for Java applications:

import redis.clients.jedis.Jedis;

public class RedisExample {
    public static void main(String[] args) {
        try (Jedis jedis = new Jedis("localhost", 6379)) {
            jedis.auth("YourStrongPasswordHere");
            
            // Set and get values
            jedis.set("java_key", "Hello from Java");
            String value = jedis.get("java_key");
            System.out.println(value);
        }
    }
}

Connection Pooling and Best Practices

For production use, implement connection pooling to improve performance:

  1. Reuse connections instead of creating new ones for each operation
  2. Set reasonable connection timeouts and retry strategies
  3. Implement error handling for Redis operations
  4. Consider cache patterns like cache-aside or write-through based on your needs

These practices will help your application handle Redis connections efficiently, even under high load.

Monitoring and Maintenance

Implement robust monitoring and maintenance procedures to ensure Redis runs smoothly over time.

Using Redis CLI for Monitoring

Redis provides built-in commands for monitoring:

# Get server stats
redis-cli INFO

# Watch commands in real-time (use sparingly)
redis-cli MONITOR

# List connected clients
redis-cli CLIENT LIST

# Check for slow commands
redis-cli SLOWLOG GET 10

Setting Up External Monitoring

For comprehensive monitoring, use Prometheus and Grafana:

1. Install Redis Exporter:

sudo dnf install prometheus-redis-exporter

2. Configure Prometheus to scrape Redis metrics

3. Create Grafana dashboards to visualize Redis performance

Popular monitoring tools like RedisInsight also provide user-friendly interfaces for Redis monitoring.

Regular Maintenance Tasks

Implement these maintenance practices:

1. Configure log rotation for Redis logs:

sudo nano /etc/logrotate.d/redis

Add:

/var/log/redis/redis-server.log {
    weekly
    rotate 10
    compress
    delaycompress
    notifempty
    missingok
    postrotate
        systemctl reload redis
    endscript
}

2. Schedule regular backups of Redis data files

3. Monitor disk space usage on Redis data directories

4. Keep Redis updated with security patches:

sudo dnf update redis

Troubleshooting Common Issues

When problems arise, check these areas:

1. Memory issues:

redis-cli INFO memory

2. Permission problems (common with log files):

ls -la /var/log/redis/

3. Configuration syntax errors:

redis-server --check /etc/redis/redis.conf

4. Service startup issues:

sudo journalctl -u redis

Common errors include “permission denied” for log files, “port already in use,” and “configuration errors”.

Congratulations! You have successfully installed Redis. Thanks for using this tutorial for installing the Redis cache on your Fedora 42 Linux system. For additional help or useful information, we recommend you check the official Redis website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button