Web

Linux Swap File Setup and SSH Hardening: What Should You Change?

Talha Aslan 20 min read 1 views

What is a Linux swap file and why does a server need one?

A Linux swap file is a regular file on disk that the kernel uses as overflow space when RAM runs short, moving rarely used memory pages there. It does not replace RAM. Instead, it gives memory spikes a buffer, so a process is less likely to get killed for lack of memory.

This guide covers two jobs that usually happen in the first hour on a new VPS. First, we set up a Linux swap file step by step. Then we harden SSH access with key based login, a restricted user list and a configuration you test before you trust it.

We are a digital marketing and web team, not a hosting company. So every command and setting name here comes from primary documentation: the swapon manual page, the Linux kernel docs and the OpenSSH manual. If your distribution differs, compare each step with its official docs.

Can swap replace RAM?

No. Even the fastest NVMe drive is far slower than memory. Therefore a server that swaps constantly gets slow: page responses stretch, and database queries queue up.

The real job of swap is a safety margin. For example, a nightly backup or a short traffic burst can push memory use over the edge for a few minutes. Without swap, the kernel's out of memory killer ends a process, and that process is often the database because it holds the most memory. With swap, the server slows down but stays up.

In addition, swap lets the kernel move idle pages out of RAM and leave more room for the file cache. As a result, frequently read files stay in memory longer. That said, this small gain does not fix a real shortage of RAM.

In short, treat swap like a spare tire. It gets you home, but you do not drive on it every day. If your site swaps all the time, the real fix is more RAM or a leaner application. Our guide to server side causes of a slow website walks through the usual suspects.

How do you check whether your server already has swap?

Start by looking at the current state. Some VPS images ship with a swap file, while others have none at all. Three commands tell you what you need:

swapon --show
free -h
cat /proc/swaps

The first command lists active swap areas with their type and size. If it prints nothing, the system has no active swap. The second shows RAM and swap usage in readable units. The third reads the kernel's own record, which is the source the other two rely on.

Next, look at the trend. High, steady swap use combined with a low "available" column for RAM means the server is under memory pressure. On the other hand, a few hundred megabytes of stable swap use is not a problem by itself. The kernel may simply have moved idle pages there.

Also check disk space, because a swap file takes up room on disk. The command df -h / shows free space on the root filesystem. If the disk is nearly full, clean up first.

How big should a Linux swap file be?

There is no single universal number. The right size depends on RAM, workload and whether you use hibernation. Servers almost never hibernate, so desktop rules of thumb do not map cleanly onto them.

Distributions publish their own guidance and update it over time. For instance, the Red Hat Enterprise Linux 9 documentation includes a recommendation table based on RAM ranges. Therefore we suggest you take the number from the current official docs of your own distribution, not from a blog post.

Still, ask yourself these questions before you decide:

  • Does your application spike in memory use, or is usage flat?
  • Does the database run on the same server, and how much memory did you give it?
  • How much free disk space can you spare for swap?
  • Does your provider cap disk writes or IOPS?

On a small VPS, picking a modest starting size and watching free -h for a few days beats starting with a big number. That is the main advantage of a swap file: you can resize it later with little effort.

Should you use a swap file or a swap partition?

Linux supports both. A swap partition is a separate area on the disk, while a swap file is an ordinary file on an existing filesystem. On a VPS, changing partitions after the fact is awkward, so a swap file is usually the practical choice.

CriterionSwap fileSwap partition
When you set it upAny time, while the system runsUsually at install time or during disk changes
ResizingTurn it off and recreate itRequires changing the partition table
Filesystem dependencyYes; no files with holes, extra rules on BtrfsNone, it uses the block device directly
Fit for a VPSWorks on most full virtualization plansRepartitioning is often impractical
Removalswapoff, fstab line, delete the fileswapoff, fstab line, reuse the partition

For most workloads on modern kernels, performance does not decide between the two. Flexibility does. The steps below use a swap file.

How do you create a Linux swap file step by step?

