I had the great idea(not so great really) to setup my own EC2 instance in Amazon. Recently, I noticed mysql was crashing. When I looked at the CPU reports there were some spikes in usage, that for some reason would make mysql crash. I will have to login into my server and restart it manually. When I was looking at the apache logs for traffic increases, everything seems fine.
After talking to Mike Reed at my company(our wonderful DevOps guy), he mentioned experiencing a similar behavior when he set up an EC2 instance – I really hope my server is not getting hacked! Not that I have a lot of important information but that would just suck.
I couldn’t figure out a way to fix this but using the cron utility. A time-based job scheduler in Unix-like computer operating systems. Since my server is running Ubuntu, this comes on handy to deal with my problem.
Basically what the Cron job does it to run a specific script given a time stamp. I bumped into the following script from the guys at Open Source Web – credit where is due! And kudos for sharing this.
# APACHE SECTION
if [ $? -ne 0 ]
# MYSQL SECTION
if [ $? -ne 0 ]
This shell script basically looks at both mysql and apache. It checks if any of them are down, and if so it restarts them
1. After login into your server, make sure you switch to root user. You want your Cron Jobs to be performed without any password prompted. Use the following command to become root and enter password if you have set up a password for root before:
2. Go into the root folder of root – I know this sounds redundant, but remember that for set users the root folder is inside /home/”user_name”. Go ahead and create a folder. I call mine cronscripts:
3. Go inside the folder:
4. Create a shell script using your preferred text editor, I call mine script, running the following command:
Make sure you paste the script above. Hit esc and wq. This will save and quit vim.
5. Change the file permission with:
chmod 755 script.sh
6. Now we want to set up the task on our crontab. Remember! Crontabs are attached to user profiles, hence the importance of doing it as a root user. Run:
If running it for the first time, terminal will prompt you to use a text editor. Again, choose the one of your preference.
7. Add the following line of code in order to run your task every 10 mins:
*/10 * * * * /root/cronscript/script.sh > /root/cronscript/scriptlog.txt
Let’s take a look at the following line of code. */10 makes sure the task is run every 10 minutes. Subsequently, I specify the location of the script I want to run. /root/cronscript/script.sh Finally I’m using the operator > . Similar to piping | , This is taking care of putting the output result of my script into a file in the same location named scriptlog.txt. This is for login purposes. The operator overrides the result, if you want the task to concatenate each single output that comes every 10 minutes in your log file use >> instead!