Назад | Перейти на главную страницу

Проблема с производительностью Ubuntu 16.4 и PHP

Мы недавно установили виртуальный сервер Ubuntu 16.4 LTS + apache + mysql в среде Windows server 2016.

Наша нынешняя производственная система в облачном сервисе работает так, как должна, время загрузки страницы на сервере ~ 200 мс или около того. Но при использовании в нашей среде время загрузки одной и той же страницы составляет 3,4 секунды. Это произошло только на одной конкретной странице PHP. Другие страницы дают неплохие результаты по времени загрузки страницы.

У сервера много свободных ресурсов, и я дал серверу 40 ядер (все) и 8 гигабайт оперативной памяти. Так что это не должно быть из-за нехватки ресурсов.

Я пока доработал mysql. если я запускаю SQL-запросы с помощью phpmyadmin, время отклика будет примерно 0,02 секунды / запрос ...

Я думаю, что в нашей среде есть что-то, что блокирует сценарии PHP или какие-то сетевые вещи, или что-то не так с PHP, настройками apache ...

С чего начать отладку этой проблемы? как ускорить PHP? Я много гуглил, но ни один из них не помог. Например, не вызывайте mysql localhost, используйте вместо него 127.0.0.1 и так далее.

Основная проблема была в конфигурации mysql. Некоторые из этих настроек были критически важны для производительности mysql. Настоящая настройка:

    #
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 0.0.0.0
#
#omat saadot
key_buffer_size = 128M
#kopioitu vanhasta
sort_buffer_size = 12M
read_buffer_size = 12M
read_rnd_buffer_size = 12M
myisam_sort_buffer_size = 76M
query_cache_type=1

thread_stack = 128K
max_heap_table_size = 256M
query_cache_limit = 1M
query_cache_size = 16M

innodb_log_file_size = 512M

#kopioituja vanhasta
# In theory, you want this to encompass your entire database. In
# practice, you only have so much RAM available
innodb_buffer_pool_size = 512M
# Reduce contention. Set to 4+ in MySQL 5.5+
innodb_buffer_pool_instances = 4
# O_DIRECT bypasses the operating system's handling of data. This can
# drastically improve how well your system handles large amounts of RAM by
# removing buffers (once in InnoDB's cache, again in the filesystem's
# cache), at a slight cost to reliability. This appears to be more dramatic
# the more RAM you have. Should reduce swap pressure and in most cases
# improves performance.
#innodb_flush_method = O_DIRECT
# Control Durability
# 1=flush and sync; 2=flush; 0=neither
# Setting innodb_flush_log_at_trx_commit to 0 causes InnoDB to only flush to
# disk once per second, improving performance considerably.
innodb_flush_log_at_trx_commit = 0
# How long to wait for row level locks before bailing out.
innodb_lock_wait_timeout = 180
# The number of open tables for all threads. Increasing this value increases
# the number of file descriptors that mysqld requires.
#table_cache = 4096
# The next two lines replace the basic table_cache value as of MySQL 5.1.
# table_definition_cache should be big enough for every table in your database,
# plus temporary tables, and table_open_cache should be a reflection of how
# many of these will be open in a live connection at once - it will likely
# exceed your definition cache.  It doesn't hurt to set these to large values.
# They don't take a lot of RAM and it's better than hitting the limit.
table_definition_cache = 4096
table_open_cache = 16384
# The default optimizer_search_depth is 62. This causes MySQL to take
# an obscene amount of time planning a query, though when it finally
# executes, it is pretty close to optimal.
optimizer_search_depth = 32
#open-files = 10000




skip_name_resolve

# * Fine Tuning
#
key_buffer_size     = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options  = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit   = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
slow_query_log=1
slow_query_log_file = /var/log/mysql/mysql-slow.log
long_query_time = 1
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size   = 100M
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem


sql-mode="TRADITIONAL"

Предыдущие настройки были настройками по умолчанию, которые mysql имеет после установки и после первого запуска, я думаю:

#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0

[mysqld]
#
# * Basic Settings
#
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 0.0.0.0
#
# * Fine Tuning
#
key_buffer_size     = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover-options  = BACKUP
#max_connections        = 100
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit   = 1M
query_cache_size        = 16M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1
#
# Error log - should be very few entries.
#
log_error = /var/log/mysql/error.log
#
# Here you can see queries with especially long duration
#log_slow_queries   = /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id      = 1
#log_bin            = /var/log/mysql/mysql-bin.log
expire_logs_days    = 10
max_binlog_size   = 100M
#binlog_do_db       = include_database_name
#binlog_ignore_db   = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem

Я не уверен, что это самое важное? Стоит ли мне еще больше поднять эти ценности? У меня есть много памяти, которую нужно использовать. На данный момент у меня на этой виртуальной машине 8 гигабайт памяти.

Я хотел бы знать, что может вызвать такие большие различия в mysql? Есть ли у вас какие-то предпочтительные настройки для Mysql на производстве?

Если вы удалите из своего файла конфигурации следующие строки,

sort_buffer_size
read_buffer_size
read_rnd_buffer_size

система ПО УМОЛЧАНИЮ будет работать на вас и позволит избежать чрезмерного выделения ОЗУ, которое пагубно сказывается на каждом новом соединении. Использование MySQLCalculator.com поможет вам понять этот ответ, связанный с этими 3 критическими ресурсами ОЗУ на одно соединение.