Ubuntu – How to use RAM storage for the /tmp directory and how to set a maximum amount of RAM usage for it

filesystemfstabtmpfs

After seeing the comment by Anonymous on the question How is the /tmp directory cleaned up?, I found that it would be a great idea to implement on my system, since I have 16GB of RAM and I never used all of it.

My temporary files never get written to the disk. They get written to a RAM disk. I did put tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0 in /etc/fstab.

My question is:

Can I set a maximum value for RAM Usage for /tmp? And in that case, what would happen if the maximum amount got exceeded, would it write into the hard-disk drive?

I have read a solution which states:

mkdir -p /tmp/ram
sudo mount -t tmpfs -o size=512M tmpfs /tmp/ram/

But in my understanding, this won't be a permanent solution. If I need it to be permanent, it has to be added to the /etc/fstab configuration file.

If this is the correct solution, how can I transform that mount command into a line in /etc/fstab?

Best Answer

You are absolutely right. The according fstab entry would look like this:

tmpfs /tmp tmpfs defaults,noatime,nosuid,nodev,noexec,mode=1777,size=512M 0 0

Please note:

As tmpfs gets filled up, it will behave as any physical hard drive by giving an "not enough space" error. While rebooting (and thus emptying the cache) will fix this, you may run into trouble when a single operation consumes more space to begin with than there's space on tmpfs. In this case your computer will start to swap from ram to disk, which will make your system crawl to a halt, given you've got a swap partition to begin with, of course.

Considering this, a size of 512MB might be far too less nowadays, since much more ram is in existence in modern machines and it has become much cheaper. Since you've already got 16GB of ram, using the default value of half your ram for tmpfs should more than suffice for almost all scenarios. To use the default value, simply leave out the size=512M entry in your /etc/fstab file.

Another note:

You can quite as easily mount other system folders into ramdisk as well, such as

/var/cache

/var/games

/var/log/apt (use only defaults,noatime without mode= or nosuid)

But beware: the same rules apply as above, running out of space might cause major trouble. E.g. imagine running out of space for /var/log/apt will render you unable to install any programs! Furthermore, loading /var/log folders into ramdisk will delete all your log files upon reboot, so you won't be able to debug your system if anything unexpected happens. So use these settings at your own risk!

Editorial note: I removed the /run in tmpfs mount option since this folder and its subfolders are already mounted in tmpfs by default.

Related Question