MySQL Ubuntu

To install MySQL, secure it, and create a new database on an Ubuntu 22.04 VPS, follow these steps:

Install MySQL

Step 1: Install MySQL

  1. Update your package index:

    sudo apt update
  2. Install MySQL server:

    sudo apt install mysql-server
  3. Start MySQL service and enable it to start on boot:

    sudo systemctl start mysql
    sudo systemctl enable mysql

Step 2: Secure MySQL

  1. Run the security script:

    sudo mysql_secure_installation

    During the execution of this script, you will be prompted to:

    • Set the root password.
    • Remove anonymous users.
    • Disallow root login remotely.
    • Remove test database and access to it.
    • Reload privilege tables.

    Follow the prompts and provide appropriate responses to secure your installation.

Step 3: Create a New Database and User

  1. Log in to MySQL as root:

    sudo mysql -u root -p
  2. Create a new database:

    CREATE DATABASE your_database_name;
  3. Create a new user and grant privileges:

    CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'your_password';
    GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';
    FLUSH PRIVILEGES;
  4. Exit MySQL:

    EXIT;

Step 4: Obtain Connection Credentials

The connection credentials for your new database will be:

  • Host: localhost
  • Database Name: your_database_name
  • Username: your_username
  • Password: your_password

Example of Using the Connection Credentials

If you're using a MySQL client or connecting from a script, you can use the credentials like this:

mysql -u your_username -p -h localhost your_database_name

Or in a configuration file for a web application:

database:
  host: localhost
  name: your_database_name
  user: your_username
  password: your_password

This should set up and secure MySQL on your Ubuntu VPS and provide you with the necessary credentials to connect to your new database.

Allow Remote Connection

To access your MySQL database from outside (i.e., over the internet), you need to make several configurations to ensure the database is accessible and secure. Here are the steps:

Step 1: Configure MySQL to Allow Remote Connections

  1. Edit the MySQL configuration file:

    sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
  2. Find the bind-address directive and change its value:

    bind-address = 0.0.0.0

    This will allow MySQL to listen on all interfaces.

  3. Save the file and exit the editor.

  4. Restart MySQL service:

    sudo systemctl restart mysql

Step 2: Create a MySQL User for Remote Access

  1. Log in to MySQL as root:

    sudo mysql -u root -p
  2. Create a new user with remote access privileges:

    CREATE USER 'remote_user'@'%' IDENTIFIED BY 'your_password';
    GRANT ALL PRIVILEGES ON your_database_name.* TO 'remote_user'@'%';
    FLUSH PRIVILEGES;
  3. Exit MySQL:

    EXIT;

Step 3: Configure Your Firewall

  1. Allow MySQL port (3306) through the firewall:

    sudo ufw allow 3306/tcp
  2. Reload the firewall rules to apply the changes:

    sudo ufw reload

Step 4: Secure Your Remote Connection

While opening MySQL to remote connections, it's crucial to secure the connection to avoid unauthorized access:

  1. Use strong passwords for your MySQL users.
  2. Consider using SSL/TLS to encrypt the connection.
  3. Restrict access by IP address if possible.

Step 5: Obtain Your Server's Public IP Address

  1. Find your VPS's public IP address:
    curl ifconfig.me

Step 6: Connect to MySQL Remotely

Now you can connect to your MySQL database from a remote machine using a MySQL client:

mysql -u remote_user -p -h your_server_ip your_database_name

Replace your_server_ip with the public IP address of your VPS.

Example Configuration for a Web Application

If you want to connect to the MySQL database from a web application, use the following configuration:

database:
  host: your_server_ip
  name: your_database_name
  user: remote_user
  password: your_password
  port: 3306

By following these steps, you will make your MySQL database accessible from outside your VPS, while also taking necessary security precautions.

Backpup Database

To set up a daily backup system for your MySQL database on a particular time, you can use a combination of MySQL's mysqldump utility and a cron job to automate the backup process. Here are the steps:

Step 1: Create a Backup Script

  1. Create a script to perform the backup:

    sudo nano /usr/local/bin/mysql_backup.sh
  2. Add the following content to the script:

    #!/bin/bash
    
    # Variables
    BACKUP_DIR="/path/to/backup/directory"
    MYSQL_USER="your_username"
    MYSQL_PASSWORD="your_password"
    MYSQL_DATABASE="your_database_name"
    DATE=$(date +%F_%T)
    
    # Create backup directory if it does not exist
    mkdir -p $BACKUP_DIR
    
    # Perform the backup
    mysqldump -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE > $BACKUP_DIR/$MYSQL_DATABASE-$DATE.sql
    
    # Delete backups older than 7 days
    find $BACKUP_DIR -type f -name "*.sql" -mtime +7 -exec rm {} \;

    Replace /path/to/backup/directory, your_username, your_password, and your_database_name with your actual values.

  3. Save the script and exit the editor.

  4. Make the script executable:

    sudo chmod +x /usr/local/bin/mysql_backup.sh

