1. Home
  2. Delegate
  3. Linux
  4. Initial Server Setup with Ubuntu 16.04

Initial Server Setup with Ubuntu 16.04

Introduction

When you first create a new Ubuntu 16.04 server, there are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions. Make sure to have some time, since this is going to be a long tutorial. Before we start however, make sure to read through these basic safety practices:

  1. Install Software Updates regularly This protects you from exploits in installed software or you OS.
  2. Use Unique Passwords This is a practice most people forget about. If a cracker ever gets your password to some service where your E-Mail address is given and you have the same password for the E-Mail, the damage can be fatal.
  3. Use Two-Factor Authentication –> If we assume that someone somehow got your unique and strong password, you should still have some defense: 2FA. Most times this is an activation code that changes every few seconds and is send to your mobile while logging in. SHIFT offers the 2nd passphrase as your last defense. Use it!
  4. Use Strong Passwords –> There are different specifications of password, but 8 symbols are not enough anymore. For more specifications, look below.
  5. Use a Password Manager –> Managing passwords can be hard; You can either use a password manager on a safe system, or simply write them down in a notebook.

A secure password has:

  1. at least 15 characters
  2. uppercase letters
  3. lowercase letters
  4. numbers
  5. symbols, such as ` ! " ? $ ? % ^ & * ( ) _ - + = { [ } ] : ; @ ' ~ # | \ < , > . ? /

A secure password doesn’t have:

  1. your login or username
  2. your name, your friend’s name, your family member’s name, or a common name
  3. a dictionary word
  4. like your previous passwords
  5. your date of birth
  6. a keyboard pattern, such as qwerty, asdfghjkl, or 12345678

Step Zero – Tips & Tricks (Optional)

Before proceeding, make sure you are on your local system first! Add the IP of your VPS and hostname to your hosts file:

sudo nano /etc/hosts

If nano isn’t installed, do:

sudo apt-get install nano

At the bottom of /etc/hosts, type in your IP and a hostname, so you only have to remember the hostname instead of the IP address of your server. For this example, I added this to the bottom of the /etc/hosts file.

45.79.103.118 znode

Ping your server to make sure that the hostname resolution is working:

ping znode

You should get something similar to this response. Press Ctrl-C to stop the pinging.

Now you can connect to your VPS using your hostname, instead of the IP.

Step One — Root Login and Update

To log into your server, you will need to know your server’s public IP address. You will also need the password or, if you installed an SSH key for authentication, the private key for the “root” user’s account. If you have not already logged into your server, you may want to follow the first tutorial in this series, How to Connect to Your Droplet with SSH, which covers this process in detail.

If you are not already connected to your server, go ahead and log in as the root user using the following command (substitute the highlighted word with your server’s public IP address or hostname, if you created one in Step 0):

ssh [email protected]_server_ip

Complete the login process by accepting the warning about host authenticity, if it appears, then providing your root authentication (password or private key). If it is your first time logging into the server with a password, you will also be prompted to change the root password.

After login in, you should execute following command to update the package list and upgrade all the packages.

apt-get update && apt-get -y upgrade && apt-get -y dist-upgrade

If not already done, also install the necessary packages:

apt-get install git nano ufw

About Root

The root user is the administrative user in a Linux environment that has very broad privileges. Because of the heightened privileges of the root account, you are actually discouraged from using it on a regular basis. This is because part of the power inherent with the root account is the ability to make very destructive changes, even by accident.

The next step is to set up an alternative user account with a reduced scope of influence for day-to-day work. We’ll teach you how to gain increased privileges during the times when you need them.

Step Two — Create a New User

Once you are logged in as root, we’re prepared to add the new user account that we will use to log in from now on.

This example creates a new user called “sammy”, but you should replace it with a username that you like:

adduser sammy

You will be asked a few questions, starting with the account password.

Enter a strong password and, optionally, fill in any of the additional information if you would like. This is not required and you can just hit ENTER in any field you wish to skip.

Step Three — Root Privileges

Now, we have a new user account with regular account privileges. However, we may sometimes need to do administrative tasks.

To avoid having to log out of our normal user and log back in as the root account, we can set up what is known as “superuser” or root privileges for our normal account. This will allow our normal user to run commands with administrative privileges by putting the word sudo before each command.

To add these privileges to our new user, we need to add the new user to the “sudo” group. By default, on Ubuntu 16.04, users who belong to the “sudo” group are allowed to use the sudo command.

As root, run this command to add your new user to the sudo group (substitute the highlighted word with your new user):

usermod -aG sudo sammy

Now your user can run commands with superuser privileges! For more information about how this works, check out this sudoers tutorial.

Everytime you want to use the sudo command, it will ask you for your password. While this is a secure default, we need to disable it. First open the sudo configuartion:

sudo visudo

And then add USERNAME ALL=(ALL) NOPASSWD: ALL under #includedir /etc/sudoers.d:

#includedir /etc/sudoers.d
USERNAME ALL=(ALL) NOPASSWD:ALL

Note that you need to replace USERNAME with the user you created. This will allow that user to use sudo without entering a password. Press Ctrl+O to save the document, confirm the name with enter and then press Ctrl+X to exit the document.

Step Four — Add Public Key Authentication (Recommended)

The next step in securing your server is to set up public key authentication for your new user. Setting this up will increase the security of your server by requiring a private SSH key to log in.

a.) Generate a Key Pair

If you do not already have an SSH key pair, which consists of a public and private key, you need to generate one. If you already have a key that you want to use, skip to the Copy the Public Key step.

To generate a new key pair, enter the following command at the terminal of your local machine (ie. your computer):

ssh-keygen

Assuming your local user is called “localuser”, you will see output that looks like the following:

Generating public/private rsa key pair. Enter file in which to save the key (/users/localuser/.ssh/id_rsa):

Hit return to accept this file name and path (or enter a new name).

Next, you will be prompted for a passphrase to secure the key with. You may either enter a passphrase or leave the passphrase blank.

Note: If you leave the passphrase blank, you will be able to use the private key for authentication without entering a passphrase. If you enter a passphrase, you will need both the private key and the passphrase to log in. Securing your keys with passphrases is more secure, but both methods have their uses and are more secure than basic password authentication.

This generates a private key, id_rsa, and a public key, id_rsa.pub, in the .ssh directory of the localuser‘s home directory. Remember that the private key should not be shared with anyone who should not have access to your servers!

b.) Copy the Public Key

After generating an SSH key pair, you will want to copy your public key to your new server. We will cover two easy ways to do this.

Note: The ssh-copy-id method will not work on DigitalOcean if an SSH key was selected during Droplet creation. This is because DigitalOcean disables password authentication if an SSH key is present, and the ssh-copy-id relies on password authentication to copy the key.

If you are using DigitalOcean and selected an SSH key during Droplet creation, use option 2 instead.

Option 1: Use ssh-copy-id

If your local machine has the ssh-copy-id script installed, you can use it to install your public key to any user that you have login credentials for.

Run the ssh-copy-id script by specifying the user and IP address of the server that you want to install the key on, like this:

ssh-copy-id [email protected]_server_ip

After providing your password at the prompt, your public key will be added to the remote user’s .ssh/authorized_keys file. The corresponding private key can now be used to log into the server.

Option 2: Manually Install the Key

Assuming you generated an SSH key pair using the previous step, use the following command at the terminal of your local machine to print your public key (id_rsa.pub):

cat ~/.ssh/id_rsa.pub

This should print your public SSH key, which should look something like the following (Don’t
copy the values show in this example!
):

id_rsa.pub contents
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDBGTO0tsVejssuaYR5R3Y/i73SppJAhme1dH7W2c47d4gOqB4izP0+fRLfvbz/tnXFz4iOP/H6eCV05hqUhF+KYRxt9Y8tVMrpDZR2l75o6+xSbUOMu6xN+uVF0T9XzKcxmzTmnV7Na5up3QM3DoSRYX/EP3utr2+zAqpJIfKPLdA74w7g56oYWI9blpnpzxkEd3edVJOivUkpZ4JoenWManvIaSdMTJXMy3MtlQhva+j9CgguyVbUkdzK9KKEuah+pFZvaugtebsU+bllPTB0nlXGIJk98Ie9ZtxuY3nCKneB+KjKiXrAvXUPCI9mWkYS/1rggpFmu3HbXBnWSUdf [email protected]

Select your own public key, and copy it to your clipboard.

To enable the use of SSH key to authenticate as the new remote user, you must add the public key to a special file in the user’s home directory.

On the server, as the root user, enter the following command to temporarily switch to the new user (substitute your own user name):

su - sammy

Now you will be in your new user’s home directory.

Create a new directory called .ssh and restrict its permissions with the following commands:

mkdir ~/.ssh
chmod 700 ~/.ssh

Now open a file in .ssh called authorized_keys with a text editor. We will use nano to edit the file:

nano ~/.ssh/authorized_keys

Now insert your public key (which should be in your clipboard) by pasting it into the editor.

Hit CTRL-X to exit the file, then y to save the changes that you made, then ENTER to confirm the file name.

Now restrict the permissions of the authorized_keys file with this command:

chmod 600 ~/.ssh/authorized_keys

Type this command once to return to the root user:

exit

Now your public key is installed, and you can use SSH keys to log in as your user.

To read more about how key authentication works, read this tutorial: How To Configure SSH Key-Based Authentication on a Linux Server.

Next, we’ll show you how to increase your server’s security by disabling password authentication.

Step Five — Configure SSH Daemon

Now that your new user can use SSH keys to log in, you can increase your server’s security by disabling password-only authentication. Doing so will restrict SSH access to your server to public key authentication only. That is, the only way to log in to your server (aside from the console) is to possess the private key that pairs with the public key that was installed.

Note: Only disable password authentication if you installed a public key to your user as recommended in the previous section, step four. Otherwise, you will lock yourself out of your server!

a.) Disable password authentication

Login into your new user and open the SSH daemon configuration:

sudo nano /etc/ssh/sshd_config

Find the line that specifies PasswordAuthentication, uncomment it by deleting the preceding #, then change its value to “no”. It should look like this after you have made the change:

sshd_config — Disable password authentication
PasswordAuthentication no

Here are two other settings that are important for key-only authentication and are set by default. If you haven’t modified this file before, you do not need to change these settings:

sshd_config — Important defaults
PubkeyAuthentication yes ChallengeResponseAuthentication no

b.) Deactivate root and faster timeout

Next, we need to find the line that looks like this:

/etc/ssh/sshd_config (before)
LoginGraceTime 120
PermitRootLogin yes

Here, we have the option to disable root login through SSH. This is generally a more secure setting since we can now access our server through our normal user account and escalate privileges when necessary.

Modify this line to “no” like this to disable root login and change the LoginGraceTime to 60 or 30 seconds. This will disconnect SSH if you don’t login successfully in 60/30 seconds:

/etc/ssh/sshd_config (after)
LoginGraceTime 60
PermitRootLogin no

Disabling remote root login is highly recommended on every server!

c.) Change SSH Port

After that, you should change your SSH Port from the default to anything from 49152 to 65535 by finding a line called:

# What ports, IPs and protocols we listen for 
Port 22

As said, change that line to a number from 49152 to 65535 (in this case 55555):

# What ports, IPs and protocols we listen for 
Port 55555

d.) Deactivate X11 and limit SSH connections

Since we don’t need the X11 graphics forwarding, we will disable it. Move down further with the arrow keys to where it says X11Forwarding, which we will be changing as follows and limit the SSH connections to two:

Change from:

X11Forwarding yes
...
#MaxStartups 10:30:60

To:

X11Forwarding no
...
MaxStartups 2

Note that you need to un-comment this line to make it active, meaning that you must delete the # at the start!

When you are finished making your changes, save and close the file using the method we went over earlier (CTRL-X, then Y, then ENTER).

Type this to reload the SSH daemon:

sudo systemctl reload sshd

Password authentication is now disabled. Your server is now only accessible with SSH key authentication.

Step Six — Test Log In

Now, before you log out of the server, you should test your new configuration. Do not disconnect until you confirm that you can successfully log in via SSH.

In a new terminal on your local machine, log in to your server using the new account that we created. To do so, use this command (substitute your username and server IP address):

ssh -p new_ssh_port [email protected]_server_ip

If you added public key authentication to your user, as described in steps four and five, your private key will be used as authentication. Otherwise, you will be prompted for your user’s password.

Note about key authentication: If you created your key pair with a passphrase, you will be prompted to enter the passphrase for your key. Otherwise, if your key pair is passphrase-less, you should be logged in to your server without a password.

Once authentication is provided to the server, you will be logged in as your new user.

Remember, if you need to run a command with root privileges, type “sudo” before it like this:

sudo command_to_run

Step Seven — Set Up a Basic Firewall

a.) Preparation

Ubuntu 16.04 servers can use the UFW firewall to make sure only connections to certain services are allowed. We can set up a basic firewall very easily using this application.

sudo apt-get install ufw

First step is to configure the firewall and allow only the ports that we need to be open. For that we will first run the command to check if the firewall is running:

sudo ufw status

Then make sure the firewall is disabled:

sudo ufw disable

Now we must deny all incoming traffic with:

sudo ufw default deny incoming

b.) Opening Ports and activating

After that, we have enable the ports that we need open, and one of them is, of course, our newly set SSH port, in our case port 55555. If you want your delegate to run for testnet on port 9405, that one must be open and if you are running delegate for mainnet you need to open port 9305. Since we don’t need UDP, we will only enable TCP by adding a simple /tcp flag at the end of each ufw allow command:

sudo ufw allow new_ssh_port/tcp

If your delegate runs for testnet, enable port 9405 (tShift):

sudo ufw allow 9405/tcp

If your delegate runs for mainnet, enable port 9305 (mShift):

sudo ufw allow 9305/tcp

Afterwards, we can enable the firewall by typing:

sudo ufw enable

Type “y” and press ENTER to proceed. You can see that SSH connections are still allowed by typing:

sudo ufw status

Output

Status: active

If you install and configure additional services, you will need to adjust the firewall settings to allow acceptable traffic in. You can learn some common UFW operations in this guide.

Step Eight – Set Up Fail2Ban

a.) Preparation

Servers do not exist in isolation, and those virtual private servers with only the most basic SSH configuration can be vulnerable to brute force attacks. fail2ban provides a way to automatically protect virtual servers from malicious behavior. The program works by scanning through log files and reacting to offending actions such as repeated failed login attempts.

Install the fail2ban package:

sudo apt-get install fail2ban

b.) Copy the config file

The default fail2ban configuration file is located at /etc/fail2ban/jail.conf. The configuration work should not be done in that file, however and therefore we’ll instead make a local copy of it.

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

After the file is copied, you can make all of your changes within the new jail.local file. Many of possible services that may need protection are in the file already. Each is located in its own section, configured and turned off.

c.) Configure the Defaults in Jail.Local

Open up the the new fail2ban configuration file:

sudo nano /etc/fail2ban/jail.local

The first section of defaults covers the basic rules that fail2ban will follow. If you want to set up more nuanced protection on your virtual server, you can customize the details in each section.

You can see the default section below.

[DEFAULT]


# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip = 127.0.0.1/8
bantime = 600
maxretry = 3


# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
# This issue left ToDo, so polling is default backend for now
backend = auto


#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = [email protected]

Write your personal IP address into the ignoreip line. You can separate each address with a space. IgnoreIP allows you white list certain IP addresses and make sure that they are not locked out. Including your address will guarantee that you do not accidentally ban yourself from your own server.

The next step is to decide on a bantime, the number of seconds that a host would be blocked from the VPS if they are found to be in violation of any of the rules. This is especially useful in the case of bots, that once banned, will simply move on to the next target. The default is set for 10 minutes—you may raise this to an hour (or higher) if you like.

Maxretry is the amount of incorrect login attempts that a host may have before they get banned for the length of the ban time.

You can leave the backend as auto.

Destemail is the email that alerts get sent to. If you have a mail server set up on your droplet, Fail2Ban can email you when it bans an IP address.

Additional Details—Actions

The Actions section is located below the defaults. The beginning looks like this:

#
# ACTIONS
#


# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overridden globally or per
# section within jail.local file
banaction = iptables-multiport


# email action. Since 0.8.1 upstream fail2ban uses sendmail
# MTA for the mailing. Change mta configuration parameter to mail
# if you want to revert to conventional 'mail'.
mta = sendmail


# Default protocol
protocol = tcp
[...]

Banaction describes the steps that fail2ban will take to ban a matching IP address. This is a shorter version of the file extension where the config if is located. The default ban action, “iptables-multiport”, can be found at /etc/fail2ban/action.d/iptables-multiport.conf

MTA refers to email program that fail2ban will use to send emails to call attention to a malicious IP.

You can change the protocol from TCP to UDP in this line as well, depending on which one you want fail2ban to monitor.

d.) Configure the ssh-iptables Section in Jail.Local

The SSH details section is just a little further down in the config, and it is already set up and turned on. Although you should not be required to make any changes within this section, you can find the details about each line below.

[ssh]

enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 6

Enabled simply refers to the fact that SSH protection is on. You can turn it off with the word “false”.

The port designates the port that fail2ban monitors. If you have set up your virtual private server on a non-standard port, change the port to match the one you are using:

eg. port=55555

The filter, set by default to sshd, refers to the config file containing the rules that fail2ban uses to find matches. sshd refers to the /etc/fail2ban/filter.d/sshd.conf.

log path refers to the log location that fail2ban will track.

The max retry line within the SSH section has the same definition as the default option. However, if you have enabled multiple services and want to have specific values for each one, you can set the new max retry amount for SSH here.

e.) Restart Fail2Ban

After making any changes to the fail2ban config, always be sure to restart Fail2Ban:

sudo service fail2ban restart

You can see the rules that fail2ban puts in effect within the IP table:

sudo iptables -L

Step Nine– Add Swap Space

One of the easiest way of increasing the responsiveness of your server and guarding against out-of-memory errors in applications is to add some swap space. In this guide, we will cover how to add a swap file to an Ubuntu 16.04 server.

Warning

Although swap is generally recommended for systems utilizing traditional spinning hard drives, using swap with SSDs can cause issues with hardware degradation over time. Due to this consideration, we do not recommend enabling swap on DigitalOcean or any other provider that utilizes SSD storage. Doing so can impact the reliability of the underlying hardware for you and your neighbors. This guide is provided as reference for users who may have spinning disk systems elsewhere.

If you need to improve the performance of your server on DigitalOcean, we recommend upgrading your Droplet. This will lead to better results in general and will decrease the likelihood of contributing to hardware issues that can affect your service.

a.) What is Swap?

Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM. Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fall back for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

b.) Check the System for Swap Information

Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

We can see if the system has any configured swap by typing:

sudo swapon --show

If you don’t get back any output, this means your system does not have swap space available currently. If your system created swap space at the installation, you don’t need to create more.

You can verify that there is no active swap using the free utility:

free -h

Output

             total        used        free      shared  buff/cache   available Mem:           488M         36M        104M        652K        348M        426M
Swap:            0B          0B          0B

As you can see in the “Swap” row of the output, no swap is active on the system.

c.) Check Available Space on the Hard Drive Partition

The most common way of allocating space for swap is to use a separate partition devoted to the task. However, altering the partitioning scheme is not always possible. We can just as easily create a swap file that resides on an existing partition.

Before we do this, we should check the current disk usage by typing:

df -h

Output

Filesystem      Size  Used Avail Use% Mounted on
udev            238M     0  238M   0% /dev
tmpfs            49M  624K   49M   2% /run
/dev/vda1        20G  1.1G   18G   6% /
tmpfs           245M     0  245M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           245M     0  245M   0% /sys/fs/cgroup
tmpfs            49M     0   49M   0% /run/user/1001

 

The device under /dev is our disk in this case. We have plenty of space available in this example (only 1.1G used). Your usage will probably be different.

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

d.) Create a Swap File

Now that we know our available hard drive space, we can go about creating a swap file within our filesystem. We will create a file of the swap size that we want called swapfile in our root (/) directory.

The best way of creating a swap file is with the fallocate program. This command creates a file of a preallocated size instantly.

Since the server in our example has 512MB of RAM, we will create a 1 Gigabyte file in this guide. Adjust this to meet the needs of your own server:

sudo fallocate -l 1G /swapfile

We can verify that the correct amount of space was reserved by typing:

ls -lh /swapfile 
-rw-r--r-- 1 root root 1.0G Apr 25 11:14 /swapfile

Our file has been created with the correct amount of space set aside.

e.) Enabling the Swap File

Now that we have a file of the correct size available, we need to actually turn this into swap space.

First, we need to lock down the permissions of the file so that only the users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

Make the file only accessible to root by typing:

sudo chmod 600 /swapfile

Verify the permissions change by typing:

ls -lh /swapfile

Output

-rw------- 1 root root 1.0G Apr 25 11:14 /swapfile

As you can see, only the root user has the read and write flags enabled.

We can now mark the file as swap space by typing:

sudo mkswap /swapfile

Output

Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes)
no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

After marking the file, we can enable the swap file, allowing our system to start utilizing it:

sudo swapon /swapfile

We can verify that the swap is available by typing:

sudo swapon –show

Output

NAME      TYPE  SIZE USED PRIO
/swapfile file 1024M   0B   -1

 

We can check the output of the free utility again to corroborate our findings:

free -h

Output

              total        used        free      shared  buff/cache   available
Mem:           488M         37M         96M        652K        354M        425M
Swap:          1.0G          0B        1.0G

 

Our swap has been set up successfully and our operating system will begin to use it as necessary.

f.) Make the Swap File Permanent

Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

Back up the /etc/fstab file in case anything goes wrong:

sudo cp /etc/fstab /etc/fstab.bak

You can add the swap file information to the end of your /etc/fstab file by typing:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

g.) Tweak your Swap Settings

There are a few options that you can configure that will have an impact on your system’s performance when dealing with swap.

Adjusting the Swappiness Property

The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are “expensive” in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications’ memory profile or what you are using your server for, this might be better in some cases.

We can see the current swappiness value by typing:

cat /proc/sys/vm/swappiness

Output

60

For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

We can set the swappiness to a different value by using the sysctl command.

For instance, to set the swappiness to 10, we could type:

sudo sysctl vm.swappiness=10

Output

vm.swappiness = 10 

This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

sudo nano /etc/sysctl.conf

At the bottom, you can add:

/etc/sysctl.conf 
vm.swappiness=10

Save and close the file when you are finished.

Adjusting the Cache Pressure Setting

Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it’s an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:

cat /proc/sys/vm/vfs_cache_pressure

Output

100

As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing: sudo sysctl vm.vfs_cache_pressure=50

Output

vm.vfs_cache_pressure = 50 

Again, this is only valid for our current session.

We can change that by adding it to our configuration file like we did with our swappiness setting:

sudo nano /etc/sysctl.conf

At the bottom, add the line that specifies your new value:

/etc/sysctl.conf 

vm.vfs_cache_pressure=50

Save and close the file when you are finished.

h.) Swap Conclusion

Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these common problems.

If you are running into OOM (out of memory) errors, or if you find that your system is unable to use the applications you need, the best solution is to optimize your application configurations or upgrade your server.

What now?

Congratulations! After following these steps you have made a good and secure base for other applications, like a Shift node. However, security isn’t a state, it is a process that you have the responsibilty to keep up with. While some security measures are included in this guide, you should still read An Introduction to Securing your Linux VPS.

 

This article contains parts of “How To Protect SSH with fail2ban on Ubuntu 12.04” by Etel Sverdlovis licensed under CC BY-NC-SA 4.0,

Initial Server Setup with Ubuntu 16.04” by Mitchell Anicas licensed under CC BY-NC-SA 4.0,

How To Add Swap on Ubuntu 16.04” by Justin Ellingwood is licensed under CC BY-NC-SA 4.0

and Build a ZenCash Secure Node – Part 1 – Prepare the VPS.

 

Was this article helpful to you? Yes 2 No

How can we help?