skip to Main Content

I’m am running my redis-server by building redis in my wsl2 Ubuntu distro. But unfortunately, I’m not able to connect to it using the ioredis package. Here is my code (It’s the same code that ioredis provided):-

const Redis = require("ioredis");
const redis = new Redis({
  port: 6379,
  host: '127.0.0.1'
});

redis.set("foo", "bar");

redis.get("foo", function (err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result); // Promise resolves to "bar"
  }
});

Every time I get the following error

[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1146:16)

I am able to connect to the redis-server using redis-client from my wsl2 terminal, just not from my code. I haven’t changed the default Redis configuration, so I am not sure where this is coming from. Any sort of lead would be really helpful. Thank you.

2

Answers


  1. Chosen as BEST ANSWER

    After several hours of trying out different solutions, I was able to fix the issue. Since redis-server on wsl2 was running on a separate network, accessing it via 127.0.0.1 didn't work. I needed to know the IP address of my wsl2 instance and pass the correct connection details in ioredis constructor.

    1. Type sudo apt install net-tools in your wsl2 terminal
    2. Type ifconfig to get the IP address. It should be in the eth0 inet section.
    3. Copy and paste the IP address when creating the ioredis instance
    const redis = new Redis({
     port: 6379,
     host: '<your-wsl2-ip-here>'
    });
    
    1. Type redis-cli and then turn off protected mode using CONFIG SET protected-mode no.

    Hope that helped.


  2. Another way of solving the above issue would be by loading the default config file redis.conf located in the one level above the redis-server executable, which has the necessary configuration to allow external traffic into the wsl2 process.

    ./redis-server ../redis.conf
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search