Step 2: Schedule the Backup Script with Cron

  1. Edit the crontab file:

    sudo crontab -e
  2. Add a cron job to run the backup script at a specific time every day:

    # Minute   Hour   Day of Month   Month   Day of Week   Command
    0         2      *              *       *             /usr/local/bin/mysql_backup.sh

    This example schedules the backup script to run every day at 2:00 AM. Adjust the timing as needed.

  3. Save the crontab file and exit the editor.

Step 3: Verify the Setup

  1. Check the backup directory to ensure the script is running correctly and creating backups:

    ls /path/to/backup/directory
  2. Check the cron logs if you encounter any issues:

    sudo grep CRON /var/log/syslog

Additional Tips

  • Secure the backup script and directory: Ensure that the script and backup directory have appropriate permissions to prevent unauthorized access.
  • Monitor disk space: Regularly monitor the disk space on your VPS to ensure that it does not run out due to accumulated backups.
  • Test restore process: Periodically test the restore process to ensure that your backups are valid and can be used in case of data loss.

By following these steps, you will set up an automated daily backup system for your MySQL database on your Ubuntu VPS.

Import .sql

To import a .sql file from your local PC to the newly created MySQL database on your VPS, follow these steps:

Step 1: Transfer the .sql File to the VPS

  1. Use scp (Secure Copy Protocol) to transfer the file to your VPS:
    scp /path/to/your/local/file.sql your_username@your_server_ip:/path/to/remote/directory/
    inside docker container
    docker exec -i 8524f7535885 mysql -u redmine -predmine@12345 redmine < /c/Users/Dell/Downloads/backup.sql
    in case of permission issue:
    sudo chmod 777 /home/mysql/files
    Replace /path/to/your/local/file.sql with the path to your local .sql file, your_username with your VPS username, your_server_ip with the public IP address of your VPS, and /path/to/remote/directory/ with the desired directory on your VPS where you want to upload the file.

Step 2: Import the .sql File into MySQL

  1. SSH into your VPS:

    ssh your_username@your_server_ip
  2. Navigate to the directory where you uploaded the .sql file:

    cd /path/to/remote/directory/
  3. Import the .sql file into your MySQL database:

    mysql -u your_username -p your_database_name < file.sql

    Replace your_username with your MySQL username, your_database_name with the name of the database you created, and file.sql with the name of the .sql file you transferred.

Example

Let's assume:

  • The .sql file on your local PC is located at ~/backups/my_database_backup.sql.
  • Your VPS username is vps_user.
  • Your VPS IP address is 192.168.1.100.
  • The database name on your VPS is my_database.
  • The MySQL username is db_user.

Here's how you'd do it:

  1. Transfer the .sql file to the VPS:

    scp ~/backups/my_database_backup.sql vps_user@192.168.1.100:/home/vps_user/
  2. SSH into your VPS:

    ssh vps_user@192.168.1.100
  3. Navigate to the directory where you uploaded the file:

    cd /home/vps_user/
  4. Import the .sql file into the MySQL database:

    mysql -u db_user -p my_database < my_database_backup.sql

Additional Tips

  • Ensure the .sql file has the correct SQL statements for creating tables, inserting data, etc.
  • If the database is large, consider using a compressed file and decompressing it on the server to speed up the transfer.

By following these steps, you can successfully import a .sql file from your local PC to the MySQL database on your VPS.

Secure Database

Securing remote connections to your MySQL database is essential to prevent unauthorized access and protect your data. Here’s how you can implement these security measures:

1. Use Strong Passwords

Ensure that all MySQL user accounts, especially those with remote access, have strong, complex passwords.

Tips for Strong Passwords:

  • Use a mix of uppercase and lowercase letters, numbers, and special characters.
  • Make the password at least 12-16 characters long.
  • Avoid using common words or easily guessable information.

Example:

CREATE USER 'remote_user'@'%' IDENTIFIED BY 'StroNgP@ssw0rd123!';

2. Use SSL/TLS to Encrypt Connections

