How to Install Redis on Ubuntu Linux

Redis is an in-memory data structure store used as a database, cache, and message broker. It also handles strings, hashes, lists, sets, sorted sets, and streams with microsecond latency, making it ideal for session caching, real-time analytics, message queues, and leaderboards. As a result, Redis delivers throughput exceeding millions of operations per second on commodity hardware while maintaining data persistence options and replication for high availability.

Ubuntu offers two Redis installation paths: the default APT (Advanced Package Tool, Ubuntu’s package manager comparable to combining Windows Update with the Microsoft Store) repository delivers tested stable versions integrated with system updates, while the official Redis.io repository provides the latest releases with recent features and performance improvements. Throughout this guide, you learn about both methods alongside configuration examples for memory management, network access, authentication, and firewall rules.

Choose Your Redis Installation Method

Ubuntu provides two Redis installation paths with different update cycles and version availability. Consequently, understanding the trade-offs helps you match the installation method to your requirements.

MethodVersion/ChannelStabilityBest For
Ubuntu APT RepositoryStable versions tested for Ubuntu LTS releasesHigh stability, conservative updates tied to Ubuntu release cycleProduction servers, applications requiring long-term stability, systems following standard Ubuntu update schedules
Redis.io Official RepositoryLatest Redis releases, frequent updates with new featuresStable upstream releases but updates arrive faster with less Ubuntu-specific testingDevelopment environments, applications needing cutting-edge features, workloads requiring performance improvements from recent releases

The Ubuntu APT repository delivers Redis versions aligned with the distribution’s release cycle, receiving security patches through standard Ubuntu update channels. Additionally, these builds integrate tightly with Ubuntu’s package management and receive thorough testing across the distribution’s supported lifetime. Updates arrive conservatively, prioritizing stability over feature velocity.

The Redis.io repository tracks upstream Redis development closely, shipping new features, performance optimizations, and bug fixes shortly after release. Consequently, this path suits development workflows and applications that benefit from recent Redis capabilities like improved memory management, new data structures, or enhanced clustering features. The faster update cycle means less Ubuntu-specific testing but maintains Redis project quality standards.

Production environments should favor the Ubuntu repository for predictable updates and extended support alignment. Meanwhile, development and performance-critical workloads benefit from Redis.io’s rapid feature delivery when you can manage the slightly higher update frequency.

Method 1: Install Redis via APT Default Repository

Update Ubuntu Before Redis Installation

Open the terminal (press Ctrl + Alt + T or search for “Terminal” in the Activities overview) and update your system packages to ensure clean Redis installation without dependency conflicts:

sudo apt update && sudo apt upgrade

Install Redis via APT Command

Ubuntu includes Redis in the default repository. Next, install the server package and command-line tools:

sudo apt install redis-server redis-tools

This installs the Redis server daemon, command-line interface, and supporting utilities. In addition, the installation automatically configures systemd (Ubuntu’s service manager, similar to Windows Services) and creates the default configuration at /etc/redis/redis.conf.

Configure Systemd Supervision

Redis can integrate with systemd for proper service lifecycle management. Therefore, open the configuration file and set the supervised directive to enable systemd integration:

sudo nano /etc/redis/redis.conf

Locate the supervised directive (typically around line 277) and change it from no to systemd:

supervised systemd

This enables Redis to signal systemd when it’s ready to accept connections and improves integration with systemd’s service management features. After making the change, save the file (Ctrl + O, Enter) and exit (Ctrl + X), then restart Redis:

sudo systemctl restart redis-server

Verify Redis Installation

After installation completes, confirm Redis installed correctly by checking the version:

redis-cli --version

The output displays the installed Redis version:

redis-cli 7.2.4

This confirms successful installation. Enable and start the Redis service:

sudo systemctl enable redis-server --now

Confirm the service is running without errors:

systemctl status redis-server

The output should show “active (running)” status:

redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; preset: enabled)
     Active: active (running) since Sat 2025-11-16 14:32:15 UTC; 5s ago
   Main PID: 4171 (redis-server)
      Tasks: 5 (limit: 4557)
     Memory: 3.1M
     CGroup: /system.slice/redis-server.service
             |-4171 /usr/bin/redis-server 127.0.0.1:6379

Together, these steps confirm Redis is operational and listening on the default port 6379.

Method 2: Install Redis via Redis.io APT Repository

Update Ubuntu Before Redis.io Installation

First, update system packages to ensure compatibility and prevent conflicts:

