Devorein
Devorein

Reputation: 1319

Cannot connect to `redis-server` running in wsl2 using `ioredis` package due to ECONNREFUSED error

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.

Upvotes: 1

Views: 5162

Answers (3)

deadcoder0904
deadcoder0904

Reputation: 8693

You can also find your ip using this simple command where redis-server is your container name that you get when you run docker ps in the terminal:

docker inspect --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' redis-server

This should give you the same ip as the recommended answer :)

Upvotes: 0

Devorein
Devorein

Reputation: 1319

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

Upvotes: 1

Devorein
Devorein

Reputation: 1319

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.

Upvotes: 3

Related Questions