'NatsError: Could not connect to server: Error: connect ECONNREFUSED Error

I created a NATS Streaming Server on my Kubernetes cluster.

And "Kubectl get services" output like that:

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)             AGE
api-gateway-srv      NodePort    10.106.100.181   <none>        8080:30440/TCP      16m
auth-mongo-srv       ClusterIP   10.101.9.123     <none>        27017/TCP           16m
auth-srv             ClusterIP   10.102.227.91    <none>        3000/TCP            16m
radio-srv            ClusterIP   10.111.20.153    <none>        3003/TCP            16m
kubernetes           ClusterIP   10.96.0.1        <none>        443/TCP             3d13h
tv-srv               ClusterIP   10.111.88.212    <none>        3001/TCP            16m
nats-srv             ClusterIP   10.105.230.126   <none>        4222/TCP,8222/TCP   16m

On on my nats-publisher.js file like that:

const nats = require('node-nats-streaming');

const stan = nats.connect('natsserver', 'nats-cli1', {
    url: 'nats://nats-srv:4222'
});
stan.on('connect', () => {
    console.log('Links publisher connected to NATS')
}, (err, guid) => {
    if(err) console.log(err)
    else console.log(guid)
})  

And I get :

NatsError: Could not connect to server: Error: connect ECONNREFUSED 10.105.230.126:4222

But on the another service I used same connection codes for nats connection. And this service can connect successfully nats server.

Why I getting this error? Same code run as correctly on the another service but this code How can crash from this service?



Solution 1:[1]

When you use command kubectl port-forward [pod_name] 4222:4222

You can see next lines at the terminal:

Forwarding from 127.0.0.1:4222 -> 4222
Forwarding from [::1]:4222 -> 4222

Use 127.0.0.1:4222 in config

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1