EASY RESPONSE:
* * * * * systemctl is-active --quiet mysqld || systemctl restart mysqld
DETAILED ANSWER:
This is an important issue, especially for people who use a very small VPS, say, 1 GB of RAM or less. If MySQL shuts down, it may be due to the configuration of your server (Apache | nginx) or MySQL. DOS attacks can cause an increased surge in the use of system resources (see. Image). The end result is that the MySQL process is shut down by the kernel. For a long-term solution, take a look at optimizing your Apache or MySQL configurations.

There are several other discussions related to stack overflow, as well as the MySQL manual and the Percona blog:
MySQL Manual - How MySQL uses memory:
https://dev.mysql.com/doc/refman/8.0/en/memory-use.html
Percona - Recommendations for tuning the optimal use of MySQL memory:
https://www.percona.com/blog/2016/05/03/best-practices-for-configuring-optimal-mysql-memory-usage/
How to optimize MySQL performance using MySQLTuner:
https://www.linode.com/docs/databases/mysql/how-to-optimize-mysql-performance-using-mysqltuner/
Apache memory usage configuration:
https://serverfault.com/questions/254436/apache-memory-usage-optimization
Apache Performance Tuning Guide:
https://httpd.apache.org/docs/2.4/misc/perf-tuning.html
Apache server setup:
https://www.linode.com/docs/web-servers/apache-tips-and-tricks/tuning-your-apache-server/
However, as for your original question, yes, you can write a workaround that checks if the MySQL service is loaded and active, and will restart MySQL if it is not loaded and not active.
You did not mention which operating system you are using. This would help give you a specific command. I will give you an example for CentOS Linux.
Take a look at the following output from the systemctl status mysql command. At the top you can see that the service is loaded and active .
[root@centos-mysql-demo ~]
If the service is not loaded, then a command such as:
systemctl status mysqld || systemctl restart mysqld
will do the trick of restarting the process. You could cron that:
* * * * * systemctl status mysqld || systemctl restart mysqld
However, in case mysql is loaded but the service is not active , your cron will do nothing. So you should use a more detailed command such as:
* * * * * systemctl is-active --quiet mysqld || systemctl restart mysqld
In this case, if the service is loaded but inactive, for example, a state in which a DOS attack can leave the mysql service, the command will also restart mysql. Using the --quiet flag simply tells the command only to return a status code, not to display anything on the screen. If you omit the --quiet flag, you will see the status output either active or inactive .
You can also create some swap space to add more available RAM resources to your server, for example:
sudo dd if=/dev/zero of=/swapfile count=2096 bs=1MiB chmod 600 /swapfile mkswap /swapfile swapon /swapfile swapon --show swapon --summary free -h