I am running a web server on an AWS EC2 micro instance. The instance has ~630MB of RAM. With time, I have several httpd processes and very little free RAM. When I restart the httpd service, I end up freeing about 350MB of RAM.

I thought of having this automated every 12 hours using a cron job under root. My script includes code as

service httpd restart
service mysqld restart
ps aux
free -m

This is the first time I am attempting cron scripts.

I receive an email with the expected output for ps aux and free -m, but

./scriptName.sh: line 1: service: command not found
./scriptName.sh: line 2: service: command not found

for the restarts commands.

The script did run as root. I am afraid that using sudo may cause the script to hang. The relevant lines from the output of ps -

root     14664  0.0  0.2 142200  1720 ?        S    22:41   0:00 CROND
root     14665  0.0  0.2   9296  1236 ?        Ss   22:41   0:00 /bin/sh -c ./scriptName.sh
smmsp    14667  0.0  0.6  76020  4244 ?        R    22:41   0:00 /usr/sbin/sendmail -FCronDaemon -i -odi -oem -oi -t -f root
root     14669  0.0  0.1  11244  1008 ?        R    22:41   0:00 ps aux

What is the right thing to do to have a successful restart of services?

Is it even advisable to do something like this?

Output of free -m

             total       used       free     shared    buffers     cached
Mem:           596        573         23          0          8         71
-/+ buffers/cache:        493        103
Swap:            0          0          0

Solution 1:

The primary problem is that there is no proper $PATH defined in the run environment of cron, so you need to use the full path to service for this to work.

You can find out this path with the command which service, which should print something like /usr/sbin/service.

The secondary problem: I wouldn't do that, just blindly restarting services on a production system is never a good idea. Do you have an actual memory/performance problem or might it be that your RAM is just used up by buffers and the like (see http://www.linuxatemyram.com/)?

Please add the output of free -m after a few hours to your question.

Solution 2:

It might be better to look at something like Monit instead of trying to do a homebrew cron script.

Here's the example config for Apache:

http://mmonit.com/wiki/Monit/ConfigurationExamples#apache

You should be able to do something like:

if totalmem > 300 MB for 2 cycles then alert

in the Apache block.

Monit should be in one of the RPM repositories.

Solution 3:

I think you're going about this the wrong way. Look into tuning Apache first of all. Then, research Linux memory management. You WANT your server using the ram, otherwise why do you have it?