Linux создать ram диск

How to Easily Create RAM Disk on Debian, Ubuntu, Linux Mint, CentOS

This tutorial will show you how to quickly create a RAM disk in any Linux distro (Debian, Ubuntu, Linux, Fedora, Arch Linux, CentOS, etc). Compared to commercial Windows RAM disk software that costs money, Linux can utilize this cool feature 100% free of charge.

What is RAM Disk?

RAM disk is also known as RAM drive. It’s a portion of your RAM that are formated with a file system. You can mount it to a directory on your Linux system and use it as a disk partition.

Why use RAM disk?

RAM is ultra-fast compared to even the fastest solid state drive (SSD). As you may know, the main performance bottleneck in today’s computer is the speed of hard drive, so moving programs and files to the RAM disk yields super fast computing experience.

  • RAM is volatile which means all data in RAM disk will be lost when the computer shutdowns or reboots. However, this can be a pro in some situations, if you use it wisely.
  • RAM is expensive so it has limited capacity. You need to make sure not allocate too much space for RAM disk, or the operating system would run out of RAM.

You can do a lot of interesting things with RAM disk.

  • RAM disk is best suited for temporary data or caching directories, such as Nginx FastCGI cache, and Debian package downloads ( /var/cache/apt/archive/ ). If you use a SSD and there will be a lot of writes to a particular directory, you can mount that directory as a RAM disk to reduce wear out of SSD.
  • I also use RAM disk to temporarily store screenshots when writing articles on this blog, so when my computer shut down, those screenshots will automatically be deleted on my computer.
  • You might not believe it, but I use RAM disk to run virtual machines inside VirtualBox. My SSD is about 250G. I can’t run many VMs directly on the SSD and I’m not happy about the speed of my 2TB mechanical hard drive (HDD). I can move the VM from HDD to RAM disk before starting the VM, so the VM can run much faster. After shutting down the VM, I move the VM files back to HDD, which takes less than 1 minute. This of course requires your computer to have a large capacity RAM.
Читайте также:  Linux узнать ip адрес интерфейса

How to Create a RAM Disk in Any Linux Distro

First make a directory which can be anywhere in the file system such as

If you want to let every user on your Linux system use the RAM disk, then change its permission to 777.

sudo chmod 777 /tmp/ramdisk

Next, check how much free RAM are left on your system with htop command line utility because we don’t want to use too much RAM.

easily create ram disk linux

Then all left to do is to specify the file system type, RAM disk size, device name and mount it to the above directory. You can see from the screenshot above that I have plenty of free RAM, so I can easily allocate 1GB for my RAM disk. This can be done with the following one-liner. It will be using tmpfs file system and its size is set to 1024MB. myramdisk is the device name I gave to it.

sudo mount -t tmpfs -o size=1024m myramdisk /tmp/ramdisk

To allocate 10G for the RAM disk, run this instead.

sudo mount -t tmpfs -o size=10G myramdisk /tmp/ramdisk

If we issue the following command

We can see it’s successfully mounted.

create linux ramdisk

Now if I copy my VirtualBox machines file (5.8G) into the RAM disk, my RAM usage suddenly goes up to 9.22G.

linux automount ramdisk

Everything in that directory will be lost and RAM usage goes down to original.

linux ramdisk file system

This is how you can test if your RAM disk is working.

Test RAM Disk Speed

To test write speed of RAM disk, you can use dd utility.

sudo dd if=/dev/zero of=/tmp/ramdisk/zero bs=4k count=100000

Which gave me 2.8GB/s write speed.

linux ramdisk speed test

sudo dd if=/tmp/ramdisk/zero of=/dev/null bs=4k count=100000

Which gave me 3.1 GB/s read speed.

I also did a speed test on my SSD. The write speed is 534MB/s and read speed 1.6GB/s.

Auto-mount on System Boot

myramdisk /tmp/ramdisk tmpfs defaults,size=1G,x-gvfs-show 0 0

x-gvfs-show will let you see your RAM disk in file manager. Save and close the file. Your Linux system will automatically mount the RAM disk when your computer boots up.

To mount it immediately without reboot, run the following command.

Using RAM Disk to Reduce SSD Wear Out

To increase the lifespan of your SSD, you should avoid write and delete operations on the SSD as much as possible. The Linux operating system has two activities that make up the most write and delete operations.

If you use a Debian-based Linux distribution, the temporary download directory for software packages is /var/cache/apt/archives/ . Once the package is installed, APT package manager automatically deletes the .deb files in this directory. You can add the following line in /etc/fstab file to mount this directory in RAM.

package_archive /var/cache/apt/archives tmpfs defaults,size=6G 0 0

Fedora stores temporary package downloads under /var/cache/dnf/ directory, so you can add the following line in /etc/fstab file to mount this directory in RAM.

package_archive /var/cache/dnf tmpfs defaults,size=6G 0 0

Some folks might wonder if mounting this directory will prevent Fedora from upgrading to a new release, because Fedora requires reboot to install system upgrade packages. The answer is No. It won’t prevent system upgrades, as Fedora stores system upgrade pacakges under a different directory /var/lib/dnf/system-upgrade/ .

Читайте также:  Embedded linux for stm32

The logging directory on Linux is usually /var/log/ . It’s not safe to mount the entire /var/log/ directory in RAM. Change to this directory.

You will find that the /var/log/journal/ sub-directory uses the most disk space. It’s used for logging systemd services and safe to mount in RAM, so you can add the following in in the /etc/fstab file.

systemd_journal /var/log/journal tmpfs defaults,size=6G 0 0

