Check memory usage on Linux, and what swap usage means
To check memory usage on Linux, run free -h and read the available column: that is how much memory programs can still get. The free column looks alarming on any busy server because Linux fills spare memory with disk cache and hands it back when a program asks. Then use top or ps to see which process holds the memory, and docker stats for containers. Swap in use is normal; swap that keeps moving is the warning sign.
Check memory usage with free
free -h
total used free shared buff/cache available
Mem: 3.8Gi 2.1Gi 180Mi 12Mi 1.5Gi 1.4Gi
Swap: 2.0Gi 310Mi 1.7Gi| Column | What it means |
|---|---|
| used | Memory programs hold, without the cache |
| free | Memory nothing uses, not even the cache; low is normal |
| buff/cache | Disk cache the kernel gives back when a program needs it |
| available | What a program can still get without swapping: the number to watch |
cat /proc/meminfo shows the same figures in more detail, and vmstat -s prints them as a list.
Find which process uses the memory
top -o %MEM # live, sorted by memory; press M in top to switch
ps aux --sort=-rss | head -n 11 # the ten biggest, by resident memory
sudo smem -tk # proportional share, if smem is installedRSS is the memory a process holds in RAM right now. Shared libraries count towards every process that maps them, so the column adds up to more than the machine has; smem splits shared pages fairly. A process whose RSS only grows over days, under the same load, is leaking.
Memory per Docker container
docker stats --no-stream --format 'table {{.Name}} {{.MemUsage}} {{.MemPerc}}'MemUsage shows each container against its limit, or against the whole machine when it has none. A container near its limit is the likeliest to be killed, with exit code 137 (OOM killed). Set a limit with --memory or mem_limit in Compose so one container cannot starve the rest.
What swap usage means
Swap is disk space the kernel moves idle memory pages to. Some swap in use only means the kernel parked pages nothing touched for a while, which frees RAM for the cache. It turns into a problem when pages move in and out all the time, because every move waits on the disk.
swapon --show # swap devices and how full they are
vmstat 1 5 # si and so: memory swapped in and out per second (KiB)Steady non-zero si and so mean the server is short of memory: add RAM, cap the process that grows, or move a service off the box. vm.swappiness only changes how early the kernel swaps, not how much memory you have.
When memory runs out
With no memory left and swap full or absent, the kernel’s OOM killer picks a process and kills it. sudo dmesg -T | grep -i "killed process" shows which one and when. In a container it shows as exit code 137; a container that is killed and started again in a loop is covered in why a container keeps restarting.