I want to share the solution to use connect-redis with a password on Docker.
Problem
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 })
redisClient.connect().catch(console.error)
app.use(
session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: "keyboard cat",
resave: false,
})
)
Solution
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.
createClient({
url: 'redis://alice:foobared@awesome.redis.server:6380'
});
The contents of this URL are the following.
redis[s]://[[username][:password]@][host][:port][/db-number]
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")
console.log(env.REDIS_PASS);
// 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})
redisClient.connect().catch(console.error);
The description of each vairable on this code is the following.
REDIS_USER=user name(default value is "default")
REDIS_PASS=password
REDIS_HOST=host name (It is written to docker-compose.yml)
REDIS_PORT=port number(default value is 6379)
This original article is the following that is written by me. This article was translated from Japanese to English.
Top comments (0)