Salta al contenuto principale

Installare MySQL 8.0 in Debian 12 Bookworm

In questa guida vedremo come effettuare l'installare MySQL in Debian 12 Bookworm con apt, il gestore di pacchetti di default

l'install di MySQL è molto comune nei nostri interventi di Gestione Server Debian, essendo la base per gli stack LAMP (Linux, Apache, MySQL, PHP), LEMP (NginX) e svariati altri, necessari per Web App, CMS ed e-commerce

Aggiungere il mirror ufficiale MySQL

Come primo passaggio scarichiamo il pacchetto di configurazione del repository ufficiale di MySQL

sudo apt update && sudo apt install wget
cd /tmp
wget https://dev.mysql.com/get/mysql-apt-config_0.8.32-1_all.deb

Installiamo il pacchetto scaricato

sudo apt install ./mysql-apt-config_0.8.32-1_all.deb

Durante l'install di MySQL possiamo selezionare la versione desiderata, visualizzando una di queste schermate:

  --------               Configuring mysql-apt-config               --------
  
  │ Which MySQL product do you wish to configure?                           │ 
  │                                                                         │ 
  │         MySQL Server & Cluster (Currently selected:  mysql-8.4-lts)     │ 
  │         MySQL Connectors (Currently selected: Enabled)                  │
Configuring mysql-apt-config
----------------------------
The MySQL APT Repository features MySQL Server along with a variety of components. You may select the desired
products to install and update from the official MySQL Repository, and also select the associated version series.
Select "Ok" to save the configuration, and then execute "apt update" to load the selected package list. This
configuration can be updated later, depending on your needs.
 1. MySQL Server & Cluster (Currently selected: mysql-8.0)  3. Ok
 2. MySQL Connectors (Currently selected: Enabled)
Which MySQL product do you wish to configure? 3

Modifichiamo, nella selezione "MySQL Server & Cluster",  a mysql-8.0 nel primo caso usando frecce e invio, nel secondo utilizzando il numero 1 da tastiera

Se preferisci utilizzare MySQL 8.4, modifica la selezione a mysql-8.4-lts e segui la guida Installare MySQL 8.4 in Debian 12 Bookworm

Installare MySQL in Debian 12 Bookworm

Aggiorniamo la lista dei pacchetti disponibili

sudo apt update

Noteremo delle nuove righe contenenti il nuovo mirror MySQL 8.0 per Debian 12 Bookworm

Get:10 http://repo.mysql.com/apt/debian bookworm/mysql-8.0 Sources [946 B]
Get:11 http://repo.mysql.com/apt/debian bookworm/mysql-apt-config amd64 Packages [566 B]
Get:12 http://repo.mysql.com/apt/debian bookworm/mysql-8.0 amd64 Packages [12.7 kB]
Get:13 http://repo.mysql.com/apt/debian bookworm/mysql-tools amd64 Packages [4129 B]

Procediamo a installare MySQL con questo comando

sudo apt install mysql-server

Il processo ci richiederà se inserire una password, lasciamo vuoto, così l'autenticazione avverrà tramite Socket, solamente in locale. La configureremo in seguito

L'installazione a questo punto, ci chiede se utilizzare Strong Password Encryption o Legacy Authentication. Consiglio di mantenere le raccomandate "Password Forti", se non abbiamo applicazioni legacy che non la supportano.

  ┌──────────────┤ Configuring mysql-community-server ├─────────────┐
  │ MySQL 8 uses a new authentication based on improved SHA256-based    
  │ password methods. It is recommended that all new MySQL Server       
  │ installations use this method going forward. This new               
  │ authentication plugin requires new versions of connectors and       
  │ clients, with support for this new authentication method            
  │ (caching_sha2_password). Currently MySQL 8 Connectors and           
  │ community drivers built with libmysqlclient21 support this new      
  │ method. Clients built with older versions of libmysqlclient may     
  │ not be able to connect to the new server.                           
  │ 
  | To retain compatibility with older client software, the default 
  | authentication plugin can be set to the legacy value 
  | (mysql_native_password) This should only be done if required
  | third-party software has not been updated to work with the new
  | authentication method. The change will be written to the file 
  | /etc/mysql/mysql.conf.d/default-auth-override.cnf                                                              
  |
  │ After installation, the default can be changed by setting the 
  | default_authentication_plugin server setting.
  |
  │ Select default authentication plugin
  │
  │     Use Strong Password Encryption (RECOMMENDED)
  │     Use Legacy Authentication Method (Retain MySQL 5.x)
  │
  │
  │
  |                             <Ok>
  |
  └────────────────────────────────────────────────────────────────┘