sudo apt update && sudo apt upgrade

Install Repository Prerequisites

Next, install packages needed for secure repository management:

sudo apt install ca-certificates curl gnupg lsb-release software-properties-common -y

These tools enable secure HTTPS repository access, GPG key verification, and certificate validation when adding third-party sources. Additionally, the curl command handles downloading GPG keys and repository files over secure connections. Installing lsb-release ensures the codename detection used in the repository configuration works on minimal images.

Add Redis.io Repository

Create a dedicated keyring location and import the Redis.io GPG key to verify package authenticity:

sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/redis-archive-keyring.gpg
sudo chmod 0644 /etc/apt/keyrings/redis-archive-keyring.gpg

Add the Redis.io repository using a modern DEB822 .sources file for precise key scoping:

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: /etc/apt/keyrings/redis-archive-keyring.gpg
EOF

The Signed-By directive ensures APT only accepts packages signed with the Redis.io GPG key, preventing package spoofing attacks.

Refresh Package Cache

Afterward, update APT’s package cache to include Redis packages from the new repository:

sudo apt update

Install Redis from Redis.io Repository

Now install Redis server and command-line tools from the Redis.io repository. If Redis is already installed from Ubuntu’s default repository, this command upgrades to the Redis.io version:

sudo apt install redis-server redis-tools

Verify Redis.io Installation

Confirm the installed version comes from the Redis.io repository:

apt-cache policy redis-server

Example output showing Redis served from packages.redis.io:

redis-server:
  Installed: 7.4.0-1rl1~noble
  Candidate: 7.4.0-1rl1~noble
  Version table:
 *** 7.4.0-1rl1~noble 100
        100 /var/lib/dpkg/status
     5:7.0.15-1ubuntu0.1 500
        500 http://archive.ubuntu.com/ubuntu noble-updates/universe amd64 Packages

The output should show packages from packages.redis.io, confirming installation from the Redis.io repository. Immediately afterward, enable and start the Redis service:

sudo systemctl enable redis-server --now

Next, confirm the service is running without errors:

systemctl status redis-server

Example systemctl output showing a healthy service:

redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; preset: enabled)
     Active: active (running) since Sat 2025-11-16 14:32:15 UTC; 5s ago
   Main PID: 4171 (redis-server)
      Tasks: 5 (limit: 4557)
     Memory: 3.1M
     CGroup: /system.slice/redis-server.service
             |-4171 /usr/bin/redis-server 127.0.0.1:6379

Redis should be actively listening on localhost at the default port 6379. Confirm the listener with ss:

sudo ss -tlnp 'sport = :6379'

Example output:

State  Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0      128    127.0.0.1:6379    0.0.0.0:*     users:(("redis-server",pid=4171,fd=6))

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. Then 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 “PONG” response confirms Redis is accepting commands. Finally, exit the CLI session:

exit

Redis is now operational and ready for configuration. From here, the following sections cover memory management, network access, authentication, and firewall rules.

Configure Redis Core Settings

Redis configuration controls memory usage, network access, and authentication through settings in /etc/redis/redis.conf. Accordingly, this section covers essential configurations for production deployments including memory limits, bind addresses, and password protection.

Access Redis Configuration File

First, open the Redis configuration file to adjust memory, network, and authentication settings:

sudo nano /etc/redis/redis.conf

Set Memory Limits

Redis operates in-memory by default without memory limits, risking system instability if data grows unchecked. Therefore, set explicit memory limits and eviction policies to control resource usage. Add these lines at the end of the configuration file:

maxmemory 500mb
maxmemory-policy allkeys-lru

This configuration caps Redis memory usage at 500 MB and applies the Least Recently Used (LRU) eviction policy when the limit is reached. The allkeys-lru policy removes the least recently accessed keys from the entire keyspace, making it suitable for general caching workloads. If you need to preserve persistent keys with no expiration, tune the policy using the key-expiration guidance later in this section. For production systems, allocate 60-70% of available RAM to leave headroom for operating system processes and Redis memory overhead.

Configure Network Binding

Redis defaults to binding only the localhost interface (127.0.0.1), restricting access to local processes. However, remote access requires changing the bind directive to accept connections from specific IP addresses, subnets, or all interfaces. Locate the bind directive in the configuration file (typically around line 69).

Binding Redis to external interfaces exposes it to network access. Always combine network binding with strong password authentication (covered below) and firewall rules restricting access to trusted IP addresses. Redis has no built-in encryption; consider using SSH tunnels or TLS proxies for connections over untrusted networks.

