What is happening?
A cloud server is sometimes called a droplet. It is a small virtual computer you rent. MySQL is the program that stores your website's data in databases. When the server runs out of memory, Ubuntu may stop MySQL to save itself. Then your site shows "Error establishing a database connection".
The most common reason is too little RAM. RAM is the short-term memory a computer uses while it works.
Step 1: Check if memory ran out
- Connect to your server with SSH.
- Run this command:
sudo grep -i "out of memory" /var/log/syslog
This searches the system log for out-of-memory events. If you see "Killed process" and "mysqld", memory is the cause.
- Check the MySQL log too:
sudo tail -n 50 /var/log/mysql/error.log
This shows the last 50 lines of MySQL's own notes.
Step 2: Add swap space
Swap is a part of the disk used as extra memory. It is slower than RAM, but it can stop crashes.
- Create a 1 GB swap file:
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
These lines make the file, lock it down, prepare it as swap and turn it on.
- Make it stay after a restart:
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
Step 3: Make MySQL use less memory
Back up the config file first.
- Copy the file:
sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /root/mysqld.cnf.bak - Open it:
sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf - Under
[mysqld], add or lower these values:
innodb_buffer_pool_size = 128M
max_connections = 50
These limit how much memory MySQL takes and how many users can connect at once.
- Save, then restart MySQL:
sudo systemctl restart mysql
Other causes
- The disk is full. Check with
df -h. - A broken table. Run
mysqlcheck -u root -p --all-databases. - Too many plugins or heavy traffic on your site.
Quick recap
- Most crashes come from running out of memory.
- Check the system log and MySQL log.
- Add swap space.
- Lower MySQL's memory settings.
- Upgrade RAM if it continues.