Controllo stato e riavvio del servizio MySQL

Controllo dello stato di MySQL

Terminata l'installazione il server MySQL dovrebbe essere già funzionante, controlliamo se il processo è attivo

sudo service mysql status
○ mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; preset: enabled)
     Active: inactive (dead) since Mon 2024-08-26 08:33:45 UTC; 1s ago
   Duration: 1min 18.811s
       Docs: man:mysqld(8)
             http://dev.mysql.com/doc/refman/en/using-systemd.html
    Process: 4614 ExecStartPre=/usr/share/mysql-8.0/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
    Process: 4650 ExecStart=/usr/sbin/mysqld (code=exited, status=0/SUCCESS)
   Main PID: 4650 (code=exited, status=0/SUCCESS)
     Status: "Server shutdown complete"
        CPU: 1.541s

Riavvio del servizio MySQL

Se il servizio, come in questo caso non è attivo (Active: inactive) possiamo riavviare MySQL e ripetere il controllo

sudo service mysql restart
sudo service mysql status
● mysql.service - MySQL Community Server
     Loaded: loaded (/lib/systemd/system/mysql.service; enabled; preset: enabled)
     Active: active (running) since Mon 2024-08-26 08:32:25 UTC; 5s ago
       Docs: man:mysqld(8)
             http://dev.mysql.com/doc/refman/en/using-systemd.html
    Process: 4614 ExecStartPre=/usr/share/mysql-8.0/mysql-systemd-start pre (code=exited, status=0/SUCCESS)
   Main PID: 4650 (mysqld)
     Status: "Server is operational"
      Tasks: 38 (limit: 9513)
     Memory: 371.2M
        CPU: 1.003s
     CGroup: /system.slice/mysql.service
             └─4650 /usr/sbin/mysqld

Controlliamo la porta default di MySQL, la 3306 TCP, che ora dovrebbe essere in ascolto

sudo apt install net-tools
sudo netstat -tnplu |grep 3306

Il comando deve restituirci l'output seguente, mostrando la porta 3306 in ascolto in locale

tcp6       0      0 :::3306           :::*           LISTEN      4951/mysqld         
tcp6       0      0 :::33060          :::*           LISTEN      4951/mysqld         

Settare la Password di root di MySQL

Per accedere da remoto sarà necessario settare la password di root di MySQL. Possiamo utilizzare questo comando, ma consigliamo di utilizzare una password "forte", con numeri, maiuscole e minuscole e caratteri speciali.

sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'LA_MIA_PASSWORD';
exit;

Serve una mano?

Affidati alla nostra consulenza, Gratis 30m di analisi per il tuo sistema

Configurare MySQL 8.0

Il server è attivo, per una nuova installazione le configurazioni utilizzate sono quelle di default, la sicurezza è scarsa, a questo punto è consigliato eseguire lo script di configurazione del DBMS per settare le autenticazioni e rimuovere gli accessi anonimi

sudo mysql_secure_installation

Lo script ci guiderà nella configurazione delle opzioni di sicurezza del server.

Come prima cosa abilitiamo il controllo delle password per gli utenti, e selezioniamo le password forti, con ricerca a dizionario di password comuni.

Securing the MySQL server deployment.
Enter password for user root:

Inseriamo la password di root che abbiamo settato in precedenza e abilitiamo la validazione delle password

VALIDATE PASSWORD COMPONENT can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD component?
Press y|Y for Yes, any other key for No: Y
There are three levels of password validation policy:
LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary                  file
Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 2

Selezionate le password forti "STRONG", inseriamo una password di root efficace 

