skip to Main Content

I’m trying to connect to a remote machine which has docker installed. I want to exec into the docker container and connect to database and then fetch a table data using java.

Following are my commands that i’m trying to execute.

docker exec it containerID – to login to docker container
cqlsh -u username -p password — to connect to cassandra DB
use keyspace; —to connect to cassandra keyspace
desc tables; — to view the tables that are available in keyspace.

Following is the Java code that I’m trying. Can someone let me know if this approach is correct or what should i do to make this code work. I’m completely new to java code.

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ExecuteanyCommands {

    public static void main(String[] args) throws JSchException, InterruptedException, IOException {

            //JSch
            JSch jsch = new JSch();
            Session session = jsch.getSession("cambi", "10.10.96.20", 22);
            session.setPassword("axone");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            
            
            Channel channel = session.openChannel("exec");
            
            InputStream in = channel.getInputStream();
            ((ChannelExec) channel).setCommand("docker exec -it containerID; cqlsh -u username -p password; use keyspace; desc tables;");
            
            channel.connect();
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            
            String line;
            
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            channel.disconnect();
            session.disconnect();
    }

}

2

Answers


  1. If you want to connect to a container from a remote machine over SSH, then the way to do it is to define an SSH tunnel, external to your Java program.

    In addition, the idea of interacting with Cassandra by running cqlsh on the host is very unusual.
    It’s better to use the official Cassandra Java driver for that purpose.

    To summarize:

    1. Create an SSH tunnel between the client and the docker host
    2. Write a Java program that uses the Java Driver to query Cassandra
    Login or Signup to reply.
  2. I echo Jonathan Jacobson’s point that your method isn’t the correct. Running cqlsh which itself is an app/client to retrieve data from your Cassandra tables is incorrect.

    You need to instead use one of the available Cassandra drivers to connect to your cluster. In your case, it would be the Java driver for Apache Cassandra.

    On the Astra DB docs site, there’s a fully working Java code example for connecting to a cluster. Here’s a stripped down version that you can use:

    import com.datastax.oss.driver.api.core.CqlSession;
    import com.datastax.oss.driver.api.core.cql.ResultSet;
    import com.datastax.oss.driver.api.core.cql.Row;
    
    public class ConnectDatabase {
    
      public static void main(String[] args) {
        try (CqlSession session = CqlSession.builder()
            .withAuthCredentials("your_username","your_password")
            .build()) {
              // select the release_version from the system.local table
              ResultSet rs = session.execute("SELECT release_version FROM system.local");
              Row row = rs.one();
              // print the results to the console
              if (row != null) {
                System.out.println(row.getString("release_version"));
              } else {
                System.out.println("An error occurred.");
              }
        }
        System.exit(0);
      }
    }
    

    You’ll need to get a copy of the example pom.xml file to compile the app. You can get more information about the Java driver here.

    Note that you will need to expose the ports in Docker so that Cassandra is accessible from outside the container. For example, map the CQL port with -p 9042:9042.

    If you’re new to Cassandra, I recommend having a look at datastax.com/dev which has lots of free hands-on interactive learning resources. In particular, the Cassandra Fundamentals learning series lets you learn the basic concepts quickly.

    For what it’s worth, you can also use the Stargate.io data platform. It allows you to connect to a Cassandra cluster using APIs you’re already familiar with. It is fully open-source so it’s free to use. Here are links to the Stargate tutorials on datastax.com/dev: REST API, Document API, GraphQL API, and more recently gRPC API.

    Finally, we also run live workshops for free to teach developers how to build apps for Cassandra. We provide all the materials including all the source code for fully working apps plus coding environments on the cloud so there’s nothing for you to install. There are 2-3 workshops every week and details are at datastax.com/workshops. Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search