Goldi Pandey
Goldi Pandey

Reputation: 61

When connecting cassandra hosted on docker container with nodejs getting NoHostAvailableError: No host could be resolved

I set up the Cassandra container by running the following commands: This will pull the Cassandra docker image from the docker hub and start up a container with Cassandra

  1. docker network create cassandra-net
  2. docker run --name my-cassandra --network cassandra-net -d cassandra:latest
  3. docker run --name my-cassandra-1 --network cassandra-net -d -e CASSANDRA_SEEDS=my-cassandra cassandra:latest
  4. docker run -it --rm --network cassandra-net cassandra:latest cqlsh my-cassandra

Then created a keyspace

CREATE KEYSPACE user_keyspace WITH REPLICATION={'class': 'SimpleStrategy', 'replication_factor': 3};

Which has a user table in it.

My node.js code is

const cassandra = require('cassandra-driver');
var contactPoints = ['my-cassandra:9042'];
const client = new cassandra.Client({
    contactPoints: contactPoints,
    localDataCenter: 'datacenter1',
    keyspace: 'user_keyspace'
});

client.connect(function (err) {
    if (err) {
        console.log('Error in connnection: ', err); return;
    }
    console.log('Cassandra connected');
});

There was an error when connecting

NoHostAvailableError: No host could be resolved at ControlConnection.init (/app/node_modules/cassandra-driver/lib/control-connection.js:203:13) at async Client._connect (/app/node_modules/cassandra-driver/lib/client.js:513:5) { name: 'NoHostAvailableError', info: 'Represents an error when a query cannot be performed because no host is available or could be reached by the driver.', message: 'No host could be resolved', innerErrors: {}

I don't have much experience with Cassandra or Docker, so I'm not sure why my app is not connecting to the DB, perhaps something with the ports not being open to incoming requests, but I don't know how I would check that or change it.

Upvotes: 2

Views: 1828

Answers (1)

jorgebg
jorgebg

Reputation: 6600

The driver will try to resolve the host names used as contact points. The contact points expect a host name or an IP address.

In your case, instead of using my-cassandra which is user defined network name, use the IP address:

const contactPoints = ['127.0.0.1'];

On the docker run, you could use bridged/host network or use -P or -p 9042:9042:

docker run -it --rm -P cassandra:latest cqlsh my-cassandra

Upvotes: 2

Related Questions