Это старая версия документа.
MySQL
MySQL - это быстрый, многопоточный, многопользовательский и устойчивый сервер SQL базы данных. Он предназначен как для ответственных сильнозагруженных производственных систем, так и для встраивания в массовое программное обеспечение.
Установка
Для установки MySQL запустите следующую команду из терминала:
sudo apt-get install mysql-server
В процессе установки у вас запросят пароль для пользователя root под MySQL.
Как только установка завершится, сервер MySQL запустится автоматически. Вы можете использовать следующую команду в терминале для проверки, что сервер MySQL запущен:
sudo netstat -tap | grep mysql
Когда вы запустите эту команду, ввы сможете увидеть что-то похожее на следующую строку:
tcp 0 0 localhost:mysql *:* LISTEN 2556/mysqld
Если сервер не работает, вы можете набрать следующую команду для его запуска:
sudo service mysql restart
Настройка
Вы можете отредактировать файл /etc/mysql/my.cnf для настройки основных параметров - файл журнала, номер порта и пр. Например, чтобы настроить MySQL на ожидание подключений от компьютеров в сети, измените параметр bind-address на IP адрес сервера:
bind-address = 192.168.0.5
После изменений в /etc/mysql/my.cnf сервис MySQL нужно перезагрузить:
sudo service mysql restart
Если вам потребовалось сменить пароль пользователя root в MySQL, введите в терминале:
sudo dpkg-reconfigure mysql-server-5.5
Сервис MySQL будет остановлен и вас попросят ввести новый пароль.
Драйверы базы данных
Хотя конфигурация по умолчанию для MySQL, предоставляемая пакетами Ubuntu имеет великолепную функциональность и работает достаточно хорошо, есть некоторые вещи, которые вы можете решить до того как продолжить.
MySQL разработан так, что позволяет хранить данные по-разному. Эти варианты относятся к драйверам (управляющим модулям - engines) как баз данных, так и хранилищ. Существует два основных драйвера, которые вам могут быть интересны: InnoDB и MyISAM. Драйверы хранилищ прозрачны (незаметны) конечным пользователям. MySQL управляет событиями по-разному на нижнем уровне, но независимо от того, какая система хранения данных используется, вы будете взаимодействовать с базой одним и тем же способом.
Каждый драйвер имеет свои преимущества и недостатки.
Хотя смешивание и связывание драйверов баз данных на уровне таблиц разрешается и может быть привлекательным, это снижает эффективность настройки производительности, которую вы смогли бы провести при разделении ресурсов между двумя системами вместо замешивания их в одно целое.
MyISAM более старая из двух. Она может быть быстрее InnoDB при определенных обстоятельствах и предпочтительна при рабочей нагрузке, ориентированной на чтение данных. Некоторые интернет приложения настроены на использование именно MyISAM (однако это не означает, что они будут медленнее под InnoDB). MyISAM также поддерживает тип данных FULLTEXT, который позволяет осуществлять очень быстрый поиск по большому количеству текстовых данных. Однако MyISAM поддерживает блокировку записи только на уровне таблиц. Это означает, что только один процесс может изменять данные в таблице в один момент времени. Поскольку некоторые приложения, использующие таблицу, могут масштабироваться (работать несколькими экземплярами - scales), это может стать серьезной помехой. Здесь также отсутствует журналирование, что может усложнить восстановление данных после сбоя. Следующая ссылка предоставляет некоторые соображения по использованию MyISAM в работающей базе данных.
InnoDB - более современный драйвер, созданный по принципам ACID, что гарантирует надежную обработку транзакций базы данных. Блокировка записи производится на уровне одной записи в таблице. Это означает возможность нескольких изменений в одной таблице одновременно. Кэширование данных происходит также и в оперативной памяти внутри драйвера базы данных, позволяя кэшировать более эффективно чем на уровне блоков файлов. В соответствии с ACID все транзакции журналируются независимо от основных таблиц. Это позволяет намного более надежно восстанавливать данные при проверке целостности данных.
Начиная MySQL 5.5 InnoDB является драйвером по умолчанию и настоятельно рекомендуется вместо MyISAM, если только у вас нет специфических потребностей, уникальных для этого драйвера.
Расширенные настройки
Создание настроенного файла my.cnf
There are a number of parameters that can be adjusted within MySQL's configuration file that will allow you to improve the performance of the server over time. For initial set-up you may find Percona's my.cnf generating tool useful. This tool will help generate a my.cnf file that will be much more optimised for your specific server capabilities and your requirements.
Do not replace your existing my.cnf file with Percona's one if you have already loaded data into the database. Some of the changes that will be in the file will be incompatible as they alter how data is stored on the hard disk and you'll be unable to start MySQL. If you do wish to use it and you have existing data, you will need to carry out a mysqldump and reload:
mysqldump –all-databases –all-routines -u root -p > ~/fulldump.sql
This will then prompt you for the root password before creating a copy of the data. It is advisable to make sure there are no other users or processes using the database whilst this takes place. Depending on how much data you've got in your database, this may take a while. You won't see anything on the screen during this process.
Once the dump has been completed, shut down MySQL:
sudo service mysql stop
Now backup the original my.cnf file and replace with the new one:
sudo cp /etc/my.cnf /etc/my.cnf.backup sudo cp /path/to/new/my.cnf /etc/my.cnf
Then delete and re-initialise the database space and make sure ownership is correct before restarting MySQL:
sudo rm -rf /var/lib/mysql/* sudo mysql_install_db sudo chown -R mysql: /var/lib/mysql sudo service start mysql
Finally all that's left is to re-import your data. To give us an idea of how far the import process has got you may find the 'Pipe Viewer' utility, pv, useful. The following shows how to install and use pv for this case, but if you'd rather not use it just replace pv with cat in the following command. Ignore any ETA times produced by pv, they're based on the average time taken to handle each row of the file, but the speed of inserting can vary wildly from row to row with mysqldumps:
sudo apt-get install pv pv ~/fulldump.sql | mysql
Once that is complete all is good to go!
This is not necessary for all my.cnf changes. Most of the variables you may wish to change to improve performance are adjustable even whilst the server is running. As with anything, make sure to have a good backup copy of config files and data before making changes.
MySQL Tuner
MySQL Tuner is a useful tool that will connect to a running MySQL instance and offer suggestions for how it can be best configured for your workload. The longer the server has been running for, the better the advice mysqltuner can provide. In a production environment, consider waiting for at least 24 hours before running the tool. You can get install mysqltuner from the Ubuntu repositories:
sudo apt-get install mysqltuner
Then once its been installed, run it:
mysqltuner
and wait for its final report. The top section provides general information about the database server, and the bottom section provides tuning suggestions to alter in your my.cnf. Most of these can be altered live on the server without restarting, look through the official MySQL documentation (link in Resources section) for the relevant variables to change in production. The following is part of an example report from a production database which shows there may be some benefit from increasing the amount of query cache:
——– Recommendations —————————————————– General recommendations:
Run OPTIMIZE TABLE to defragment tables for better performance Increase table_cache gradually to avoid file descriptor limits
Variables to adjust:
key_buffer_size (> 1.4G) query_cache_size (> 32M) table_cache (> 64) innodb_buffer_pool_size (>= 22G)
One final comment on tuning databases: Whilst we can broadly say that certain settings are the best, performance can vary from application to application. For example, what works best for Wordpress might not be the best for Drupal, Joomla or proprietary applications. Performance is dependent on the types of queries, use of indexes, how efficient the database design is and so on. You may find it useful to spend some time searching for database tuning tips based on what applications you're using it for. Once you get past a certain point any adjustments you make will only result in minor improvements, and you'll be better off either improving the application, or looking at scaling up your database environment through either using more powerful hardware or by adding slave servers.
Ссылки
See the MySQL Home Page for more information.
Full documentation is available in both online and offline formats from the MySQL Developers portal
For general SQL information see Using SQL Special Edition by Rafe Colburn.
The Apache MySQL PHP Ubuntu Wiki page also has useful information.