Script 03 · Memory
3. Add Swapfile & Zram (Managed Package)
Creates or resizes a disk swapfile and configures ZRAM so small VPS instances handle temporary memory pressure more safely.
Category: Memory
Risk: Medium
Lines: calculating
Language: Bash / Linux
What this script does
- Reduce out-of-memory crashes.
- Use compressed memory before slower disk swap.
- Persist swap and ZRAM configuration.
Prerequisites
- Root access
- Enough disk space for swapfile
- Kernel support for zram
- linux-modules-extra package availability
Execution flow
- Detects existing swapfile
- Optionally recreates swap
- Installs zram-tools
- Configures algorithm and percentage
- Restarts zramswap
Validation checklist
- swapon --show
- zramctl
- cat /proc/swaps
- systemctl status zramswap
Operational cautions
- Oversized swap can hide memory leaks.
- ZRAM uses CPU; choose lz4 for low CPU overhead.
Original script notes
ℹ️ Script Info: Manages virtual memory. It safely creates or resizes a disk-based Swap file and configures ZRAM (compressed RAM) to prevent Out-Of-Memory (OOM) crashes during heavy computational loads.
cat << 'EOF' > auto_install_optimized.sh
#!/bin/bash
# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
clear
echo -e "${YELLOW}=======================================================${NC}"
echo -e "${YELLOW} SERVER OPTIMIZATION: SWAPFILE MANAGER & ZRAM TOOLS ${NC}"
echo -e "${YELLOW}=======================================================${NC}"
# --- PART 1: SWAP FILE LOGIC (DISK) ---
echo -e "\n${CYAN}[PART 1] Checking Swap File (Disk)${NC}"
PROCESS_NEW_SWAP=false
# 1. Check if Swapfile already exists
if grep -q "/swapfile" /proc/swaps; then
CURRENT_SWAP_SIZE=$(grep "/swapfile" /proc/swaps | awk '{print $3}')
CURRENT_SWAP_SIZE_MB=$((CURRENT_SWAP_SIZE / 1024))
echo -e "${YELLOW}[!] System detects an active swapfile of ${CURRENT_SWAP_SIZE_MB} MB.${NC}"
echo -e "What would you like to do?"
echo -e "${GREEN}1. Skip${NC} - Keep the current swapfile, proceed to ZRAM install."
echo -e "${GREEN}2. Resize/Recreate${NC} - Delete the old one, create a new one."
read -p "Your Choice (1/2): " SWAP_ACTION_CHOICE
if [[ "$SWAP_ACTION_CHOICE" == "2" ]]; then
PROCESS_NEW_SWAP=true
echo -e "${YELLOW}[*] Mode: Deleting old swap and creating new one...${NC}"
else
echo -e "${GREEN}[*] Using existing swapfile. Proceeding to ZRAM...${NC}"
fi
else
echo -e "${GREEN}[*] No swapfile detected. Proceeding to create new swap...${NC}"
PROCESS_NEW_SWAP=true
fi
# 2. Swap Creation Process (If selected or if none exists)
if [ "$PROCESS_NEW_SWAP" = true ]; then
# Detect RAM
TOTAL_RAM_MB=$(free -m | awk '/^Mem:/{print $2}')
echo -e "\n>> Total Physical RAM: ${GREEN}${TOTAL_RAM_MB} MB${NC}"
# Size Method Selection
echo -e "Choose size method for new Swap File:"
echo -e "${GREEN}1. Automatic${NC} (2x RAM - Recommended)"
echo -e "${GREEN}2. Manual${NC} (Input yourself in MB)"
read -p "Choice (1/2): " SWAP_METHOD_CHOICE
if [[ "$SWAP_METHOD_CHOICE" == "2" ]]; then
read -p "Enter size (MB): " MANUAL_SWAP_INPUT
if [[ "$MANUAL_SWAP_INPUT" =~ ^[0-9]+$ ]]; then
SWAP_SIZE_MB=$MANUAL_SWAP_INPUT
else
SWAP_SIZE_MB=$((TOTAL_RAM_MB * 2))
echo -e "${RED}[!] Invalid input. Defaulting to Auto.${NC}"
fi
else
SWAP_SIZE_MB=$((TOTAL_RAM_MB * 2))
fi
SWAP_SIZE="${SWAP_SIZE_MB}M"
SWAP_FILE="/swapfile"
echo -e ">> Target Swap Size: ${GREEN}${SWAP_SIZE}${NC}"
# SAFE REMOVE EXECUTION
if [ -f "$SWAP_FILE" ]; then
echo -e "${YELLOW}[*] Deactivating old swap (Safe Remove)...${NC}"
swapoff $SWAP_FILE >/dev/null 2>&1
rm -f $SWAP_FILE
# Clean up fstab to avoid duplicates
sed -i "\|$SWAP_FILE|d" /etc/fstab
echo -e "${GREEN}[OK] Old swap deleted.${NC}"
fi
# CREATE NEW SWAP EXECUTION
echo -e "${YELLOW}[*] Creating new Swap File...${NC}"
sudo fallocate -l $SWAP_SIZE $SWAP_FILE && \
sudo chmod 600 $SWAP_FILE && \
sudo mkswap $SWAP_FILE && \
sudo swapon $SWAP_FILE && \
echo "$SWAP_FILE none swap sw 0 0" | sudo tee -a /etc/fstab && \
echo -e "${GREEN}>> Success! Swap file $SWAP_FILE (${SWAP_SIZE}) is permanently active.${NC}"
# Tuning Kernel Swap Disk
if ! grep -q "vm.vfs_cache_pressure" /etc/sysctl.conf; then
echo "vm.vfs_cache_pressure=50" | sudo tee -a /etc/sysctl.conf
else
sed -i 's/^vm.vfs_cache_pressure.*/vm.vfs_cache_pressure=50/' /etc/sysctl.conf
fi
sysctl -p >/dev/null 2>&1
fi
# --- PART 2: ZRAM INSTALLATION (MANAGED PACKAGE) ---
echo -e "\n${CYAN}[PART 2] ZRAM Installation (zram-tools)${NC}"
# 1. Install Package & Fix Missing Kernel Modules (KVM/Cloud VPS)
echo -e "${YELLOW}[*] Updating Repo and Installing kernel modules & zram-tools...${NC}"
sudo apt update -qq
sudo apt install linux-modules-extra-$(uname -r) -y
sudo modprobe zram
sudo apt install zram-tools -y
# 2. Configuration Prompts
echo -e "\n${YELLOW}--- ZRAM CONFIGURATION WIZARD ---${NC}"
# A. Choose Algorithm
echo -e "Select Compression Algorithm:"
echo -e "${GREEN}1. lz4${NC} (Fastest, Low CPU Usage - Recommended for most VPS)"
echo -e "${GREEN}2. zstd${NC} (High Compression, Higher CPU Usage)"
read -p "Your Choice (1/2): " ALGO_OPT
if [[ "$ALGO_OPT" == "2" ]]; then
SET_ALGO="zstd"
else
SET_ALGO="lz4"
fi
echo -e ">> Algorithm set to: ${GREEN}$SET_ALGO${NC}"
# B. Choose Percentage
echo -e "\nHow much RAM (%) should be allocated to ZRAM?"
echo -e "Example: 50 means 50% of your RAM."
read -p "Enter Percentage (Default 50): " PERCENT_OPT
if [[ -z "$PERCENT_OPT" ]] || ! [[ "$PERCENT_OPT" =~ ^[0-9]+$ ]]; then
SET_PERCENT=50
else
SET_PERCENT=$PERCENT_OPT
fi
echo -e ">> Allocation set to: ${GREEN}${SET_PERCENT}%${NC}"
# C. Auto Priority Info
SET_PRIORITY=100
echo -e "\n>> Priority automatically set to: ${GREEN}${SET_PRIORITY}${NC}"
echo -e " (This ensures system uses ZRAM first before touching Disk Swap)"
# 3. Apply Configuration to /etc/default/zramswap
echo -e "\n${YELLOW}[*] Applying configuration to /etc/default/zramswap...${NC}"
CONFIG_FILE="/etc/default/zramswap"
# Function to safely update variable in config file
update_cfg() {
local key=$1
local value=$2
if grep -q "^#*$key=" "$CONFIG_FILE"; then
# Replace existing line (commented or not)
sudo sed -i "s/^#*$key=.*/$key=$value/" "$CONFIG_FILE"
else
# Append if not found
echo "$key=$value" | sudo tee -a "$CONFIG_FILE" > /dev/null
fi
}
update_cfg "ALGO" "$SET_ALGO"
update_cfg "PERCENT" "$SET_PERCENT"
update_cfg "PRIORITY" "$SET_PRIORITY"
# 4. Restart Service
echo -e "${YELLOW}[*] Restarting zramswap service to apply changes...${NC}"
if sudo systemctl restart zramswap; then
echo -e "${GREEN}[OK] Service restarted successfully.${NC}"
else
echo -e "${RED}[!] Failed to restart service. Trying daemon-reload...${NC}"
sudo systemctl daemon-reload
sudo systemctl restart zramswap
fi
# --- PART 3: VERIFICATION ---
echo -e "\n${CYAN}[PART 3] Final Verification${NC}"
echo -e "${YELLOW}-------------------------------------------------------${NC}"
# Check ZRAM Device
if zramctl | grep -q "zram"; then
echo -e "${GREEN}[SUCCESS] ZRAM is Active and Running!${NC}"
echo -e "\nDevice Details:"
zramctl
else
echo -e "${RED}[ERROR] ZRAM device not found! Check logs manually.${NC}"
fi
echo -e "${YELLOW}-------------------------------------------------------${NC}"
# Check Swap Priority
echo -e "SWAP PRIORITY CHECK (ZRAM should have higher priority e.g., 100):"
cat /proc/swaps
# Reboot Prompt
echo -e "\n${YELLOW}[?] REBOOT recommended to ensure all memory hooks are clean. Reboot now? (y/n)${NC}"
read -p "Choice: " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
echo -e "${RED}[*] Rebooting...${NC}"
sleep 2
reboot
else
echo -e "${GREEN}[*] Done. Script saved: auto_install_optimized.sh${NC}"
fi
EOF
chmod +x auto_install_optimized.sh && sudo ./auto_install_optimized.sh