Option 1: Listen on all network interfaces

Comment out the bind directive to accept connections on all interfaces:

# bind 127.0.0.1 ::1

This permits connections from any interface. Use only in development environments or when combined with strict firewall rules.

Option 2: Bind to specific IP addresses

Alternatively, specify one or more IP addresses to restrict which interfaces accept connections. Replace the bind directive with your server’s IP address:

bind 192.168.1.100 127.0.0.1

This example binds to the private network address 192.168.1.100 and maintains localhost access. Multiple space-separated addresses are supported. Choose addresses matching your network topology, such as private RFC1918 ranges for internal networks, and use public IPs only when paired with authentication and firewall protection.

Enable Password Authentication with ACLs

Redis 6.0+ uses Access Control Lists (ACLs) for authentication, replacing the legacy requirepass directive. Consequently, ACLs provide granular control over user permissions, allowing you to create multiple users with specific command and keyspace restrictions. First, generate a strong password:

openssl rand -base64 32

Example output:

Zx9K2mN8pQ7rL3vT6bH1wY4cF5aS0dG8jU9iO2eR1mP=

Copy the generated password. Then open the Redis configuration file and scroll to the ACL section (typically around line 1000). Disable the default user and create a new user with your password:

# Disable the default user for security
user default off

# Create new user with full permissions
user redisuser on >YourGeneratedPasswordHere ~* &* +@all

This ACL rule creates redisuser with full permissions: on enables the user, >password sets the password, ~* grants access to all keys, &* allows all Pub/Sub channels, and +@all permits all commands. For production systems, restrict permissions using categories like +@read, +@write, -@dangerous to limit command access.

After enabling password authentication, clients must authenticate. Therefore, connect with redis-cli using the --user and --askpass flags for secure authentication:

redis-cli --user redisuser --askpass

Enter your password when prompted. Test authentication with a PING command:

127.0.0.1:6379> PING
PONG

The PONG response confirms successful authentication. Alternatively, authenticate after connecting with AUTH redisuser YourPassword, though this exposes the password in shell history and process listings.

Older Redis installations may use the legacy requirepass directive for simple password authentication. While functional, requirepass provides only single-user authentication without permission controls. Redis 6.0+ strongly recommends ACLs for production deployments, offering per-user command restrictions and improved security through the principle of least privilege.

Apply Configuration Changes

Save the configuration file (press Ctrl + O, then Enter) and exit nano (Ctrl + X). Afterwards, restart Redis to load the new settings:

sudo systemctl restart redis-server

Verify Redis restarted successfully without configuration errors:

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) since Sat 2025-11-16 14:45:22 UTC; 3s ago
   Main PID: 5284 (redis-server)
      Tasks: 5 (limit: 4557)
     Memory: 3.2M
     CGroup: /system.slice/redis-server.service
             |-5284 /usr/bin/redis-server 127.0.0.1:6379

Check for “active (running)” status. Configuration errors appear in the service logs, accessible with journalctl -u redis-server -n 50.

Configure Firewall Rules for Redis

Redis listens on TCP port 6379 by default. If you configured Redis to accept network connections beyond localhost, adjust your firewall rules to permit access from trusted sources while blocking unauthorized attempts. Accordingly, this section covers UFW (Uncomplicated Firewall) configuration for Redis access control.

Ensure UFW is Installed and Enabled

First, make sure UFW is installed on your system:

sudo apt install ufw -y

Before enabling UFW, allow SSH to prevent locking yourself out of remote sessions:

sudo ufw allow OpenSSH

Next, enable UFW if it isn’t already:

sudo ufw enable

You’ll receive a confirmation message:

Firewall is active and enabled on system startup

Add Redis Firewall Rules

Restrict Redis access to specific IP addresses or subnets based on your network architecture. Never expose Redis port 6379 to the public internet without additional security layers like VPNs or TLS proxies.

Option 1: Allow access from a specific IP address

Grant access to a single application server or bastion host:

sudo ufw allow proto tcp from 192.168.1.50 to any port 6379

UFW confirms the rule addition:

Rule added

Replace 192.168.1.50 with your application server’s IP address. This rule permits only the specified host to connect to Redis while blocking all other addresses.

Option 2: Allow access from a subnet

For Redis clusters or multiple application servers within a trusted network segment, allow an entire subnet:

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

