DEV Community

Akira Kashihara
Akira Kashihara

Posted on

connect-redis on Docker with Password

I want to share the solution to use connect-redis with a password on Docker.


I use redis@v4.
connect-redis official website provides the following code. However, this code does not work correctly on Docker using docker-compose. This code does not include password settings. It is also one of the problems.
I guess that this container connects to localhost on the setting of this code. So it might be its cause.

const session = require("express-session")
let RedisStore = require("connect-redis")(session)

// redis@v4
const { createClient } = require("redis")
let redisClient = createClient({ legacyMode: true })

    store: new RedisStore({ client: redisClient }),
    saveUninitialized: false,
    secret: "keyboard cat",
    resave: false,
Enter fullscreen mode Exit fullscreen mode


redis on npm website provides me to solve these problems.
It indicates the following code. So I try to make a code according to this code.

  url: 'redis://alice:foobared@awesome.redis.server:6380'
Enter fullscreen mode Exit fullscreen mode

The contents of this URL are the following.

Enter fullscreen mode Exit fullscreen mode

Of course, this is an URL; you should not use "/," "+," "&" and "?".
host is a service name that is written on docker-compose.yml.
The following is a sample code.
You must add legacyMode:true to createClient argument. The process does not escape from store process if you do not add this option.

const RedisStore = require("connect-redis")(session);

// redis@v4
const { createClient } = require("redis")
// let redisClient = createClient({host: 'redisdb', port: 6379, legacyMode: true, password: env.REDIS_PASS })
let redisClient = createClient({url: `redis://${env.REDIS_USER}:${env.REDIS_PASS}@${env.REDIS_HOST}:${env.REDIS_PORT}`, legacyMode: true})
Enter fullscreen mode Exit fullscreen mode

The description of each vairable on this code is the following.

REDIS_USER=user name(default value is "default")
REDIS_HOST=host name (It is written to docker-compose.yml)
REDIS_PORT=port number(default value is 6379)
Enter fullscreen mode Exit fullscreen mode

This original article is the following that is written by me. This article was translated from Japanese to English.

Discussion (0)