How to Install Redis on Ubuntu

Redis is an in-memory data structure store used as a database, cache, and message broker. It 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 multiple Redis installation paths: the default APT 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 will configure Redis using your preferred method, then customize memory management, network access, authentication, firewall rules, and data persistence options.

Choose Your Redis Installation Method

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

MethodChannelVersionUpdatesBest For
Ubuntu APT RepositoryUbuntu ReposDistribution default (6.0-8.0 depending on release)Automatic via apt upgradeProduction servers prioritizing stability and long-term support
Redis.io RepositoryRedis.io PackagesLatest stable (8.x)Automatic via apt upgradeUsers needing latest Redis features or performance improvements

For most users, the Ubuntu APT repository is recommended because it provides automatic security updates aligned with your distribution’s support lifecycle, requires no additional configuration, and receives thorough Ubuntu-specific testing. Only add the Redis.io repository if you specifically need features from newer Redis versions or require the latest performance improvements.

The Ubuntu APT repository delivers Redis versions aligned with the distribution’s release cycle. Ubuntu 22.04 LTS includes Redis 6.0, Ubuntu 24.04 LTS provides Redis 7.0, and Ubuntu 26.04 LTS ships Redis 8.0. These builds integrate tightly with Ubuntu’s package management and receive security patches through standard update channels.

The Redis.io repository tracks upstream Redis development closely, shipping new features, performance optimizations, and bug fixes shortly after release. You add this repository using DEB822 format which provides proper GPG key scoping and clear configuration.

This guide supports Ubuntu 22.04 LTS, 24.04 LTS, and 26.04 LTS installations. The Redis.io repository provides packages for all supported releases, while the default Ubuntu repository versions vary by release (Redis 6.0 on 22.04, 7.0 on 24.04, 8.0 on 26.04). Commands shown work identically across all supported LTS releases unless noted otherwise.

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 command installs the Redis server daemon, command-line interface, and supporting utilities. Additionally, the installation automatically configures systemd service integration and creates the default configuration at /etc/redis/redis.conf.

Configure Systemd Supervision (Ubuntu 22.04 Only)

Redis integrates with systemd for proper service lifecycle management. Specifically, the supervised directive controls this behavior, but the default value varies by version:

  • Redis 6.0 (Ubuntu 22.04): Defaults to supervised no at line 236. Change this to supervised systemd.
  • Redis 7.0+ (Ubuntu 24.04, 26.04): Defaults to supervised auto which detects systemd automatically. No changes needed.
  • Redis.io packages (8.x): Defaults to supervised auto at line 333. No changes needed.

If you’re running Ubuntu 22.04, open the configuration file:

sudo nano /etc/redis/redis.conf

Then, locate the supervised directive around line 236 and change it from no to systemd:

supervised systemd

This enables Redis to signal systemd when it’s ready to accept connections. Save the file (Ctrl + O, Enter) and exit (Ctrl + X), then restart Redis:

sudo systemctl restart redis-server

Ubuntu 24.04, 26.04, and Redis.io installations skip this step since they default to supervised auto, which detects and integrates with systemd automatically.

Verify Redis Installation

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

redis-cli --version

Subsequently, the output displays the installed Redis version, which varies by Ubuntu release:

redis-cli 8.0.2

Your version number will differ based on your Ubuntu release: Redis 6.0.x on Ubuntu 22.04, Redis 7.0.x on Ubuntu 24.04, or Redis 8.0.x on Ubuntu 26.04.

This output confirms successful installation. Next, enable and start the Redis service:

sudo systemctl enable redis-server --now

Finally, 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 gpg lsb-release -y

These tools enable secure HTTPS repository access and certificate validation when adding third-party sources. The curl command downloads GPG keys over secure connections, gpg handles key conversion with the --dearmor flag, and lsb-release provides codename detection for repository configuration on minimal images.

Add Redis.io Repository

Now, 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

Then, 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

Notably, 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: 6:8.4.0-1rl1~noble1
  Candidate: 6:8.4.0-1rl1~noble1
  Version table:
 *** 6:8.4.0-1rl1~noble1 500
        500 https://packages.redis.io/deb noble/main amd64 Packages
        100 /var/lib/dpkg/status
     5:7.0.15-1ubuntu0.24.04.2 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

At this point, 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

Next, test your Redis installation by connecting 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

To allow all interfaces, comment out the bind directive to accept connections on all interfaces:

# bind 127.0.0.1 ::1

This configuration permits connections from any interface. However, use this 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. Additionally, 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

Now, 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

For example, 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. Consequently, 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. Therefore, 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. As a result, 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"

Notably, 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.

By default, RDB snapshots write to /var/lib/redis/dump.rdb. 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.

First, 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. Then, 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

Now, 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 due to encryption and decryption operations. The performance impact varies depending on your workload, CPU capabilities, and connection patterns, so benchmark your specific use case with TLS enabled before deploying to production. 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.

Troubleshoot Common Redis Issues

Redis Service Fails to Start

If Redis fails to start, check the service logs for specific error messages:

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

Common causes include configuration syntax errors, permission issues on the data directory, or port conflicts. Additionally, test your configuration file for syntax errors:

redis-server --test-memory 256

Connection Refused Errors

If you receive “Connection refused” when connecting to Redis, verify the service is running and listening on the expected address:

ss -tlnp | grep 6379

Also, check if firewall rules are blocking the connection:

sudo ufw status numbered

Finally, verify the bind address in /etc/redis/redis.conf matches your connection target. If Redis binds only to 127.0.0.1, remote connections will fail.

Authentication Errors

If you configured ACL users and receive “NOAUTH Authentication required” or “WRONGPASS invalid username-password pair”, verify your credentials:

redis-cli
AUTH your_username your_password

To check configured users, authenticate as the default user first, then list ACL entries:

redis-cli
AUTH default your_default_password
ACL LIST

Memory Limit Reached

When Redis reaches its memory limit, behavior depends on your maxmemory-policy setting. Check current memory usage:

redis-cli INFO memory | grep -E 'used_memory|maxmemory'

If Redis is evicting keys unexpectedly or refusing writes, consider increasing maxmemory or adjusting the eviction policy in /etc/redis/redis.conf.

Remove Redis from Ubuntu

If you need to remove Redis from your system, the process differs depending on whether you installed from the default Ubuntu repository or the Redis.io repository.

Uninstall Redis Packages

Stop the Redis service and remove the packages:

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

The --purge option removes configuration files created by the package, while autoremove cleans up dependencies that were installed alongside Redis and are no longer needed.

Remove Redis Data and Configuration

Warning: The following commands permanently delete Redis data and configuration files. If you have data you want to keep, back up the dump.rdb and appendonly.aof files first with sudo cp /var/lib/redis/* ~/redis-backup/.

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

Remove Redis.io Repository (If Added)

If you installed Redis from the Redis.io repository using the manual DEB822 method, remove the repository configuration and GPG key:

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

Verify Redis is completely removed by checking for any remaining packages:

dpkg -l | grep redis

An empty output confirms successful removal.

Conclusion

Redis delivers high-performance in-memory data storage through Ubuntu’s stable APT repository or Redis.io’s latest releases via manual repository configuration. The configuration 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. 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

Let us know you are human: