nats-io / k8s

NATS on Kubernetes with Helm Charts
Apache License 2.0
446 stars 302 forks source link

Cant connect from Node.js application #182

Closed MohammedAl-Mahdawi closed 3 years ago

MohammedAl-Mahdawi commented 3 years ago

Hi,

I installed the chart with helm install nats -f values.yaml nats/nats and the values.yaml file is:

stan:
  image: nats-streaming:0.18.0
  replicas: 3
  clusterID: microservices
  logging:
    debug: false
    trace: false

store:
  type: file

  cluster:
    enabled: true

  #
  # File storage settings.
  #
  file:
    path: /data/stan/store

  # Volume for each pod.
  volume:
    enabled: true

    # Mount path for the volume.
    mount: /data/stan

I tried to connect using Node.js application with "node-nats-streaming": "^0.2.6" npm package using the following URLs and non of them worked!

http://nats-0.default.svc.cluster.local:4222
nats://nats.default.svc.cluster.local:4222
http://nats-0.default.svc.cluster.local:4222
nats://nats-0.nats.default.svc.cluster.local:4222
http://nats-0.nats.default.svc.cluster.local:4222
http://nats:4222
http://nats-0.nats:4222
nats://nats:4222

The Node.js code:

nats-wrapper.js file

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

class NatsWrapper {
  _client

  get client() {
    if (!this._client) {
      throw new Error('Cannot access NATS client before connecting');
    }

    return this._client;
  }

  connect(clusterId, clientId, url) {
    this._client = nats.connect(clusterId, clientId, { url });

    return new Promise((resolve, reject) => {
      this.client.on('connect', () => {
        console.log('Connected to NATS');
        resolve();
      });
      this.client.on('error', (err) => {
        reject(err);
      });
    });
  }
}

module.exports = new NatsWrapper();

index.js file

const natsWrapper = require('./nats-wrapper')
const { randomBytes } = require('crypto')

;(async () => {
  await natsWrapper.connect(
    'microservices',
    randomBytes(4).toString('hex'),
    process.env.NATS_URL || 'http://localhost:4222'
  )

  natsWrapper.client.on('close', () => {
    console.log('NATS connection closed!')
    process.exit()
  })
  process.on('SIGINT', () => natsWrapper.client.close())
  process.on('SIGTERM', () => natsWrapper.client.close())

  require('./listener')
  require('./publisher')
})()
wallyqs commented 3 years ago

Try with stan instead of nats:

helm install nats -f values.yaml nats/stan
MohammedAl-Mahdawi commented 3 years ago

Thank you so much! Now I can connect with http://nats:4222