Creating a Linux swap file takes four steps: allocate the file, lock down its permissions, write a swap signature and switch it on. The example below builds a 2 GB file. Change the size to fit your own decision; this is a sample value, not a recommendation.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
swapon --show

The first line reserves 2 GB on disk. The second makes the file readable and writable only by root. This matters because swap holds data pushed out of memory, and other users should never read it.

The third line writes the swap signature. The fourth activates the space right away. Finally, the last command confirms the result; you should see a /swapfile row in the output.

At this point swap works, but it disappears after a reboot. To keep it, follow the fstab step in the next section. Also note that fallocate does not behave well on every filesystem, and we explain why right below.

Should you use fallocate or dd?

Both commands allocate the file, but they work differently. fallocate reserves space instantly without writing zeros, so it is very fast. dd actually fills the file with zeros from start to finish, which can take minutes for large files.

The swapon manual page makes an important point: the kernel expects to write to a swap file directly, without help from the filesystem. For that reason swapon rejects files with holes. According to the manual, files preallocated with fallocate may look like files with holes, depending on the filesystem. The manual calls dd with /dev/zero the most portable method.

On the other hand, the Red Hat docs prefer fallocate over dd on modern filesystems such as ext4 or XFS. In practice, our approach is simple. Try fallocate first. If swapon complains about holes, delete the file and rebuild it with dd.

sudo dd if=/dev/zero of=/swapfile bs=1M count=2048
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

Btrfs is a special case. The manual says Btrfs supports swap files only when the file carries the nocow attribute. So on Btrfs, follow the specific steps in your distribution's documentation.

How do you make swap permanent with /etc/fstab?

The swapon command only lasts until the next reboot. To bring swap back automatically, you add one line to /etc/fstab. Make a copy first, because a typo in fstab can disrupt boot.

sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap defaults 0 0' | sudo tee -a /etc/fstab

The line reads simply. The first field is the file path, the second is the mount point (none for swap), the third is the type and the fourth holds options. The two zeros turn off dump and filesystem check ordering. Some distribution docs write "sw" as the option; both forms are common.

Then test the change without a reboot:

sudo swapoff /swapfile
sudo swapon -a
swapon --show

swapon -a activates every swap entry in fstab. If your swap shows up, the line is correct. The Red Hat docs also suggest running systemctl daemon-reload after editing fstab on systemd based systems, so systemd picks up the new entry right away.

One more warning: do not add the same line twice. If you ran the command again by mistake, check with grep swap /etc/fstab.

What is swappiness and how do you tune it?

Swappiness controls how eagerly the kernel uses swap under memory pressure. According to the Linux kernel documentation, the value ranges from 0 to 200 and the default is 60. Lower values tell the kernel that swap I/O is expensive; higher values say it is cheap.

At 100, the docs say, the kernel applies equal pressure to the page cache and to swap backed pages. At 0, it does not start swapping until free and file backed pages drop below a certain watermark. In other words, 0 does not mean "swap off".

To read the current value and change it for now:

cat /proc/sys/vm/swappiness
sudo sysctl vm.swappiness=10

Here 10 is only a sample value. To keep the change across reboots, create a file under /etc/sysctl.d:

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

So should you lower it? On database servers, a lower value is a common choice because you want hot data to stay in RAM. However, make that call from measurements, not from a rule. Watch free -h and application response times for a few days before and after. For database tuning, see our guide on installing MySQL on Ubuntu and tuning performance.

How do you remove or resize swap?

Removing swap reverses the setup. You turn swap off, delete the fstab entry and only then remove the file. Order matters here; never delete an active swap file.

  1. Run sudo swapoff /swapfile to turn swap off. This moves swapped pages back into RAM.
  2. Open /etc/fstab in a text editor and delete the /swapfile line.
  3. Delete the file with sudo rm /swapfile.
  4. Confirm the result with swapon --show and free -h.

Keep one thing in mind: swapoff pulls swapped data back into memory. If RAM does not have room for it, the command fails or the server comes under heavy pressure. Therefore run swapoff during a quiet hour.

