linux 內存相關問題
今天收到服務器的內存報警信息。比如下面的例子
free -m
total used free shared buffers cached
Mem: 1875 1589 286 0 127 542
-/+ buffers/cache: 920 955
Swap: 4031 70 396
真正剩餘的內存數量是free+cached
即便是一個剛裝上不久的linux系統 ,如果有頻繁的文件訪問,就會導致cache使用量增大,從而內存使用量這個值會很高,乃至90%也很正常。但是,這個內存佔用量不會達到100%的,因爲當達到一個佔用量的時候,就會啓用swap(虛擬內存)。
而使用內存高的原因是:
1.linux把剩餘的內存都用做磁盤緩存了,這樣可以減少硬盤讀寫次數,Linux在磁盤操作上的速度是要比windows快的。這樣做並不會影響系統速度。換句話說就是Linux 是先佔用,然後再慢慢使用,windows是要用多少就佔用多少。Linux 不會讓內存空着的,程序用不了就當緩存用。
2.桌面追求的是用戶處理的反應速度,而服務器則是承載量,linux正式服務器系統中的佼佼者,着重體現在任務的調度和內存的管理等。而從桌面的角度講,一定要保留足夠的空閒內存去快速反應。
這個佔用內存高固然不會影響使用,但是需要注意去使用top等相關的命令,查看程序真正佔用的內存數是不是很高。如果確定沒問題,那就是真的沒問題了。
關於使用的內存是可以手動進行清理的。
運行sync將dirty的內容寫回硬盤
$sync
通過修改proc系統的drop_caches清理free的cache
$echo 3 > /proc/sys/vm/drop_caches
drop_caches的詳細文檔如下:
Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.
To free pagecache:
* echo 1 > /proc/sys/vm/drop_caches
To free dentries and inodes:
* echo 2 > /proc/sys/vm/drop_caches
To free pagecache, dentries and inodes:
* echo 3 > /proc/sys/vm/drop_caches
As this is a non-destructive operation, and dirty objects are notfreeable, the user should run "sync" first in order to make sure allcached objects are freed.
This tunable was added in 2.6.16.
修改/etc/sysctl.conf 添加如下選項後就不會內存持續增加(不推薦使用)
vm.dirty_ratio = 1
vm.dirty_background_ratio=1
vm.dirty_writeback_centisecs=2
vm.dirty_expire_centisecs=3
vm.drop_caches=3
vm.swappiness =100
vm.vfs_cache_pressure=163
vm.overcommit_memory=2
vm.lowmem_reserve_ratio=32 32 8
kern.maxvnodes=3