This permits any host in the 192.168.1.0/24 range to connect. Use subnet rules only for secure internal networks where all hosts are trusted, because a compromised machine within the subnet gains Redis access.

Verify Firewall Configuration

Test Redis connectivity from an allowed client machine to confirm firewall rules work as expected:

redis-cli -h 192.168.1.100 ping

Replace 192.168.1.100 with your Redis server’s IP address. A successful connection returns:

PONG

If authentication is enabled, include the password with -a flag: redis-cli -h 192.168.1.100 -a YourPassword ping. Connection timeouts or “Connection refused” errors indicate firewall blocking or incorrect bind configuration.

Additional Redis Configuration Options

Beyond basic memory limits and authentication, Redis offers advanced configuration options for performance tuning and operational monitoring. These settings control key eviction behavior, connection management, query performance logging, event notifications, and debug output levels.

Configure Key Expiration Policy

The maxmemory-policy setting determines which keys Redis evicts when memory limits are reached. If you run general caches, keep the earlier allkeys-lru value. When your dataset mixes cached items with critical persistent records, switch the directive to volatile-lru, which removes the least recently used keys only among those with expiration times set. Locate and modify this setting in /etc/redis/redis.conf:

maxmemory-policy volatile-lru

The maxmemory-samples setting controls eviction accuracy by determining how many keys Redis samples when selecting candidates for removal. Furthermore, higher values improve eviction quality at the cost of CPU usage:

maxmemory-samples 5

The default value of 5 balances accuracy and performance for most workloads. Alternatively, increase to 10 for applications requiring precise LRU approximation, or decrease to 3 for high-throughput environments prioritizing speed over eviction precision.

Configure TCP Keepalive

TCP keepalive probes detect and close idle connections, freeing system resources. Accordingly, set the tcp-keepalive interval (in seconds) to enable periodic connection checks:

tcp-keepalive 300

This configuration sends keepalive probes every 300 seconds (5 minutes). Lower values detect dead connections faster but increase network overhead, while higher values reduce overhead at the cost of delayed detection. Adjust based on your network reliability and connection patterns.

Configure Slow Log Monitoring

Slow query logging identifies performance bottlenecks by recording commands exceeding a specified execution time. Configure the threshold (in microseconds) and maximum log entries:

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

This logs commands taking longer than 10,000 microseconds (10 milliseconds) and retains the 128 most recent slow queries. Lower thresholds catch more queries but generate more log entries, while higher thresholds focus on severe performance issues. To inspect them, review slow logs with the SLOWLOG GET command in redis-cli:

redis-cli SLOWLOG GET 5

Example output showing slow query entries:

1) 1) (integer) 14
   2) (integer) 1731758423
   3) (integer) 12450
   4) 1) "KEYS"
      2) "user:*"
   5) "127.0.0.1:52134"
   6) ""
2) 1) (integer) 13
   2) (integer) 1731758401
   3) (integer) 15230
   4) 1) "ZRANGE"
      2) "leaderboard"
      3) "0"
      4) "100"
   5) "127.0.0.1:52134"
   6) ""

Each entry shows the unique ID, timestamp, execution time in microseconds, command with arguments, client address, and client name. This helps identify expensive operations like KEYS * patterns or large range queries that should be optimized or avoided.

Enable Event Notifications

Keyspace notifications publish events when keys expire, get evicted, or undergo specific operations. Enable notifications by configuring the notify-keyspace-events setting with event type flags:

notify-keyspace-events ExA

The Ex flags enable notifications for expired keys (x) and evicted keys (e), while A is an alias for all event types. Applications can subscribe to these events using PSUBSCRIBE to track key lifecycle changes, implement cache invalidation patterns, or monitor expiration behavior. Test event notifications by subscribing in one terminal:

redis-cli PSUBSCRIBE '__keyevent@0__:expired'

In another terminal, set a key with a short expiration:

redis-cli SETEX testkey 5 "temporary value"

After 5 seconds, the first terminal displays the expiration event:

1) "pmessage"
2) "__keyevent@0__:expired"
3) "__keyevent@0__:expired"
4) "testkey"

Notifications add minimal overhead but generate significant traffic in high-throughput environments with frequent expirations or evictions.

Adjust Logging Level

Redis logging verbosity controls how much information appears in logs. Set the loglevel directive to balance debugging needs against log volume:

loglevel notice