If you run Nginx web server, you might want to mount the /var/log/nginx/ directory into RAM. On one of my servers, this directory is 2.2G in size.

nginx_logs /var/log/nginx/ tmpfs defaults,size=6G 0 0

After saving the /etc/fstab file, run the following command to mount all file systems.

How to Run VirtualBox VM on RAM Disk

Note that this requires a large-capacity RAM.

When you create a brand new virtual machine, you should set the machine folder to the RAM disk directory ( /tmp/ramdisk/ ). If you can’t find the Machine folder option, then you need to install the latest version of Virtualbox on your system.

Run VirtualBox VM on RAM Disk

If you have an existing VM, then select the VM in the main VirtualBox Manager window and go to the menu bar and select Machine -> Move, or right-click the VM and select Move from the context menu. You will be prompted to choose a new folder for the virtual machine. Select /tmp/ramdisk/ as the new folder.

Virtualbox move virtual machine folder

Remember to move your VM back to the original folder before shutting down your computer, or your VM will be deleted.

Wrapping Up

And that’s the basics of creating RAM disk in Linux. If you found this post useful, then subscribe to our free newsletter or follow us Twitter or like our Facebook page. Thanks for visiting!

Источник

Создаём RAMdisk на Ubuntu 18.04

После чего проверяем правильность создания рамдиска командой:

И видим следующий результат:

Filesystem Size Used Avail Use% Mounted on
udev 2.0G 0 2.0G 0% /dev
tmpfs 395M 620K 394M 1% /run
/dev/vda2 89G 74.5G 580G 6% /
tmpfs 2.0G 0 2.0G 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
tmpfs 395M 0 395M 0% /run/user/1000
tmpfs 2.0G 0 2.0G 0% /mnt/ramdisk

Теперь вы можете использовать рамдиск как вы используете обычные разделы жесткого диска. Вы даже можете редактировать любые файлы прямо из РАМДИСКА.

Чтобы отключить виртуальный диск (РАМДИСК), выполните следующую команду (все ваши файлы на этом разделе будут моментально удалены):

Читайте также:  Kali linux debian install

Подключение RAM-диска на UBUNTU 18.04 автоматически, при загрузке системы

Вы можете использовать файл /etc/fstab для автоматического монтирования виртуального диска при загрузке системы.

Во-первых, сделайте резервную копию файла /etc/fstab. Можно с помощью следующей команды:

sudo cp -v /etc/fstab /etc/fstab.backup

Резервная опия файла /etc/fstab сохранится в /etc/fstab.backup. Теперь если что-то случится в процессе, вы сможете просто восстановить файл /etc/fstab.

Открываем файл /etc/fstab:

После чего в конце файла добавляем следующую строчку:

tmpfs /mnt/ramdisk tmpfs rw,size=2G 0 0

После чего перезагружаем сервер командой:

После загрузки системы РАМдиск должен быть автоматически смонтирован (нужно проверить):

. 
tmpfs 2.0G 0 2.0G 0% /mnt/ramdisk
.

Сохранение данных RAM-диска:

Далее я покажу, как сохранить данные рамдиска на десткий диск при завершении работы системы и загрузить данные с жесткого диска в RAM-диск при загрузке системы.

Для этого создадим каталог, где диск будет смонтирован и где резервные копии данных будут сохраняться должны иметь одинаковый набор прав доступа к файлам.

Сначала создайте каталог, где данных RAM-диска будет сохранен при выключении системы с помощью следующей команды:

sudo mkdir /mnt/ramdisk_backup

Теперь создайте файл системной службы с помощью следующей команды:

sudo nano /lib/systemd/system/ramdisk-sync.service

Рубрики

При заказе по этой ссылке бесплатно помогу настроить и подготовить сервер к повседневной эксплуатации.

Источник

Как создать ramdisk в Linux или виртуальный диск в RAM

Иногда попадаются задачи, когда нужно работать с большим количеством мелких файлов или некоторое небольшое время хранить объемные данные и делать это по возможности быстро, без завязок на медленную файловую подсистему и/или диски. Многие вспомнят, что есть такой виртуальный диск, он же – RAM-дисках (ramdisk), а сделать ramdisk в *nix системах можно очень быстро и просто.

Изначально, в ядре должна быть поддержка tmpfs.

Как создать диск:
В первую очередь создаем новую точку монтирования:

mkdir /cache chmod 777 /cache

и даём все права на использование.

После этого даём команду на монтирование, для примера, я создам диск на 1 Gb

# mount -t tmpfs -o size=1024M tmpfs /cache или $ sudo mount -t tmpfs -o size=1024M tmpfs /cache

где 1024M – это и есть размер RAMdisk в Мегабайтах.

Аккуратнее с размером и не размахивайтесь слишком широко: если вы попросите создать ramdisk больше, чем имеете оперативной памяти, система начнёт сгружать всё в swap-файл и дела пойдут очень медленно и грустно. Кстати, если ОЗУ в системе достаточно, swap можно и вовсе отключить, см. Как отключить SWAP

Если же вы хотите изменить размер ramdisk – это просто:

# mount -o remount -o size=2048M /cache или $ sudo mount -o remount -o size=2048M /cache

При этом содержимое RAM-диска не пропадёт, но и его размер тут же увеличится (при уменьшении также ничего не пропадёт, если только данных не больше, чем диск).

ВАЖНО.
RAM-диск это хранение в OЗУ, и это значит, что всё его содержимое после отключения питания машины будет безвозвратно потеряно. По возможности используйте резервное питание, что бы успеть сохранить важные данные.

Источник

Оцените статью
Adblock
detector