To grow swap, you follow the same path. Turn it off, recreate the file at the new size, then repeat the chmod, mkswap and swapon steps. The fstab line stays the same because the path has not changed. Alternatively, you can add a second swap file, although one file is usually simpler to manage.

Why can't you create swap on some VPS plans?

On some VPS plans, swapon fails with an "operation not permitted" style error. The most common reason is the virtualization type. With container based virtualization, your server shares the kernel with the host. As a result, kernel level settings such as swap belong to the provider, not to you.

In addition, some providers restrict swap in their terms because of disk wear or shared storage performance. In that case, even if you technically manage to enable swap, you may break the rules of your plan.

What should you do?

  • Check your provider's docs for the virtualization type and its swap policy.
  • Look for a built in swap option in the control panel.
  • If swap is not allowed, upgrade RAM or reduce the application's memory use.
  • When you pick a plan, prefer one with full virtualization.

We compare VPS, VDS and cloud servers in detail in VPS vs cloud server vs VDS. For the other questions to ask a host, see our guide on how to choose web hosting.

Which SSH hardening settings matter most?

Swap handles memory; SSH is the front door. Any SSH port that faces the internet soon draws automated password guessing. So the first goal is to make passwords useless and to narrow the door.

Here is the order we follow:

  1. Create an SSH key pair on your own computer and install it on the server.
  2. Confirm that you can log in with the key as a non root user with sudo rights.
  3. Disable password and keyboard interactive login.
  4. Disable direct root login.
  5. Limit login to specific accounts with AllowUsers.
  6. Test the config with sshd -t and confirm with a second session.
  7. Add extra layers such as a firewall and fail2ban.

The table below lists the defaults from the OpenSSH sshd_config manual for the settings we change, next to the target we suggest. Keep in mind that your distribution's packaged config may already override some of these defaults.

SettingOpenSSH defaultTarget
PubkeyAuthenticationyesyes
PasswordAuthenticationyesno
KbdInteractiveAuthenticationyesno (unless you use 2FA)
PermitRootLoginprohibit-passwordno
AllowUsersunset (everyone)admin accounts only
MaxAuthTries6a lower value, optional

How do you set up SSH key login?

Key based login swaps the password for a key pair. The private key stays on your computer, and the public key goes into the authorized_keys file on the server. Because no password ever crosses the network, brute force guessing loses its point.

The official Ubuntu OpenSSH server documentation shows how to create an Ed25519 key. Run these commands on your own machine:

ssh-keygen -t ed25519
ssh-copy-id deploy@203.0.113.10

The first command creates the key pair and asks for a passphrase. Do not leave it empty, because it protects the key if someone steals your laptop. The second command adds the public key to the user's authorized_keys file on the server. The IP in the example is a documentation address; use your own server's address.

Then open a new terminal and connect with ssh deploy@203.0.113.10. If you get in with only your key passphrase and no server password, the step is done. The Ubuntu docs also advise that authorized_keys must not be writable by others; chmod go-w ~/.ssh/authorized_keys handles that.

Never put your private key on the server, in email or in a shared folder. Each team member should create their own key, so when someone leaves you simply delete their line.

How do you disable PasswordAuthentication and root login?

Once key login works, turn off password login. The main config file is /etc/ssh/sshd_config. According to the Ubuntu docs, the very top of that file holds an Include line that reads every .conf file under /etc/ssh/sshd_config.d.

That detail matters. The OpenSSH manual says that for each keyword, the first value it reads wins, and Include files load in lexical order. Consequently, even if the main file says "no", an earlier file in sshd_config.d that says "yes" takes priority. Some cloud images drop a file there that turns password login on.

For that reason, we suggest you put your settings in a separate file whose name sorts first:

sudo nano /etc/ssh/sshd_config.d/00-hardening.conf

PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

For PermitRootLogin, the manual defines four values: yes, prohibit-password, forced-commands-only and no. The default, prohibit-password, blocks root from logging in with a password but still allows a key. The value "no" shuts off direct root login entirely, so you run admin tasks through sudo.

Also list the other files in that folder with ls /etc/ssh/sshd_config.d/. If you spot a conflicting setting, fix it too.