The notice level (default) logs important messages without excessive detail. Use debug for troubleshooting with full command logging, verbose for detailed operational information, or warning to log only critical errors. Production systems typically use notice or warning to minimize log storage and parsing overhead.

Enable Unix Sockets for Local Connections

Applications running on the same server as Redis should use Unix domain sockets instead of TCP connections. Unix sockets bypass the network stack entirely, providing faster performance and better security through filesystem permissions. Enable Unix socket support in /etc/redis/redis.conf:

unixsocket /var/run/redis/redis.sock
unixsocketperm 770

This creates a socket at /var/run/redis/redis.sock with 770 permissions, allowing the Redis user and group to access it while blocking others. After restarting Redis, connect using the socket file instead of the TCP port:

redis-cli -s /var/run/redis/redis.sock

Test the connection:

redis /var/run/redis/redis.sock> PING
PONG
redis /var/run/redis/redis.sock> SET test "Hello from Unix socket"
OK
redis /var/run/redis/redis.sock> GET test
"Hello from Unix socket"

Unix sockets eliminate network-based attacks since the socket is only accessible via the filesystem, not the network.

Configure Idle Connection Timeout

Idle client connections consume server resources unnecessarily. Consequently, configure the timeout directive to automatically close connections that remain idle beyond a specified duration:

timeout 300

This closes connections idle for 300 seconds (5 minutes), freeing memory and file descriptors. Alternatively, set timeout 0 to disable automatic closure, though this allows idle connections to persist indefinitely. Production environments should use timeouts to prevent resource exhaustion from abandoned connections.

Configure Data Persistence Options

Redis operates primarily in memory but offers two persistence mechanisms to survive restarts and crashes: RDB snapshots and Append-Only File (AOF). Understanding both options helps you balance performance against data durability requirements.

RDB Snapshots (Point-in-Time Backups)

RDB creates compact point-in-time snapshots of your dataset at specified intervals. Redis forks a child process to write the snapshot asynchronously, minimizing impact on the main server. Configure RDB snapshots in /etc/redis/redis.conf using save directives:

save 900 1
save 300 10
save 60 10000

These default settings balance write frequency against disk I/O overhead. The save 900 1 line snapshots after one change within 15 minutes, save 300 10 does so after ten changes within five minutes, and save 60 10000 captures rapid bursts of writes. RDB files are compact and fast to load, making them ideal for backups and disaster recovery. However, RDB snapshots can lose data written between snapshots if Redis crashes unexpectedly. For critical data requiring maximum durability, combine RDB with AOF.

RDB snapshots write to /var/lib/redis/dump.rdb by default. If you need to customize the destination, configure the filename and location with:

dbfilename dump.rdb
dir /var/lib/redis

After saving the file, verify RDB snapshots are working by checking for the snapshot file:

sudo ls -lh /var/lib/redis/dump.rdb

Example output showing an active snapshot file:

-rw-r--r-- 1 redis redis 127K Nov 16 15:32 /var/lib/redis/dump.rdb

Additionally, check persistence status in Redis:

redis-cli INFO PERSISTENCE

Example output showing RDB configuration:

# Persistence
loading:0
async_loading:0
current_cow_peak:0
current_cow_size:0
current_cow_size_age:0
current_fork_perc:0.00
rdb_changes_since_last_save:42
rdb_bgsave_in_progress:0
rdb_last_save_time:1731770042
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:0
rdb_current_bgsave_time_sec:-1

AOF (Append-Only File) Persistence

AOF logs every write operation to a file, providing superior data durability compared to RDB snapshots. To enable it, configure AOF persistence:

appendonly yes
appendfilename "appendonly.aof"

AOF offers three synchronization policies controlling when writes flush to disk. The appendfsync directive balances durability against performance:

appendfsync everysec

Set the directive to everysec for the recommended balance, switch to always to sync after every write when you can afford the steep performance hit, or choose no to let the kernel flush data opportunistically for maximum throughput and higher risk of loss.

AOF files grow continuously as Redis logs operations. Therefore, enable automatic AOF rewriting to compact the file by replaying operations and removing redundancy:

auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

These settings trigger rewrites when the AOF file doubles in size and exceeds 64MB. Adjust thresholds based on write patterns and disk capacity to prevent excessive rewrite frequency.

After enabling rewriting, verify AOF persistence is active:

sudo ls -lh /var/lib/redis/appendonly.aof

Example output showing the AOF file:

-rw-r--r-- 1 redis redis 4.2K Nov 16 15:45 /var/lib/redis/appendonly.aof