Change the password for root ? ((Press y|Y for Yes, any other key for No) : N	

Rimuoviamo gli utenti anonimi, per aumentare la sicurezza

By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.
Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y

Configuriamo autenticazione locale dell'utente root, che avverrà tramite socket, solamente sulla macchina locale

Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.
Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y

Rimuoviamo i database di test

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.
Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y

Effettuiamo il reload delle tabelle dei privilegi, in modo da applicare le nostre modifiche immediatamente.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y

Accesso a MySQL da console

L'installazione è terminata è possiamo accedere con l'utente root dalla console del nostro server, e ad esempio listare i database presenti. Ci verrà richiesta la password precedentemente impostata e si aprirà la console di MySQL

sudo mysql -u root -p
Enter password:

Effettuato il a MySQL listiamo i database presenti

show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

L'output ci indica i database presenti, siamo riusciti a installare MySQL in Debian 12 Bookworm, possiamo utilizzare con la solita sintassi il nostro MySQL, connettere ne nostre Web App e CMS

Serve una mano?

Affidati alla nostra consulenza, Gratis 30m di analisi per il tuo sistema

 

Errore comune nell'Installazione di MySQL

mysql_secure_installation
 ... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost' as the authentication method used doesn't store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

È necessario settare prima la password di root, poi eseguire la mysql_secure_installation

Modificare la Password di root di MySQL

Per accedere da remoto sarà necessario settare la password di root di MySQL. Possiamo utilizzare questo comando, ma consigliamo di utilizzare una password "forte", con numeri, maiuscole e minuscole e caratteri speciali.

sudo mysql -p
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'LA_MIA_PASSWORD';

Accedere a MySQL remoto

Per effettuare il login a un MySQL remoto è consigliato utilizzare un tunnel SSH ridirigendo la porta remota 3306 del nostro server, che ascolta solamente in localhost, sulla nostra porta 33006 locale

ssh root@IP-o-DNS -L 33006:localhost:3306

Grazie al tunnel potremmo connetterci direttamente alla nostra porta 33006 in localhost con le credenziali di root create prima

Accedere con MySQL Workbench

MySQL Workbench è un ottimo strumento per DBA MySQL e Operation, permette di creare DB, gestire la configurazione del server, amministrare gli utenti, effettuare backup e molto altro, e incorpora già il tunnel SSH descritto sopra

  1. Creiamo una nuova connessione
  2. Selezioniamo "Standard TCP/IP over SSH"
  3. Inseriamo le configurazioni di SSH per il nostro server di
    1. SSH Host name
    2. SSH User name
    3. Password o chiave SSH
  4. Le configurazioni del Database MySQL
    1. Host name
    2. Server Port
    3. Username
    4. Password
  5. Testiamo la connessione

FAQ Domande frequenti

1. È meglio usare MariaDB o MySQL su Debian?

MariaDB e MySQL sono simili, ma MariaDB è un fork open-source di MySQL, spesso preferito per la sua maggiore libertà e alcune funzionalità avanzate. Se hai bisogno di compatibilità con software esistenti, scegli MySQL. Per progetti nuovi, MariaDB è una buona alternativa.

2. Come configurare MySQL dopo l'installazione su Debian?

Dopo aver installato MySQL su Debian, puoi configurarlo eseguendo il comando sudo mysql_secure_installation. Questo strumento ti aiuta a impostare una password di root, rimuovere utenti anonimi e disabilitare l'accesso remoto per l'utente root, migliorando la sicurezza del server.

3. Quali versioni di MySQL sono supportate su Debian?

Le versioni supportate dipendono dalla tua versione di Debian. Ad esempio, Debian 11 (Bullseye) supporta MySQL 8.0 tramite i repository ufficiali. Puoi anche installare versioni precedenti o successive utilizzando i repository MySQL ufficiali forniti da Oracle.

4. Come aggiornare MySQL su Debian senza perdere dati?

Per aggiornare MySQL su Debian senza perdere dati:

  1. Effettua un backup completo dei database usando mysqldump.
  2. Aggiorna il sistema operativo con sudo apt update && sudo apt upgrade.
  3. Verifica la versione attuale di MySQL e aggiorna il pacchetto con sudo apt install mysql-server.
  4. Riavvia il servizio MySQL e verifica che tutto funzioni correttamente.

5. È possibile installare MySQL su Debian usando Docker?

Sì, puoi installare MySQL su Debian usando Docker. Scarica l'immagine ufficiale di MySQL con il comando docker pull mysql. Poi, avvia un container con:

docker run --name mysql-server -e MYSQL_ROOT_PASSWORD=yourpassword -d mysql:latest

7. Quali sono i requisiti di sistema per installare MySQL su Debian?

I requisiti minimi includono:

  • RAM: Almeno 512 MB (1 GB o più è consigliato).
  • Spazio su disco: 600 MB per MySQL, più spazio aggiuntivo per i database.
  • Processore: CPU moderna con supporto a 64-bit.
  • Rete: Connessione stabile per aggiornamenti e accesso remoto.

Aggiungi un commento

Comment

  • Elementi HTML permessi: <br> <p> <code class="language-*"> <pre>
  • Linee e paragrafi vanno a capo automaticamente.
  • Solo le immagini ospitate su questo sito possono essere utilizzate nel tag <img>.