Node.js + Redis on OpenShift
I have a pet project that uses a Web application running on node.js with its data stored in Redis.
Since I joined Red Hat, I took the opportunity to eat our own dog food and port this application from Heroku to OpenShift.
OpenShift does not support (yet) Redis in its list of database cartridges but it is straighforward to build a Redis server from scratch directly in OpenShift by following these instructions.
The next step is to add redis module to the list of dependencies in deplist.txt
:
$ cat deplist.txt
...
redis
...
Redis node.js module does not expose a method to create a client from a Unix socket. We need to add our own function to do that and pass the path to the socket located in a temporary directory inside OPENSHIFT_GEAR_DIR
directory (I found the code snippet on stackoverflow):
var express = require('express');
var net = require('net');
var __redis__ = require('redis');
var createSocketClient = function (path, options) {
var client = new __redis__.RedisClient(net.createConnection(path), options);
client.path = path;
return client;
};
var redis = createSocketClient(process.env.OPENSHIFT_GEAR_DIR + 'tmp/redis.sock');
The rest of the code was not changed at all:
var app = express.createServer();
// Handler for POST /test
app.post('/test', function(req, res){
redis.incr('val', function(err, value) {
if (err) {
res.writeHead(500);
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('val=' + value + '\n');
}
});
})
...
Once the code is committed and pushed to OpenShift Git repository, the hook will build and start Redis (only the first time) and the Web application is ready to serve any data from Redis:
$ curl -X POST http://${appname}-jmesnil.rhcloud.com/test/
val=1
$ curl -X POST http://${appname}-jmesnil.rhcloud.com/test/
val=2
Even though Redis is not officially supported by OpenShift yet, it is still possible to use it now and it is very simple to deploy and run it.