Then check AOF status in Redis:

redis-cli INFO PERSISTENCE | grep aof

Example output confirming AOF is enabled:

aof_enabled:1
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_current_size:4312
aof_base_size:0

Production systems requiring maximum durability should enable both RDB and AOF persistence. RDB provides fast restarts and efficient backups, while AOF guarantees minimal data loss during failures. Enable both by configuring save directives alongside appendonly yes. Redis 7.0+ supports AOF with RDB preamble format, combining the best of both approaches for optimal recovery performance.

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

sudo systemctl restart redis-server

Enable TLS/SSL Encryption (Optional)

Redis 6.0+ supports TLS encryption for client connections, protecting data in transit from eavesdropping and man-in-the-middle attacks. Consequently, TLS is critical when Redis serves remote clients over untrusted networks, though local connections via Unix sockets or localhost typically don’t require encryption overhead.

Create a small certificate authority (CA) and server certificate for testing. For production, replace the generated server certificate with one issued by your internal or public CA:

sudo mkdir -p /etc/redis/tls
cd /etc/redis/tls
sudo openssl req -x509 -newkey rsa:4096 -keyout redis-ca.key -out redis-ca.crt -days 365 -nodes -subj "/CN=redis-ca"
sudo openssl req -newkey rsa:4096 -keyout redis-server.key -out redis-server.csr -nodes -subj "/CN=redis.example.com"
sudo openssl x509 -req -in redis-server.csr -CA redis-ca.crt -CAkey redis-ca.key -CAcreateserial -out redis-server.crt -days 365

Keep the CA private key restricted to root for signing only. Grant Redis access to the server key and public certificates:

sudo chown redis:redis /etc/redis/tls/redis-server.key /etc/redis/tls/redis-server.crt /etc/redis/tls/redis-ca.crt
sudo chmod 640 /etc/redis/tls/redis-server.key
sudo chmod 644 /etc/redis/tls/redis-server.crt /etc/redis/tls/redis-ca.crt
sudo chmod 600 /etc/redis/tls/redis-ca.key

Configure Redis to use TLS by editing /etc/redis/redis.conf and enabling TLS directives:

tls-port 6380
port 0
tls-cert-file /etc/redis/tls/redis-server.crt
tls-key-file /etc/redis/tls/redis-server.key
tls-ca-cert-file /etc/redis/tls/redis-ca.crt

This enables TLS on port 6380 and disables the unencrypted port 6379 by setting port 0. The tls-ca-cert-file directive points Redis at the CA that signed your server certificate. For mutual TLS (mTLS) requiring client certificates, add tls-auth-clients yes and distribute client certificates signed by the same CA.

Restart Redis and verify TLS listens on port 6380:

sudo systemctl restart redis-server
ss -tlnp | grep 6380

The output confirms Redis is listening on the TLS port:

LISTEN 0      511          0.0.0.0:6380       0.0.0.0:*    users:(("redis-server",pid=5892,fd=6))

Connect to the TLS-enabled server using redis-cli with TLS options:

redis-cli --tls --cacert /etc/redis/tls/redis-ca.crt -p 6380

If mTLS is enabled, add --cert and --key flags with a client certificate signed by your CA. Then test connectivity with PING to confirm TLS encryption works:

127.0.0.1:6380> PING
PONG

The PONG response over port 6380 confirms TLS encryption is working properly. If using UFW, update firewall rules to allow the TLS port:

sudo ufw allow 6380/tcp comment 'Redis TLS'

TLS encryption adds computational overhead (typically 5-15% performance impact) due to encryption/decryption operations. Benchmark your workload with TLS enabled to ensure acceptable performance. For maximum security with remote access, combine TLS encryption with VPN or SSH tunneling to create multiple security layers. Applications running locally should use Unix sockets instead of TLS for better performance without sacrificing local security.

Conclusion

Redis delivers high-performance in-memory data storage through either Ubuntu’s stable APT repository or Redis.io’s latest releases. Additionally, the installation process covers systemd integration, memory management, network security through ACLs and binding restrictions, firewall configuration, and persistence options balancing durability with performance. Ubuntu’s Redis package includes an AppArmor security profile that restricts Redis process capabilities, adding defense-in-depth protection against exploits. With those safeguards in place, your server now runs a production-ready Redis instance with security hardening, resource controls, and data persistence tailored to your operational requirements.

Leave a Comment