Redis 容器不与 expressJs 应用程序连接

Redis container doesn't connect with expressJs application

我想将我的简单 expressJs 应用程序连接到 Redis 容器。但它没有与 redis 容器连接。在这里,我使用 redis:alpine 图像来构建容器。

kasun@Kasuns-MacBook-Air ~ % docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
redis        alpine    9dcd83a87127   3 weeks ago   36.5MB
alpine       latest    3fb3c9af89a9   7 weeks ago   5.32MB
kasun@Kasuns-MacBook-Air ~ % 

我已经运行一个这样的容器并且绑定了本地机器的3307端口

kasun@Kasuns-MacBook-Air ~ % docker run -dt --name redis_cache -p3307:6379 9dcd83a87127
8f44169e8c73938845319463c83f63048c5051bcbbfca7809a1300446b415ae3
kasun@Kasuns-MacBook-Air ~ % 

显示容器 运行ning 是这样的

kasun@Kasuns-MacBook-Air ~ % docker ps
CONTAINER ID   IMAGE          COMMAND                  CREATED          STATUS          PORTS                    NAMES
8f44169e8c73   9dcd83a87127   "docker-entrypoint.s…"   56 seconds ago   Up 55 seconds   0.0.0.0:3307->6379/tcp   redis_cache
kasun@Kasuns-MacBook-Air ~ % 

expressJs代码(server.js文件)

const express = require('express');
const app = express();
const redis = require('redis');

const redisClient = redis.createClient(3307, '0.0.0.0');

redisClient.on('connect', () => {
    console.log("Redis connected");
})

redisClient.on('error', () => {
    console.log("Error");
})

app.listen(8080, () => {
    console.log('listening on port 8080');
})

但是当我启动 express 应用程序时,它没有连接到 Redis 容器。

kasun@Kasuns-MacBook-Air test % npm run test

> test@1.0.0 test
> nodemon server.js

[nodemon] 2.0.16
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
listening on port 8080

我该如何解决这个问题?

将 0.0.0.0 更改为本地主机或 127.0.0.1

试试这个方法

const redisClient = redis.createClient(3307, 'localhost');

这段代码是我用的,你可以试试这个

const express = require('express');
const app = express();
const redis = require('redis');

const redisClient = redis.createClient({
    url: 'redis://127.0.0.1:3307'
});

 const redisConnect = async () => {
     try {
         await redisClient.connect()
        console.log('Redis Connected');
     } catch (error) {
         console.log(error)
     }
}

redisConnect()

app.listen(8080, () => {
    console.log('listening on port 8080');
})