How do you limit SSH access with AllowUsers?

AllowUsers spells out who may log in over SSH. According to the manual, once you set it, only user names that match one of the listed patterns can log in. In other words, other accounts on the server lose SSH access even though they still exist.

For example, to allow only the deploy and admin users, add this line to your config file:

AllowUsers deploy admin

Patterns also accept the user@host form. That lets you accept a given user only from a given IP, for example AllowUsers deploy@198.51.100.25. However, use this only if you have a static IP. If your home or mobile IP changes, you lock yourself out. You can look up the details of an address with our IP lookup tool.

The most common mistake with AllowUsers is forgetting to add your own user name. So keep your current session open after the change and test with a fresh one. If you prefer to manage access by group, the AllowGroups setting in the manual works the same way.

As a team grows, documenting who can reach which server becomes important too. That is as much a management habit as a technical setting.

Does changing the SSH port improve security?

Only a little. Moving SSH off port 22 keeps most automated scanners away and cuts noise in your logs. However, a targeted attacker finds the new port quickly with a port scan. So a port change is noise reduction, not a security control.

Real protection comes from key login, disabled passwords and AllowUsers. With those three in place, a new port adds some comfort. Without them, it saves nothing.

If you still want to change it, follow this order:

  • Open the new port in the firewall first, or you cut off your own connection.
  • Update the Port line in your config.
  • On recent Ubuntu releases, SSH can run through systemd socket activation. The Ubuntu docs note that ssh.socket may handle port bindings, so follow the docs for your release.
  • Open a second session on the new port and confirm it works.
  • Finally, close the old port in the firewall.

If your cloud provider has a separate network firewall in its panel, open the new port there as well.

How do you test SSH changes without locking yourself out?

One typo in the SSH config can leave you outside the server. So use the same safe routine for every change. The Ubuntu docs recommend a write protected copy of the original file first:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original
sudo chmod a-w /etc/ssh/sshd_config.original

After you edit, test the syntax. sudo sshd -t checks the config and the keys; it prints nothing when all is well. sudo sshd -T prints the full effective configuration, so you can see which value won after the Include files.

sudo sshd -t
sudo sshd -T | grep -i passwordauthentication
sudo systemctl restart ssh.service

On Ubuntu the service is ssh.service. On RHEL based distributions it is usually called sshd, so check your own docs.

The key rule: do not close your current SSH session. A restart usually leaves open sessions alive. Open a second session in a new terminal window and confirm that login works. Only then close the first one. If something goes wrong, you still have the open session to restore the backup. It also pays to know your provider's web console or rescue mode as a last resort.

Where do fail2ban, 2FA and a firewall fit in?

These three layers sit on top of the basics above. None of them replaces key login, but each one shrinks the attack surface a bit more.

The firewall comes first. On Ubuntu with ufw, you allow SSH before you enable the firewall. Order is critical; if you do it the other way round, you drop your own connection.

sudo ufw allow ssh
sudo ufw enable
sudo ufw status

If you moved the port, use the new port number instead of "ssh". On cPanel servers, CSF is the usual choice instead of ufw; our CSF firewall guide has the details.

Fail2ban watches log files and temporarily bans IPs that fail repeatedly. With password login disabled, its main job becomes cutting log noise. We do not repeat the setup here; our fail2ban setup guide covers it step by step.

Two factor authentication adds a second proof next to the key. The OpenSSH AuthenticationMethods setting can require more than one method in sequence. Teams usually build it with TOTP modules through PAM. However, a bad setup can lock you out easily, so try it on a test server first.

When should you leave swap and SSH setup to your host?

You do not have to handle every server setting yourself. On managed or shared hosting, swap and SSH configuration already sit with the provider. Changing them there may even void your support coverage.

We suggest you hand the job to your hosting provider or an experienced sysadmin in these cases:

  • You do not know how to reach the server through a web console or rescue mode.
  • A live online store runs on the server and downtime is not acceptable.
  • Your container based VPS does not allow swap.
  • Company compliance rules demand a specific SSH policy.
  • You copy commands without understanding what they do.

