Connecting MySQL and Cypress via an SSH tunnel ensures secure data transmission, especially in development and testing environments. The following are specific steps and examples:
Step 1: Create an SSH Tunnel
First, create an SSH tunnel that forwards a local port to the remote MySQL server's port. Assume the remote MySQL server's IP is 192.168.1.100 and the MySQL service port is the default 3306. Use the following command:
bashssh -L 3307:localhost:3306 username@192.168.1.100
This command means:
-L 3307:localhost:3306: Maps local port 3307 to remote port 3306 on the server.username@192.168.1.100: Connects to the server with IP192.168.1.100using the usernameusername.
Step 2: Configure Cypress
In Cypress, you can use any Node.js library that supports MySQL connections, such as mysql or mysql2. First, install the required library:
bashnpm install mysql2
Then, in your Cypress test script, use the following code to connect to the locally mapped port via the SSH tunnel:
javascriptconst mysql = require('mysql2'); const connection = mysql.createConnection({ host: 'localhost', user: 'yourDatabaseUsername', password: 'yourDatabasePassword', database: 'yourDatabaseName', port: 3307 // Note that this is the mapped local port }); connection.connect(err => { if (err) { return console.error('Error: ' + err.message); } console.log('Successfully connected to the database!'); }); // You can then perform SQL queries and other operations
Step 3: Run and Test
After configuring the SSH tunnel and Cypress connection code, run Cypress tests to verify the connection is successful and ensure database operations can be performed.
Example Scenario
Suppose you are developing a web application that needs to access user data in a remote database. With the above setup, you can safely test the web application locally via Cypress without exposing the remote database directly.
The benefit of this method is that data transmission is encrypted, enhancing security, especially when handling sensitive data or working in insecure network environments.
Summary
By establishing an SSH tunnel, you can securely access the remote MySQL database in Cypress tests without directly exposing the database port, providing an additional security layer for development and testing environments.