Posts tagged with “swap”

Set Up a 2GB Swap on a Remote VPS with a Simple Script

Running a small VPS with limited memory can be frustrating, especially when processes get killed due to low memory. A quick and easy way to help prevent this is by setting up a swap file.

This script will

  1. Checks if swap already exists on the remote machine.
  2. If not, it creates a 2GB swap file and enables it.
  3. Adds the swap file to /etc/fstab to make it permanent.

The script uses scp to copy a temporary script to the remote machine and ssh to execute it. Here’s the full script:

#!/bin/bash

# Check if machine name is provided
if [ -z "$1" ]; then
  echo "Usage: $0 <machine-name>"
  exit 1
fi

REMOTE_MACHINE=$1
SWAPFILE=/swapfile
SIZE=2048

# Generate remote script content
REMOTE_SCRIPT=$(cat <<EOF
#!/bin/bash
if swapon --show | grep -q "$SWAPFILE"; then
  echo "Swap is already enabled on $SWAPFILE"
  exit 0
fi

sudo dd if=/dev/zero of=$SWAPFILE bs=1M count=$SIZE
sudo chmod 600 $SWAPFILE
sudo mkswap $SWAPFILE
sudo swapon $SWAPFILE

if ! grep -q "$SWAPFILE" /etc/fstab; then
  echo "$SWAPFILE none swap sw 0 0" | sudo tee -a /etc/fstab
fi
free -h
EOF
)

# Save remote script locally
echo "$REMOTE_SCRIPT" > /tmp/create_swap.sh

# Copy script to remote machine and execute it
scp /tmp/create_swap.sh $REMOTE_MACHINE:/tmp/
ssh $REMOTE_MACHINE "bash /tmp/create_swap.sh"

# Cleanup
ssh $REMOTE_MACHINE "rm /tmp/create_swap.sh"

How It Works

  • The script checks if the swap file already exists by running swapon --show on the remote machine.
  • If swap is already enabled, it exits.
  • Otherwise, it creates a 2GB swap file (/swapfile), sets the right permissions, and adds it to /etc/fstab so it’s automatically enabled after a reboot.

Usage

  1. Save the script as create_swap.sh and make it executable:

    chmod +x create_swap.sh
    
  2. Run the script with the remote machine name:

    ./create_swap.sh <remote-machine>
    

And that's it! The script takes care of everything for you, ensuring your VPS has a swap file ready to handle memory spikes.