On the other hand, if you run your own VPS and feel at home in a terminal, the steps in this guide are routine work. What matters is a backup before every change and a way back. You can review your plan with our website backup strategy guide.

Our team plans server preparation as part of web design and software projects. We explain how we split server duties with the host on our web design service and custom software development pages.

What else should you check at the application layer?

Hardening SSH locks the server's front door. However, your website is a separate door. A flaw in the web application can give someone access without touching SSH at all.

That is why you should plan infrastructure settings together with application security. Outdated plugins, weak admin passwords and loose file permissions are the most common risks. We summarize typical web app flaws in our OWASP Top 10 guide.

Also update system packages regularly. Every package, OpenSSH included, receives security patches from time to time. Turning on automatic security updates on Ubuntu lowers the risk of forgetting. Still, keep in mind that an automatic update may restart a service.

In short, server security is not one setting but a set of layers. Swap protects stability, SSH protects access, and application security plus backups complete the picture.

Linux swap file and SSH hardening checklist

Here are all the steps from this guide in one list. Follow this order when you set up a new server:

  1. Check the current state with swapon --show and free -h.
  2. Choose the Linux swap file size from your distribution's official docs and your workload.
  3. Create the file with fallocate or dd, then run chmod 600, mkswap and swapon.
  4. Add the fstab line and test it with swapon -a.
  5. Change swappiness only based on measurements.
  6. Create an Ed25519 key on your computer and install it with ssh-copy-id.
  7. Disable password and root login in a separate file under sshd_config.d.
  8. Limit login with AllowUsers.
  9. Test with sshd -t, confirm with a second session, then restart the service.
  10. Turn on the firewall and add layers such as fail2ban.

Setting up a Linux swap file takes a few minutes. SSH hardening needs more care, but done right once, it protects you for a long time. Both share the same rule: back up before you change anything, then test.

Frequently Asked Questions

Is it a problem to run a Linux server without swap?
Not always, but it is risky. If RAM comfortably covers your workload, a server without swap can run fine. However, during a sudden memory spike the kernel kills a process, and that is often the database. That is why a modest swap file works well as a safety margin on small VPS plans.
Why should a swap file have 600 permissions?
Because a swap file holds data moved out of memory. That data can include session details or even passwords. chmod 600 makes the file readable and writable only by root. Looser permissions could let other users on the server read that data, and mkswap usually warns you about insecure permissions in that case.
Does setting swappiness to 0 turn swap off?
No, it does not. According to the Linux kernel docs, at 0 the kernel does not start swapping until free and file backed pages fall below a certain watermark. So swap still gets used once memory pressure rises far enough. To turn swap off completely, run swapoff and remove the fstab line.
What happens if I lose my SSH key after disabling passwords?
You cannot log in over SSH, but you are usually not locked out for good. Most providers offer a web console or rescue mode. From there you add a new public key to authorized_keys. So keep a safe backup of your key and test your provider's console access before you actually need it.
Is PermitRootLogin no better than prohibit-password?
For most servers, no is the cleaner choice. prohibit-password lets root log in with a key only, while no shuts off direct root login completely. If admins work through personal accounts with sudo rights, your logs also show more clearly who did what. If automation tools need root, adapt them first.
Do I still need fail2ban after changing the SSH port?
Yes, but its role changes. A new port keeps most automated scanners away, yet a targeted attacker can still find it. Fail2ban blocks repeated failed attempts and cuts log noise. With password login off, the key does the real protection work, while fail2ban and the port change act only as extra layers.
  • linux swap file
  • swappiness
  • ssh hardening
  • sshd_config
  • vps management
  • server security
  • ubuntu server
Share:
Talha Aslan

Google Partner digital marketing expert. Hands-on with SEO, Google Ads, web design and e-commerce projects since 2012; every post here comes from that experience.

Next project

Let's talk about your project.

Your brief goes straight to Talha Aslan and team: strategy led by Talha, delivery by an experienced team. The first consultation is free; we listen and come back with a clear roadmap.