Encrypting MySQL connections with SSL/TLS ensures that data transmitted between the client and server is secure.

Step-by-Step Guide to Enable SSL/TLS:

  1. Generate SSL Certificates: You need to create a Certificate Authority (CA), server certificate, and client certificate. You can use openssl to generate these.

    mkdir /etc/mysql/ssl
    cd /etc/mysql/ssl
    
    # Generate CA certificate
    openssl genrsa 2048 > ca-key.pem
    openssl req -new -x509 -nodes -days 3600 -key ca-key.pem -out ca-cert.pem
    
    # Generate server certificate
    openssl req -newkey rsa:2048 -days 3600 -nodes -keyout server-key.pem -out server-req.pem
    openssl x509 -req -in server-req.pem -days 3600 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem
    
    # Generate client certificate
    openssl req -newkey rsa:2048 -days 3600 -nodes -keyout client-key.pem -out client-req.pem
    openssl x509 -req -in client-req.pem -days 3600 -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out client-cert.pem
    
    # Secure the keys
    chmod 600 *.pem
  2. Configure MySQL to Use SSL: Edit the MySQL configuration file to include the paths to your certificates.

    sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

    Add the following lines under the [mysqld] section:

    [mysqld]
    ssl-ca=/etc/mysql/ssl/ca-cert.pem
    ssl-cert=/etc/mysql/ssl/server-cert.pem
    ssl-key=/etc/mysql/ssl/server-key.pem

    Save the file and restart MySQL:

    sudo systemctl restart mysql
  3. Require SSL for Remote User: Modify the user to require SSL connections.

    ALTER USER 'remote_user'@'%' REQUIRE SSL;
  4. Client-Side Configuration: When connecting remotely, specify the client certificates:

    mysql -u remote_user -p -h your_server_ip --ssl-ca=/path/to/ca-cert.pem --ssl-cert=/path/to/client-cert.pem --ssl-key=/path/to/client-key.pem

3. Restrict Access by IP Address

Limit remote access to specific IP addresses to reduce the risk of unauthorized access.

Step-by-Step Guide to Restrict IP Access:

  1. Grant Access to a Specific IP Address: Modify the MySQL user to allow connections only from a specific IP address or subnet.

    CREATE USER 'remote_user'@'specific_ip_address' IDENTIFIED BY 'StroNgP@ssw0rd123!';
    GRANT ALL PRIVILEGES ON your_database_name.* TO 'remote_user'@'specific_ip_address';
    FLUSH PRIVILEGES;

    Replace specific_ip_address with the actual IP address you want to allow.

  2. Use Firewall Rules: Configure your server's firewall to allow MySQL connections only from specific IP addresses.

    sudo ufw allow from specific_ip_address to any port 3306

    Replace specific_ip_address with the IP address you want to allow.

  3. Close the Port for General Public: Ensure that port 3306 is not open to the world by default.

    sudo ufw deny 3306

By implementing these security measures, you can significantly reduce the risk of unauthorized access and ensure that your MySQL remote connections are secure.

Permission issue

The error you're encountering, Permission denied, suggests that the directory you are trying to write the ca-key.pem file to does not allow write access for your user, even when using sudo.

To resolve this:

  1. Ensure Proper Permissions:

    • Check if you have the necessary permissions to write to the /etc/mysql/ssl/ directory.
    • Run the following command to change the permissions for the directory:
      sudo chmod 755 /etc/mysql/ssl
    • Alternatively, check ownership of the directory:
      ls -ld /etc/mysql/ssl
      If necessary, change ownership:
      sudo chown $USER:$USER /etc/mysql/ssl
  2. Run Command in Home Directory: If you're still facing permission issues, try generating the key in your home directory first and then move it to the desired location:

    openssl genrsa 2048 > ~/ca-key.pem
    sudo mv ~/ca-key.pem /etc/mysql/ssl/

File Transfer

from vps to local

 scp -i ~/.ssh/id_rsa cms@207.244.227.206:/home/cms/gc.sql D:\Arafat

from local to vps

scp -i ~/.ssh/id_rsa -P 2222 D:\Arafat\gc.sql cms@194.163.155.186:/root/

vps to R2 storage

 aws s3 cp /opt/backup_scripts/backups/files_backup_2024-07-31_09-04-01.tar.gz s3://redmine-files/files_backup_2024-07-31_09-04-01.tar.gz --endpoint-url https://e3946219b1798670a9fee28610635a78.r2.cloudflarestorage.com