Hướng dẫn tạo SWAP (RAM ảo) cho Ubuntu

Cập nhật ngày 19/01/2025
Lượt xem: 24

Tạo một file /swapfile.img với dung lượng 1GB

sudo dd if=/dev/zero of=/swapfile.img bs=1024 count=1M
  • /swapfile.img là đường dẫn file SWAP của bạn
  • Nếu bạn muốn có 2GB SWAP sửa count=1M thành count=2M

Sau đó chạy lệnh

sudo chmod 0600 /swapfile.img
sudo mkswap /swapfile.img

Sửa file /etc/fstab

Thêm dòng sau vào file /etc/fstab để nó tự khởi động SWAP mỗi khi khởi động

# Add this line to /etc/fstab
/swapfile.img swap swap sw 0 0

Kích hoạt swap

sudo swapon /swapfile.img

Tắt swap

sudo swapoff /swapfile.img

Muốn xóa swap thì làm ngược lại =))

Kiểm tra swap

$ cat /proc/swaps
Filename                           Type       Size    Used    Priority
/media/fasthdd/swapfile.img        file       8388604 2724    -1$ grep 'Swap' /proc/meminfo
SwapCached:         4772 kB
SwapTotal:       8388604 kB
SwapFree:        8355812 kB

Lưu ý: Bạn có thể tạo nhiều swap file

————————

Resize Swap to 8GB

# Turn swap off
# This moves stuff in swap to the main memory and might take several minutes
sudo swapoff -a

# Create an empty swapfile
# Note that "1G" is basically just the unit and count is an integer.
# Together, they define the size. In this case 8GB.
sudo dd if=/dev/zero of=/swapfile bs=1G count=8
# Set the correct permissions
sudo chmod 0600 /swapfile

sudo mkswap /swapfile  # Set up a Linux swap area
sudo swapon /swapfile  # Turn the swap on