Connecting to a database in a MySQL cluster
You can connect to Managed Service for MySQL cluster hosts:
-
Over the internet, if you configured public access for the appropriate host. You can only connect to such hosts over an SSL connection.
-
From Nebius AI virtual machines located in the same cloud network. If there is no public access to a host, using SSL for connections from such virtual machines is not required.
Warning
If only some cluster hosts have public access configured, the master may not be accessible from the internet when it changes automatically.
The maximum number of connections is defined by the Max connections setting that depends on the host class.
For more information, see Network and clusters in Managed Service for MySQL.
Getting an SSL certificate
MySQL hosts with public access only support encrypted connections. To use them, get an SSL certificate:
mkdir -p ~/.mysql && \
wget "https://storage.nemax.nebius.cloud/certs/CA.pem" \
--output-document ~/.mysql/root.crt && \
chmod 0600 ~/.mysql/root.crt
The certificate is saved to the ~/.mysql/root.crt
file.
mkdir $HOME\.mysql; curl.exe -o $HOME\.mysql\root.crt https://storage.nemax.nebius.cloud/certs/CA.pem
The certificate is saved to the $HOME\.mysql\root.crt
file.
To use graphical IDEs, save a certificate
Special FQDNs
Just like usual FQDNs, which can be requested with a list of cluster hosts, Managed Service for MySQL provides a number of special FQDNs, which can also be used when connecting to a cluster.
Warning
If, when the master host is changed automatically, a host with no public access becomes a new master or the most recent replica, you will not be able to access them from the internet. To avoid this, enable public access for all cluster hosts.
Current master
Such FQDN as c-<cluster ID>.rw.mdb.nemax.nebius.cloud
always points to the current cluster master host. You can get the cluster ID with a list of clusters in the folder.
When connecting to this FQDN, both read and write operations are allowed.
Example of connecting to a master host for a cluster with the ID c9qash3nb1v9ulc8j9nm
:
mysql --host=c-c9qash3nb1v9ulc8j9nm.rw.mdb.nemax.nebius.cloud \
--port=3306 \
--ssl-ca=~/.mysql/root.crt \
--ssl-mode=VERIFY_IDENTITY \
--user=<username> \
--password \
<DB name>
Most recent replica
Such FQDN as c-<cluster ID>.ro.mdb.nemax.nebius.cloud
points to the most recent replica, i.e., the one most up-to-date with the master host. The cluster ID can be requested with a list of clusters in the folder.
Specifics:
- When connecting to this FQDN, only read operations are allowed.
- If there are no active replicas in a cluster, you cannot connect to this FQDN, as the respective DNS CNAME record will point to a
null
object.
Here is an example of connecting to the most recent replica for a cluster with the c9qash3nb1v9ulc8j9nm
ID:
mysql --host=c-c9qash3nb1v9ulc8j9nm.ro.mdb.nemax.nebius.cloud \
--port=3306 \
--ssl-ca=~/.mysql/root.crt \
--ssl-mode=VERIFY_IDENTITY \
--user=<username> \
--password \
<DB name>
Connecting to cluster hosts from graphical IDEs
Connections were tested in the following environment:
- Ubuntu 20.04, DBeaver:
22.2.4
. - MacOS Big Sur 11.3:
- JetBrains DataGrip:
2021.1
. - DBeaver Community:
21.0.5
.
- JetBrains DataGrip:
- Windows 10 Pro 21H1 with SQL Server Management Studio
18.9.1
.
You can only use graphical IDEs to connect to public cluster hosts using SSL certificates.
To avoid connection errors, save the certificate
- Create a data source:
- Select File → New → Data Source → MySQL.
- On the General tab:
- Specify the connection parameters:
- Host:
<host name>.mdb.nemax.nebius.cloud
or a special FQDN. - Port:
3306
. - User, Password: DB user's name and password.
- Database: Name of the DB to connect to.
- Host:
- Click Download to download the connection driver.
- Specify the connection parameters:
- On the SSH/SSL tab:
- Enable the Use SSL setting.
- In the CA file field, specify the path to the file with an SSL certificate for the connection.
- To test the connection, click Test Connection. If the connection is successful, you'll see the connection status and information about the DBMS and driver.
- Click OK to save the data source.
- Create a new DB connection:
- In the Database menu, select New connection.
- Select MySQL from the DB list.
- Click Next.
- Specify the connection parameters on the Main tab:
- Server:
<host name>.mdb.nemax.nebius.cloud
or a special FQDN. - Port:
3306
. - Database: DB you want to connect to.
- Username, Password: DB username and password.
- Server:
- On the SSL tab:
- Enable Use SSL.
- In the Root certificate field, specify the path to the saved SSL certificate file.
- Under Advanced:
- Enable Require SSL.
- Disable Verify server certificate.
- Click Test connection ... to test the connection. If the connection is successful, you'll see the connection status and information about the DBMS and driver.
- Click Ready to save the database connection settings.
Connecting from a Docker container
You can only use Docker containers to connect to public cluster hosts using SSL certificates.
To connect to a Managed Service for MySQL cluster, add the following lines to the Dockerfile:
RUN apt-get update && \
apt-get install wget mysql-client --yes && \
mkdir -p ~/.mysql && \
wget "https://storage.nemax.nebius.cloud/certs/CA.pem" \
--output-document ~/.mysql/root.crt && \
chmod 0600 ~/.mysql/root.crt
Sample connection strings
The Linux examples were tested in the following environment:
- A virtual machine running Ubuntu 20.04 LTS.
- Bash:
5.0.16
. - Python:
3.8.2
; pip3:20.0.2
. - PHP:
7.4.3
. - OpenJDK:
11.0.8
; Maven:3.6.3
. - Node.JS:
10.19.0
, npm:6.14.4
. - Go:
1.13.8
. - Ruby:
2.7.0p0
. - unixODBC:
2.3.6
.
The Windows examples were tested in the following environment:
- A local machine with Windows 10 Pro build
19042.1052
. - PowerShell:
5.1.19041
. - cURL:
7.55.1 WinSSL
.
You can only connect to publicly accessible MySQL hosts using an SSL certificate.
Bash
Before connecting, install the mysql
utility:
sudo apt update && sudo apt install --yes mysql-client
mysql --host=<MySQL host name>.mdb.nemax.nebius.cloud \
--port=3306 \
--ssl-ca=~/.mysql/root.crt \
--ssl-mode=VERIFY_IDENTITY \
--user=<username> \
--password \
<DB name>
mysql --host=<MySQL host name>.mdb.nemax.nebius.cloud \
--port=3306 \
--ssl-mode=DISABLED \
--user=<username> \
--password \
<DB name>
When running any command, enter the DB user password.
Once connected to the DBMS, run SELECT @@version;
.
If the connection to the cluster and the test query are successful, the MySQL version is output.
Go
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes golang git && \
go get github.com/go-sql-driver/mysql
connect.go
package main
import (
"io/ioutil"
"crypto/tls"
"crypto/x509"
"database/sql"
"fmt"
"github.com/go-sql-driver/mysql"
)
const (
host = "<MySQL host name>.mdb.nemax.nebius.cloud"
port = 3306
user = "<username>"
password = "<user password>"
dbname = "<DB name>"
)
func main() {
rootCertPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("/home/<home directory>/.mysql/root.crt")
if err != nil {
panic(err)
}
if ok := rootCertPool.AppendCertsFromPEM(pem); !ok {
panic("Failed to append PEM.")
}
mysql.RegisterTLSConfig("custom", &tls.Config{
RootCAs: rootCertPool,
})
mysqlInfo := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?tls=custom",
user, password, host, port, dbname)
conn, err := sql.Open("mysql", mysqlInfo)
if err != nil {
panic(err)
}
defer conn.Close()
q, err := conn.Query("SELECT version()")
if err != nil {
panic(err)
}
var result string
for q.Next() {
q.Scan(&result)
fmt.Println(result)
}
}
For this connection method, the code must include the full path to the root.crt
certificate for MySQL in the ca
variable.
connect.go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
const (
host = "<MySQL host name>.mdb.nemax.nebius.cloud"
port = 3306
user = "<username>"
password = "<user password>"
dbname = "<DB name>"
)
func main() {
mysqlInfo := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s",
user, password, host, port, dbname)
conn, err := sql.Open("mysql", mysqlInfo)
if err != nil {
panic(err)
}
defer conn.Close()
q, err := conn.Query("SELECT version()")
if err != nil {
panic(err)
}
var result string
for q.Next() {
q.Scan(&result)
fmt.Println(result)
}
}
Connecting:
go run connect.go
If the connection to the cluster and the test query are successful, the MySQL version is output.
Java
Before connecting:
-
Install the dependencies:
sudo apt update && sudo apt install --yes default-jdk maven
-
Add the SSL certificate to the Java trusted certificate store (Java Key Store) so that the MySQL driver can use this certificate for secure connections to the cluster hosts. Make sure to set the password for additional storage security using the
-storepass
parameter:cd ~/.mysql && \ sudo keytool -importcert \ -alias NebiusAICA \ -file root.crt \ -keystore NebiusTrustStore \ -storepass <certificate store password, at least 6 characters> \ --noprompt
-
Create a folder for the Maven project:
cd ~/ && mkdir -p project/src/java/com/example && cd project/
-
Create a configuration file for Maven:
pom.xml<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>app</artifactId> <packaging>jar</packaging> <version>0.1.0</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.21</version> </dependency> </dependencies> <build> <finalName>${project.artifactId}-${project.version}</finalName> <sourceDirectory>src</sourceDirectory> <resources> <resource> <directory>src</directory> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <goals> <goal>attached</goal> </goals> <phase>package</phase> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.1.0</version> <configuration> <archive> <manifest> <mainClass>com.example.App</mainClass> </manifest> </archive> </configuration> </plugin> </plugins> </build> </project>
You can check the current
mysql-connector-java
version on the project page in the Maven repository .
src/java/com/example/App.java
package com.example;
import java.sql.*;
public class App {
public static void main(String[] args) {
String DB_URL = "jdbc:mysql://<MySQL host name>.mdb.nemax.nebius.cloud:3306/<DB name>?useSSL=true";
String DB_USER = "<username>";
String DB_PASS = "<user password>";
System.setProperty("javax.net.ssl.trustStore", "/home/<home directory>/.mysql/NebiusTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "<certificate store password>");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
ResultSet q = conn.createStatement().executeQuery("SELECT version()");
if(q.next()) {System.out.println(q.getString(1));}
conn.close();
}
catch(Exception ex) {ex.printStackTrace();}
}
}
This code must specify the full path to the NebiusTrustStore
certificate store for the MySQL driver in the javax.net.ssl.trustStore
property.
src/java/com/example/App.java
package com.example;
import java.sql.*;
public class App {
public static void main(String[] args) {
String DB_URL = "jdbc:mysql://<MySQL host name>.mdb.nemax.nebius.cloud:3306/<DB name>?useSSL=false";
String DB_USER = "<username>";
String DB_PASS = "<user password>";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
ResultSet q = conn.createStatement().executeQuery("SELECT version()");
if(q.next()) {System.out.println(q.getString(1));}
conn.close();
}
catch(Exception ex) {ex.printStackTrace();}
}
}
Connecting:
mvn clean package && \
java -jar target/app-0.1.0-jar-with-dependencies.jar
If the connection to the cluster and the test query are successful, the MySQL version is output.
Node.js
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes nodejs npm && \
npm install mysql2
app.js
"use strict"
const fs = require('fs');
const mysql = require('mysql2');
const config = {
host : '<MySQL host name>.mdb.nemax.nebius.cloud',
port : 3306,
user : '<username>',
password : '<user password>',
database : '<DB name>',
ssl: {
rejectUnauthorized: true,
ca: fs.readFileSync('/home/<home directory>/.mysql/root.crt').toString(),
},
}
const conn = mysql.createConnection(config)
conn.connect(err => {if (err) throw err})
conn.query('SELECT version()', (err, result, fields) => {
if (err) throw err
console.log(result[0])
conn.end()
})
For this connection method, the code must include the full path to the root.crt
certificate for MySQL in the ca
variable.
app.js
"use strict"
const mysql = require('mysql2');
const config = {
host : '<MySQL host name>.mdb.nemax.nebius.cloud',
port : 3306,
user : '<username>',
password : '<user password>',
database : '<DB name>',
}
const conn = mysql.createConnection(config)
conn.connect(err => {if (err) throw err})
conn.query('SELECT version()', (err, result, fields) => {
if (err) throw err
console.log(result[0])
conn.end()
})
Connecting:
node app.js
If the connection to the cluster and the test query are successful, the MySQL version is output.
ODBC
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes unixodbc && \
wget https://dev.mysql.com/get/Downloads/Connector-ODBC/8.0/mysql-connector-odbc_8.0.21-1ubuntu20.04_amd64.deb && \
sudo dpkg -i mysql-connector-odbc_8.0.21-1ubuntu20.04_amd64.deb
The MySQL Connector/ODBC driver will be registered automatically in /etc/odbcinst.ini
. Current version of the driver: mysql-connector-odbc
Set the connection parameters in the /etc/odbc.ini
file.
odbc.ini
[mysql]
Driver=MySQL ODBC 8.0 Unicode Driver
SERVER=<MySQL host name>.mdb.nemax.nebius.cloud
UID=<username>
PWD=<user password>
DATABASE=<DB name>
PORT=3306
SSLCA=/home/<home directory>/.mysql/root.crt
SSLVERIFY=1
For this connection method, the /etc/odbc.ini
file must include the full path to the root.crt
certificate for MySQL in the SSLCA
parameter.
odbc.ini
[mysql]
Driver=MySQL ODBC 8.0 Unicode Driver
SERVER=<MySQL host name>.mdb.nemax.nebius.cloud
UID=<username>
PWD=<user password>
DATABASE=<DB name>
PORT=3306
Connecting:
isql -v mysql
Once connected to the DBMS, run SELECT @@version;
.
If the connection to the cluster and the test query are successful, the MySQL version is output.
PHP
Before connecting, install the dependencies:
sudo apt update && apt install --yes php php-mysql
connect.php
<?php
$conn = mysqli_init();
$conn->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, true);
$conn->ssl_set(NULL, NULL, '/home/<home directory>/.mysql/root.crt', NULL, NULL);
$conn->real_connect('<MySQL host name>.mdb.nemax.nebius.cloud', '<username>', '<user password>', '<DB name>', 3306, NULL, MYSQLI_CLIENT_SSL);
$q = $conn->query('SELECT version()');
$result = $q->fetch_row();
echo($result[0]);
$q->close();
$conn->close();
?>
For this connection method, the code must include the full path to the root.crt
certificate for MySQL in the ssl_set
method.
connect.php
<?php
$conn = mysqli_init();
$conn->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, false);
$conn->real_connect('<MySQL host name>.mdb.nemax.nebius.cloud', '<username>', '<user password>', '<DB name>', 3306, NULL, NULL);
$q = $conn->query('SELECT version()');
$result = $q->fetch_row();
echo($result[0]);
$q->close();
$conn->close();
?>
Connecting:
php connect.php
If the connection to the cluster and the test query are successful, the MySQL version is output.
PowerShell
Before connecting, downloadMySQL Shell
utility.
mysqlsh --host=<MySQL host name>.mdb.nemax.nebius.cloud `
--port=3306 `
--ssl-ca=<absolute path to certificate file> `
--ssl-mode=VERIFY_IDENTITY `
--user=<username> `
--password `
--database=<DB name> `
--sql
mysqlsh --host=<MySQL host name>.mdb.nemax.nebius.cloud `
--port=3306 `
--ssl-mode=DISABLED `
--user=<username> `
--password `
--database=<DB name>
When running any command, enter the DB user password.
Once connected to the DBMS, run SELECT @@version;
.
If the connection to the cluster and the test query are successful, the MySQL version is output.
Python
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes python3 python3-pip libmysqlclient-dev && \
pip3 install mysqlclient
connect.py
import MySQLdb
conn = MySQLdb.connect(
host="<MySQL host name>.mdb.nemax.nebius.cloud",
port=3306,
db="<DB name>",
user="<username>",
passwd="<user password>",
ssl={'ca': '~/.mysql/root.crt'})
cur = conn.cursor()
cur.execute('SELECT version()')
print(cur.fetchone()[0])
conn.close()
connect.py
import MySQLdb
conn = MySQLdb.connect(
host="<MySQL host name>.mdb.nemax.nebius.cloud",
port=3306,
db="<DB name>",
user="<username>",
passwd="<user password>")
cur = conn.cursor()
cur.execute('SELECT version()')
print(cur.fetchone()[0])
conn.close()
Connecting:
python3 connect.py
If the connection to the cluster and the test query are successful, the MySQL version is output.
Ruby
Before connecting, install the dependencies:
sudo apt update && sudo apt install --yes ruby ruby-mysql2
connect.rb
require "mysql2"
conn = Mysql2::Client.new(
:host => "<MySQL host name>.mdb.nemax.nebius.cloud",
:port => 3306,
:database => "<DB name>",
:username => "<username>",
:password => "<user password>",
:ssl_mode => "verify_identity",
:sslca => "~/.mysql/root.crt")
q = conn.query("SELECT version()")
q.each do |result|
puts result["version()"]
end
conn.close()
connect.rb
require "mysql2"
conn = Mysql2::Client.new(
:host => "<MySQL host name>.mdb.nemax.nebius.cloud",
:port => 3306,
:database => "<DB name>",
:username => "<username>",
:password => "<user password>")
q = conn.query("SELECT version()")
q.each do |result|
puts result["version()"]
end
conn.close()
Connecting:
ruby connect.rb
If the connection to the cluster and the test query are successful, the MySQL version is output.