Swap memory is essential for handling memory pressure in Linux systems. This DevOps-focused guide covers swap file management, performance tuning, and container environments. Learn to optimize virtual memory for applications, Kubernetes, and Docker workloads.
Swap Management Tools Comparison
| Tool Category | Primary Tools | Purpose | DevOps Use Case |
|---|---|---|---|
| Swap Status | free, swapon, /proc/meminfo | Monitor swap usage | Health checks, monitoring |
| Swap Operations | swapon, swapoff, mkswap | Manage swap spaces | Dynamic resource management |
| Performance Tuning | sysctl, /proc/sys/vm/ | Optimize swap behavior | Application performance |
| Container Swap | docker run, k8s limits | Container memory limits | Orchestration configuration |
• Check swap:
free -h or swapon --show• Create swap file:
dd if=/dev/zero of=/swapfile bs=1G count=4• Enable swap:
swapon /swapfile• Tune swappiness:
sysctl vm.swappiness=10• Container memory: Set
--memory-swap in Docker• Kubernetes: Configure
resources.limits.memory• Monitor: Use
/proc/meminfo for detailed stats• For production: Consider 1.5x RAM for swap size
Memory Usage Visualization
Essential Swap Commands
Check current swap usage and configuration.
# Check memory and swap
free -h
# Show swap spaces
swapon --show
cat /proc/swaps
# Detailed memory info
cat /proc/meminfo | grep -i swap
# Real-time monitoring
watch -n 1 'free -h'
# Show swap usage per process
for file in /proc/*/status; do
awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file 2>/dev/null
done | sort -k2 -n -r | head
# Container memory stats
docker stats --no-stream
kubectl top pods
Create and manage swap files dynamically.
# Create 4GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1G count=4
# Set secure permissions
sudo chmod 600 /swapfile
# Format as swap
sudo mkswap /swapfile
# Enable swap
sudo swapon /swapfile
# Disable swap
sudo swapoff /swapfile
# Permanent setup - add to /etc/fstab
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Remove swap file
sudo swapoff /swapfile
sudo rm /swapfile
# Resize swap file
sudo swapoff /swapfile
sudo dd if=/dev/zero of=/swapfile bs=1G count=8
sudo mkswap /swapfile
sudo swapon /swapfile
Optimize swap behavior for better performance.
# Check current settings
sysctl vm.swappiness
sysctl vm.vfs_cache_pressure
# Set swappiness (0-100)
# Lower = less swap usage
sudo sysctl vm.swappiness=10
# Set vfs cache pressure
sudo sysctl vm.vfs_cache_pressure=50
# Make changes permanent
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
# Apply changes
sudo sysctl -p
# Check dirty pages (write cache)
sysctl vm.dirty_ratio
sysctl vm.dirty_background_ratio
# For database servers
sudo sysctl vm.swappiness=1
sudo sysctl vm.dirty_ratio=15
sudo sysctl vm.dirty_background_ratio=5
Swap Configuration Guidelines
| System Type | Recommended Swap | Swappiness | DevOps Consideration |
|---|---|---|---|
| Desktop | 2GB or equal to RAM | 60 | Good for development environments |
| Web Server | 1x RAM (min 4GB) | 10-30 | Handle traffic spikes |
| Database Server | 0.5x RAM | 1-10 | Minimize swap for performance |
| Kubernetes Node | 1-2GB | 1 | Pods should use node memory |
| Docker Host | 1GB + container needs | 10 | Per-container swap limits |
Container Environment Swap
Manage swap for Docker containers and hosts.
# Run container with memory limits
docker run -it --memory=512m --memory-swap=1g ubuntu
# Set swap equal to memory (no extra swap)
docker run -it --memory=512m --memory-swap=512m ubuntu
# Disable swap completely
docker run -it --memory=512m --memory-swap=-1 ubuntu
# Global Docker daemon settings
# /etc/docker/daemon.json
{
"memory-swap": -1,
"memory": "1g"
}
# Check container memory usage
docker stats
# Set swap for running container
docker update --memory-swap 2g container_name
# Compose file example
# docker-compose.yml
services:
app:
deploy:
resources:
limits:
memory: 512M
memory-swap: 1G
Configure memory and swap in Kubernetes.
# Pod with memory limits
apiVersion: v1
kind: Pod
metadata:
name: memory-demo
spec:
containers:
- name: memory-demo-ctr
image: polinux/stress
resources:
limits:
memory: "200Mi"
requests:
memory: "100Mi"
# Disable swap on kubelet
# /etc/default/kubelet
KUBELET_EXTRA_ARGS="--fail-swap-on=false"
# Or disable system swap
sudo swapoff -a
# ResourceQuota for namespace
apiVersion: v1
kind: ResourceQuota
metadata:
name: mem-swap-demo
spec:
hard:
requests.memory: 1Gi
limits.memory: 2Gi
# Check resource usage
kubectl top pods
kubectl describe nodes | grep -A10 "Allocated resources"
Monitor swap usage and set up alerts.
# node_exporter metrics
node_memory_SwapTotal_bytes
node_memory_SwapFree_bytes
node_memory_SwapCached_bytes
# Prometheus alert rules
groups:
- name: memory.rules
rules:
- alert: HighSwapUsage
expr: (1 - (node_memory_SwapFree_bytes / node_memory_SwapTotal_bytes)) * 100 > 80
for: 5m
labels:
severity: warning
annotations:
summary: "High swap usage detected"
# Custom monitoring script
#!/bin/bash
SWAP_USAGE=$(free | awk 'NR==3{printf "%.2f", $3/$2*100}')
if (( $(echo "$SWAP_USAGE > 80" | bc -l) )); then
echo "ALERT: High swap usage: ${SWAP_USAGE}%"
# Send to Slack/Email/PagerDuty
fi
# Container memory monitoring
docker stats --format "table {{.Name}}\t{{.MemUsage}}\t{{.MemPerc}}"
Practical DevOps Scenarios
Real-World Swap Management Scripts
# 1. Automated Swap Setup for Cloud Instances
#!/bin/bash
SWAP_SIZE="${1:-2G}"
echo "Setting up ${SWAP_SIZE} swap file..."
sudo fallocate -l $SWAP_SIZE /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
# Make permanent
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
# Optimize for server workloads
echo 'vm.swappiness=10' | sudo tee -a /etc/sysctl.conf
echo 'vm.vfs_cache_pressure=50' | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
echo "Swap configuration complete"
# 2. Kubernetes Node Swap Check
#!/bin/bash
echo "=== Kubernetes Node Memory Check ==="
echo "Memory:"
free -h
echo -e "\nSwap:"
swapon --show
echo -e "\nKubelet Status:"
systemctl is-active kubelet
# Check if swap is disabled for k8s
if swapon --show | grep -q .; then
echo "WARNING: Swap is enabled - may affect Kubernetes"
else
echo "OK: Swap is disabled"
fi
# 3. Docker Container Memory Monitor
#!/bin/bash
THRESHOLD=80
while true; do
docker stats --no-stream --format "table {{.Container}}\t{{.CPUPerc}}\t{{.MemUsage}}" | \
while read line; do
MEM_PERC=$(echo $line | awk '{print $3}' | sed 's/%//')
if [ "$MEM_PERC" -gt "$THRESHOLD" ] 2>/dev/null; then
echo "ALERT: High memory usage: $line"
fi
done
sleep 30
done
# 4. Swap Usage Alert Script
#!/bin/bash
SWAP_THRESHOLD=70
CURRENT_SWAP=$(free | awk 'NR==3{printf "%.0f", $3/$2*100}')
if [ $CURRENT_SWAP -gt $SWAP_THRESHOLD ]; then
MESSAGE="Swap usage is ${CURRENT_SWAP}% (threshold: ${SWAP_THRESHOLD}%)"
# Send to Slack
curl -X POST -H 'Content-type: application/json' \
--data "{\"text\":\"$MESSAGE\"}" \
$SLACK_WEBHOOK_URL
# Log to file
echo "$(date): $MESSAGE" >> /var/log/swap-alerts.log
fi
# 5. Application Memory Profiler
#!/bin/bash
APP_PID=$(pgrep -f "your-application")
if [ -n "$APP_PID" ]; then
echo "Memory stats for PID $APP_PID:"
cat /proc/$APP_PID/status | grep -E "VmSize|VmRSS|VmSwap"
# Check if swapping
SWAP_KB=$(cat /proc/$APP_PID/status | grep VmSwap | awk '{print $2}')
if [ $SWAP_KB -gt 1000 ]; then
echo "WARNING: Application is using swap memory"
fi
fi
# 6. Cloud Init for Auto Swap Setup
#!/bin/bash
# Save as cloud-init script
swapoff -a
dd if=/dev/zero of=/swapfile bs=1G count=2
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
echo 'vm.swappiness=10' >> /etc/sysctl.conf
sysctl -p
Troubleshooting Common Issues
Performance Problems
- High Swap Usage: Reduce swappiness, add more RAM, optimize applications
- Slow System: Check swap I/O with
iostat, move swap to SSD - OOM Killer: Monitor memory pressure, adjust swappiness, set memory limits
Container Issues
- Docker Container Restarts: Set proper
--memory-swaplimits - Kubernetes Pod Evictions: Configure resource requests and limits properly
- High Container Memory: Use
docker statsto monitor usage
Configuration Problems
- Swap Not Working: Check
dmesgfor errors, verify file permissions - fstab Errors: Test with
swapon -a, check file paths - Permission Denied: Ensure swap file has 600 permissions and root ownership
• For production servers, start with swappiness=10 and monitor
• Use swap files instead of partitions for flexibility
• Place swap on fast storage (SSD/NVMe) when possible
• Monitor swap usage in your observability platform
• Set memory limits in containers to prevent system instability
• For Kubernetes, consider disabling swap on worker nodes
• Test swap configurations in staging before production
• Have alerting for high swap usage (>80% for extended periods)
• Use
zram for compressed swap in memory-constrained environments• Set
vm.swappiness=1 for database servers• Monitor
si/so in vmstat for swap activity• Use
nice/ionice for swap-intensive processes• Consider multiple smaller swap files instead of one large file
• For cloud instances, use instance storage for swap if available
• Regularly test OOM killer behavior with controlled loads
Key DevOps Takeaways
Swap management is crucial for system stability and performance in DevOps environments. By properly configuring swap files, tuning kernel parameters, and setting appropriate container limits, you can handle memory pressure effectively while maintaining application performance. Remember that swap is not a replacement for adequate RAM but a safety net for handling unexpected memory demands.
Next Step: Explore advanced memory management topics like hugepages, memory cgroups, NUMA optimization, and application-specific memory tuning for databases and caching systems.