How to Install and Configure Redis on Ubuntu 20.04
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
This guide explains how to install and perform the basic configuration of Redis on Ubuntu version 20.04. Redis is an open-source in-memory data structure store. It can serve as a database cache and message broker and works well with web applications. Redis is an example of a key-value store database. A key is used to retrieve a stored value. A value can contain either a simple data type such as a string, or a complex data structure such as a list, set, or hash.
Before You Begin
If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.
NoteThis guide is written for non-root users. Commands that require elevated privileges are prefixed withsudo
. If you’re not familiar with thesudo
command, see the Linux Users and Groups guide.
Redis Advantages and Disadvantages
Redis supports concurrency since all single-command operations in Redis are atomic. Redis contains a large library of commands, but it does not have a query language or relational capabilities. Since Redis is an in-memory database, it runs quickly with low latency. However, you can only store as much data as memory allows. Redis provides persistence methods to either write the current database state to disk or record all transactions in a log.
Redis requires a robust, stable hosting environment to function properly. To store large amounts of data, we recommend hosting Redis on a High Memory Linode.
A Summary of the Redis Installation and Configuration Process
A complete Redis installation, including basic configuration tasks, consists of the high-level steps outlined below. Each step is covered in detail in its own section.
- Verify your System Parameters
- Install Redis
- Enable and Run Redis
- Secure Redis
- Configure Redis Persistence
- Optimize Redis for Better Performance
Verify your System Parameters
Ensure your Linode is running an up-to-date version of Ubuntu 20.04. If necessary, enable and configure the ufw firewall. Run the following commands to enable ufw
and allow it to accept incoming SSH connections.
Configure
ufw
to allow SSH connections.ufw allow OpenSSH
Enable
ufw
.ufw enable
Run the
ufw status
command to confirm the configuration.ufw status
The output now lists the OpenSSH protocols along with an action of
ALLOW
.To Action From -- ------ ---- OpenSSH ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6)
Install Redis
You can install Redis either through the Ubuntu APT utility or from a TAR file. The latest stable version (as of January 2021) is Redis 6.0.9, but pre-release versions are also available on the Redis downloads page.
Install Redis From a Package
To install Redis using the APT utility, follow the steps below:
Add the Redis repository to the Ubuntu source repositories.
sudo add-apt-repository ppa:redislabs/redis
Update your Ubuntu packages.
sudo apt update
Install Redis using the package installation program.
sudo apt install redis-server
NoteIf the Redislabs repository is added, APT automatically installs the latest stable version. We do not recommend installing Redis through the Ubuntu default packages, as that might install an older version.
Install Redis From a Downloaded File
To install Redis from a downloaded .gz
file, follow the steps below:
Download the latest stable version from the Redis downloads page to your computer. Transfer the Redis file to your host via
scp
,ftp
, or any other file transfer method. The following example shows a Redis 6.0.9 executable. Replace the filename with the actual name of the file you are transferring, and substitute your user name and host IP address.scp /localpath/redis-6.0.9.tar.gz user@yourhost:~/
Unzip the file using the tar utility.
tar xzf redis-6.0.9.tar.gz
Change directory to the appropriate directory and install Redis. The actual directory name depends upon the exact Redis version.
cd redis-6.0.9 make
Enable and Run Redis
Redis-cli is the main command-line interface for Redis. Through this utility you can interactively store and retrieve data, and perform administrative tasks. You can configure Redis through the redis.conf
file, which contains a list of directives. Each directive consists of a variable name, plus a value, such as supervised systemd
.
Add a directive to allow Redis to start via the system control utility. Edit the
redis.conf
file at/etc/redis/redis.conf
, and change the value of thesupervised
directive tosystemd
. This setting is found in the “General” section of the file.- File: /etc/redis/redis.conf
1 2 3
... supervised systemd ...
Use
systemctl
to start the Redis service.sudo systemctl restart redis.service
Enter the interactive Redis CLI.
redis-cli
Perform a
ping
to test connectivity to the server.PING
If Redis is running, it returns a
PONG
as a reply.PONG
Use the
SET
command to create a key-value pairing. Redis returns anOK
response upon a successful set operation.SET server:name "fido"
Retrieve the value of the key you previously set.
GET server:name
Redis returns
fido
as the result.fido
NoteTheredis.conf
file contains extensive documentation and many examples. A sampleredis.conf
file can be found on the Redis Git Hub site.
NoteYou can also useredis-cli
as a function to run any command. Pass in the command and any associated variables as arguments. For example, you can perform a ping withredis-cli ping
.
Secure Redis
Configure a Password for Redis
Beginning with version 6, Redis maintains multi-user security through an Access Control List (ACL). Additionally, you can create a default user password. A default password might be sufficient for a single user. However, we highly recommend you use one or both of these methods.
Change the
requirepass
variable in theredis.conf
file to set the default password. Uncomment the existingrequirepass
directive, and change the default password to a more secure password.- File: /etc/redis/redis.conf
1 2 3
... requirepass yourpassword ...
Restart Redis to force the changes to take effect.
sudo systemctl restart redis.service
Enter
redis-cli
and set a key and value without authenticating.redis-cli SET server:name "fido2"
Redis returns an authentication error since you have not logged in yet.
(error) NOAUTH Authentication required.
Login with the
auth
command, replacing “password” with the password you configured. Redis returns anOK
response upon a successful login.AUTH "password"
Try the previous SET command again. Redis now returns an
OK
response.SET server:name "fido2"
Configure an Access Control List (ACL) for Redis
In a multi-user environment, we highly recommend you configure an ACL. An ACL restricts privileges and potentially dangerous commands to a subset of the users. You can create additional users in the redis.conf
file. Each user directive must contain a username, the keyword on
or off
to enable or disable the entry, a set of command permissions and restrictions, a set of key permissions, and the password (with a preceding >
symbol). To indicate all commands, use @all
. Use allkeys
to reference all key-value pairs. Redis parses each user directive from left to right, so the order of permissions and restrictions is important.
This is only a brief introduction to this topic. Create users with memorable names, strong passwords, and appropriate permissions when building your own ACL. A complete explanation of all the ACL options is available on the Redis ACL page.
Display the current ACL configuration with the
ACL LIST
command. It currently shows only the default user and their privileges.redis-cli ACL LIST
Edit the
redis.conf
file and add user directives for two users. The first directive addsuser2
and assigns the passworduser2pass
, along with access to all commands and keys. The second user directive, foruser3
, is similar except this user cannot runSET
commands.- File: /etc/redis/redis.conf
1 2
user user2 +@all allkeys on >user2pass user user3 +@all -SET allkeys on >user3pass
Restart Redis to force the changes to take effect.
sudo systemctl restart redis.service
Re-enter the Redis CLI and log in as
user2
(authenticate with theAUTH
command). Execute aSET
command. Redis now returns anOK
response.redis-cli AUTH user2 user2pass SET server:name "fido2"
Exit and then re-enter the Redis CLI, authenticating as
user3
. Attempt to execute anotherSET
to change the same key to a new value.redis-cli AUTH user3 user3pass SET server:name "fido3"
This attempt fails and returns a permission error.
(error) NOPERM this user has no permissions to run the 'set' command or its subcommand
Attempt to retrieve the value of this same key with a
GET
command. Redis now returns the value.GET server:name
NoteYou can also create users through the
redis-cli
interface using theACL SET USER
command, or through a separate ACL file. See the Redis ACL page for more information.In earlier versions of Redis, administrators could rename and therefore hide powerful commands using
rename-command
directives inredis.conf
. With the introduction of the ACL feature, this directive is no longer recommended. However, it is still available for backward compatibility.
Configure Redis Persistence
Redis stores all of its data in memory, so in the event of a crash or a system reboot everything is lost. If you want to permanently save your data, you must configure some form of data persistence. Redis supports two persistence options:
Redis Database File (RDB) persistence takes snapshots of the database at intervals corresponding to the
save
directives in theredis.conf
file. Theredis.conf
file contains three default intervals. RDB persistence generates a compact file for data recovery. However, any writes since the last snapshot is lost.Append Only File (AOF) persistence appends every write operation to a log. Redis replays these transactions at startup to restore the database state. You can configure AOF persistence in the
redis.conf
file with theappendonly
andappendfsync
directives. This method is more durable and results in less data loss. Redis frequently rewrites the file so it is more concise, but AOF persistence results in larger files, and it is typically slower than the RDB approach.
To change the RDB snapshot intervals, edit the
save
directives inredis.conf
. A directive consisting ofsave 30 100
means Redis continues to take a snapshot every 30 seconds provided at least 100 keys have changed. Multiple snapshot thresholds can be configured.- File: /etc/redis/redis.conf
1 2 3
save 900 1 save 300 10 save 60 10000
To enable AOF persistence, edit
redis.conf
and change the value of theappendonly
directive toyes
. Then you can set theappendfsync
directive to any one of the following of your choice.always
- sync upon every new commandeverysec
- sync one time per secondno
- let Ubuntu manage the sync.
The default of
everysec
is a good compromise for most implementations.- File: /etc/redis/redis.conf
1 2
appendonly yes appendfsync everysec
Restart the redis server after making any changes to the Redis persistence directives.
sudo systemctl restart redis.service
NoteSome of the AOF persistence settings are complicated. Consult the Redis Persistence Documentation for more advice about this option.
Optimize Redis for Better Performance
Redis recommends several additional optimizations for the best performance. In addition to the following advice, Redis makes several recommendations regarding persistence and replication. Consult the Redis Administration Information for more information.
Set the overcommit memory setting to
1
insysctl.conf
. You must reboot the node for this setting to take effect.- File: /etc/sysctl.conf
1
vm.overcommit_memory = 1
Note
Enter the commandsysctl vm.overcommit_memory=1
to apply this setting immediately.Disable the transparent huge pages feature as this adversely affects Redis latency.
echo never > /sys/kernel/mm/transparent_hugepage/enabled
Specify an explicit maximum memory value (in bytes) in
redis.conf
. This value must be at least somewhat less than your available system memory. Restart Redis after making this change.- File: /etc/redis/redis.conf
1
maxmemory 2147483648
Create some swap space in the system to prevent Redis from crashing if it consumes too much memory. The following commands set up a 2GB swap file.
sudo mkdir /swapdir/ sudo dd if=/dev/zero of=/swapdir/swapfile bs=1MB count=2048 sudo chmod 600 /swapdir/swapfile sudo mkswap /swapdir/swapfile sudo swapon /swapdir/swapfile
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on