# How to add swap on Ubuntu

Swap is disk space used as virtual memory when RAM starts to run low. It is not as fast as real memory, but it can help you:

* avoid sudden process kills during memory pressure
* improve stability on smaller VPS plans
* absorb short usage spikes

### When it makes sense

Swap is especially useful on [VPS](https://ititanhosting.com/vps) plans with limited memory, such as 1–2 GB RAM. That said, if your workload constantly needs more RAM than the server has, swap is not a real substitute for upgrading.

### 1. Check current memory and swap

```bash
free -h
swapon --show
```

If `swapon --show` returns nothing, no active swap is configured.

### 2. Create a swap file

Example for a 2 GB swap file:

```bash
sudo fallocate -l 2G /swapfile
```

If `fallocate` does not work in your environment, use:

```bash
sudo dd if=/dev/zero of=/swapfile bs=1M count=2048 status=progress
```

### 3. Set secure permissions

```bash
sudo chmod 600 /swapfile
```

### 4. Format the file as swap

```bash
sudo mkswap /swapfile
```

### 5. Enable swap

```bash
sudo swapon /swapfile
```

Verify it:

```bash
swapon --show
free -h
```

### 6. Make it persistent after reboot

Edit `/etc/fstab`:

```bash
sudo nano /etc/fstab
```

Add this line at the end:

```
/swapfile none swap sw 0 0
```

### 7. Optional: tune swappiness

The `swappiness` value controls how aggressively Linux uses swap. Check the current value:

```bash
cat /proc/sys/vm/swappiness
```

For many VPS servers, a value like `10` or `20` is reasonable.

Apply it temporarily:

```bash
sudo sysctl vm.swappiness=10
```

Make it persistent:

```bash
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system
```

### Choosing a swap size

There is no perfect rule, but a practical guideline is:

* 1 GB RAM → 1–2 GB swap
* 2 GB RAM → 2 GB swap
* 4 GB RAM or more → 1–2 GB swap as a small buffer if needed

### Best practices

* Do not treat swap as the main fix for not having enough RAM.
* Monitor actual usage with `htop`, `free -h`, or `vmstat`.
* If the server swaps heavily all the time, performance can drop sharply.

### How to remove swap

If you want to disable it later:

```bash
sudo swapoff /swapfile
sudo rm /swapfile
```

Then remove the corresponding line from `/etc/fstab`.

### Conclusion

A properly configured swap file can make a small VPS more stable, especially during brief memory spikes.
