Occasionally you may want to run multiple Redis database on the same host.
Redis has a concept of databases, however these are less like a traditional database, and more like a namespace. Redis databases have a number of drawbacks:
- Redis databases have a number (typically 0-15) rather than a name
- Configuration, including password, are shared by all Redis databases
- Redis databases do not work in a Redis cluster1
- Pub-sub messaging ignores Redis databases2
- ACLs ignore Redis databases3
An interesting feature that Redis databases do have is that they can be swapped instantly using the SWAPDB4 command. Although I haven’t found a use case for this yet.
In order to have multiple real Redis databases simply run multiple instances of Redis server on the host.
Running multiple instances on Debian is documented5, but this documentation is a bit hard to find, so here are the steps:
Copy the file /etc/redis/redis.conf to redis-myinstance.conf
cp /etc/redis/redis.conf /etc/redis/redis-myinstance.conf
Change the following directives in redis-myinstance.conf:
Directive | Value |
---|---|
port | <any available port e.g. 6380> |
unixsocket | /var/run/redis-myinstance/redis-server.sock |
pidfile | /var/run/redis-myinstance/redis-server.pid |
logfile | /var/log/redis/redis-server-myinstance.log |
dbfilename | /var/dump-myinstance.rdb |
When comparing the original and myinstance configuration
diff -u0 /etc/redis/redis.conf /etc/redis/redis-myinstance.conf
The difference should look something like
--- redis.conf
+++ redis-myinstance.conf
@@ -91 +91 @@
-port 6379
+port 6380
@@ -108 +108 @@
-# unixsocket /var/run/redis/redis-server.sock
+# unixsocket /var/run/redis-myinstance/redis-server.sock
@@ -247 +247 @@
-pidfile /var/run/redis/redis-server.pid
+pidfile /var/run/redis-myinstance/redis-server.pid
@@ -260 +260 @@
-logfile /var/log/redis/redis-server.log
+logfile /var/log/redis/redis-server-myinstance.log
@@ -342 +342 @@
-dbfilename dump.rdb
+dbfilename dump-myinstance.rdb
In addition change any other configuration directives you like. I strongly recommend setting requirepass to a strong password, even if you intend to only use Redis locally.
Now use systemd’s instantiated service feature to enable and start your instance
systemctl enable redis-server@instance.service -–now
You should now have another Redis instance running, waiting to be used. Check its status using
systemctl status redis-server@instance.service
Now connect using your favorite Redis client, e.g. when using Java from the same machine use the following URL
redis://password@localhost:6380/
Enjoy your new Redis instance.
-
See top comments in
/lib/systemd/system/redis-server@.service
↩