How to Configure Uncomplicated Firewall (UFW) on Ubuntu 24.04

How to Configure Uncomplicated Firewall (UFW) on Ubuntu 24.04
JC Brian Refugia
Technical writer
Ubuntu Firewall
21.08.2024
Reading time: 8 min

Setting up a firewall is one of the fundamental steps in safeguarding an Ubuntu 24.04 installation. Security is an important part of running any server or system. A firewall restricts which services are permitted to communicate with the server, thus acting as a barrier between the system and any potential threats. On Ubuntu, the Uncomplicated Firewall (UFW) offers an intuitive frontend for controlling firewall rules. It makes setting up iptables, the robust but intricate underlying firewall mechanism, easier. UFW makes it simple to set up and manage their firewall settings, even if they have little experience with networking concepts. This increases system security without requiring a high level of technical expertise. With the help of this article, you will be able to install, configure, and manage UFW on Ubuntu 24.04, protecting the server from undesirable network traffic while maintaining the seamless operation of authorized services.

Hostman offers a cloud managed firewall that provides cutting-edge defense tailored for businesses of all sizes.

Prerequisites

  • A local computer or a cloud server with Ubuntu 24.04 installed
  • Root access or user with sudo privileges

Installing UFW

On Ubuntu 24.04, installing the Uncomplicated Firewall (UFW) is straightforward. Normally, Ubuntu has it pre-installed, but if it's not, one may easily install it on the machine by following the instructions below:

  1. Update the package lists to ensure to have the most recent information on package versions and dependencies. Run the command below: 

sudo apt update && sudo apt upgrade -y
  1. The below command can be used to install UFW on the machine.

sudo apt install ufw -y
  1. Once installation is complete, the default status of UFW is inactive. Check it using the command below:

sudo ufw status

Image1

Enabling UFW

You must enable UFW beforehand to begin securing the system. When UFW is enabled, it will begin enforcing both its default rules and any custom rules that have been established. If you are configuring a remote server, make sure to allow SSH connections before starting UFW, to avoid locking users out. Now that UFW is installed and operational, you can start creating firewall rules that meet the unique security needs. 

Enable UFW using the command below and type "y" to proceed.

sudo ufw enable

Image3

Allowing SSH Connections

Enabling the firewall before enabling SSH connections is crucial when deploying UFW on a server, particularly if if administering it remotely over SSH. SSH blocking may prevent you from accessing the server and render it unusable. 

On Ubuntu 24.04, you can enable SSH connections by following these steps:

  1. It is easy to permit SSH traffic using UFW. Use the following command to enable it.
sudo ufw allow ssh

Image9

  1. To confirm that the rule was successfully added, check the status of UFW by running thecommand below.
sudo ufw status

Image15

  1. If the SSH service is operating on a non-standard port, you can choose that port instead of the default by issuing the following command.
sudo ufw allow <custom_port>/tcp

Understanding UFW Default Policies

It's critical to learn about the default policies that UFW applies to incoming, outgoing, and forwarded traffic before digging into custom firewall rules. These default policies provide the firewall's baseline behavior, which can subsequently be adjusted with particular rules to permit or prohibit particular kinds of traffic. 

  1. UFW prevents all incoming connections to the server by default. This security precaution keeps unwanted users from accessing the system.  Any request that comes in from outside the system will be rejected unless a particular rule is configured to authorize it. Requests for SSH, FTP, HTTP, and HTTPS are included in this. 

  2. By default, UFW permits all outgoing connections. This implies that there are no restrictions on the connections the server can make to other servers or services. Because outgoing traffic is normally safe, this policy allows the server to access the internet, download updates, and connect to other services without requiring any additional settings.

  3. Since UFW's default forwarding policy is set to refuse, all forwarded traffic is blocked. Packets that are received by the firewall and subsequently forwarded to a different location are referred to as forwarded traffic. This is especially important for systems that serve as gateways or routers. The server must modify this policy if it is intended to forward traffic between networks.

Allowing and Denying Specific Ports and Services

The ability of UFW to simply control which ports and services are granted or denied access to the system is one of its main features. This feature is necessary to secure the Ubuntu 24.04 server and manage traffic. Using UFW, you can use this method to enable or block particular ports and services.

  1. To enable traffic on a specific port, run the ufw allow command followed by the port number. In this example, to allow http (port 80), run the command below.
sudo ufw allow 80/tcp

Image4

  1. To allow https (port 443), run the command below.
sudo ufw allow 443/tcp

Image20

  1. If a non-standard port is used by the application, the port can also specify using the command below.
sudo ufw allow <custom_port>/tcp

For example:

sudo ufw allow 3026/tcp

Image16

Traffic on port 3026, which is frequently used for database configurations, is now permitted.

  1. Likewise, in order to prevent access, you can restrict traffic on a particular port, run the command below.
sudo ufw deny 80/tcp

Image12

Checking UFW Status and Rules

After configuring Ubuntu 24.04's UFW (Uncomplicated Firewall), it's critical to frequently check the firewall's status and go over the rules that have been set up. By doing this, you can be sure the firewall is up and running as it should. To inspect the current firewall rules and verify the status of UFW, run the following command: 

sudo ufw status

Image2

Managing UFW Application Profiles

Predefined application profiles included in Ubuntu 24.04's UFW (Uncomplicated Firewall) make it easier to grant or restrict traffic for particular services. Firewall management is made easier by these profiles, which include preconfigured rules for popular services including SSH, POSTIFX, OPENSSH, HTTP, HTTPS, and others. Managing UFW application profiles can be done as follows.

  1. Use the following command to view every application profile that is available on the system.
sudo ufw app list

Image17

  1. Use the below command to view the rules included in a particular application profile. The ports and protocols that the profile controls will be displayed in the output.
sudo ufw app info <application_name>

For example:

sudo ufw app info OpenSSH

Image18

  1. The application profile that you wish to use can be allow with UFW once it has been identified. For instance, use the following command to enable HTTP traffic.
sudo ufw allow http

Image11

  1. Likewise, the deny command can be used to prevent traffic for a certain application profile. For example, use the following command to stop all communication related to the HTTP.
sudo ufw deny http

Image5

  1. If a rule related to an application profile is no longer required, it can be deleted using the following command:
sudo ufw delete allow http

Image6

Disabling UFW

Even though Ubuntu 24.04's UFW (Uncomplicated Firewall) is an effective tool for controlling firewall rules and system security, there may be circumstances in which it needs to be turned off, either permanently or temporarily. Unless another firewall or security solution is in place, disabling UFW will halt the firewall and erase all active rules, leaving the system unsecured.

  1. To disable UFW, run the below command. By using this command, you can successfully turn off the firewall and stop the UFW service. 
sudo ufw disable

Image8

  1. Use the command below to verify that UFW has been successfully disabled. The status output should show below.
sudo ufw status

Image14

Troubleshooting Common Issues

Although UFW (Uncomplicated Firewall) is meant to be user-friendly, there could be some problems with installation or firewall rule management. Here are some typical issues that may run into and solutions for issues.

  1. If UFW is not listed on the installed packed, try reinstalling it by running sudo apt update and sudo apt install ufw respectively.

  2. If the installation fails to install, look for issues in your sources or package management. You can also try apt update and apt clean.

  3. Conflicting firewall service. Before activating UFW, make sure that all other firewall services, such as firewall and iptables, have been stopped and deactivated. For further information, review the UFW logs if the issue continues. Useful command is sudo tail -f /var/log/ufw.log.

  4. Once UFW is enabled, you cannot connect remotely to the server and SSH access is restricted. If the you are locked out due to UFW blocking SSH, you need to access the server on the console and run command sudo ufw allow ssh to regain access.

Conclusion

In conclusion, one of the most important steps in protecting Ubuntu 24.04 is configuring the Uncomplicated Firewall (UFW), which controls inbound and outbound network traffic. Because of its intuitive interface, UFW makes firewall control simple enough even for individuals with little experience with Linux system administration. You can effectively control traffic to and from the server by following the instructions to install UFW, create default policies, allow or deny certain ports and services, and manage application profiles. Monitoring the firewall rules and UFW status on a regular basis guarantee that the system is always shielded from unwanted access. Whether it's administering a production environment or protecting a personal server, UFW offers a reliable and simple way to improve the security of the system. By adding the capability to diagnose common problems, one can keep the firewall configuration secure and effective for what is needed.

Ubuntu Firewall
21.08.2024
Reading time: 8 min

Similar

PostgreSQL

How to Install PostgreSQL on Ubuntu

PostgreSQL is a well-known relational database management system that provides high-availability features. These are renowned for their functionalities, such as support for complex statements, views, triggers, and foreign keys. PostgreSQL is installed on Ubuntu to provide a secure as well as flexible DB infrastructure. By installing it on the Linux distribution, you can enable and deal with the vast data in an efficient and secure manner. This infrastructure is designed to deal with different workloads, from single-machine apps to large internet-facing apps with multiple concurrent users. In this tutorial, we will walk through installing and setting up PostgreSQL on Ubuntu. Installing PostgreSQL on Ubuntu Ubuntu comes with the PostgreSQL package in its default repositories. You can install it on a Linux system following the given steps. It downloads the stable package. This is important for DB analysts, administrators, and industries that require a dependable DB solution for managing a large volume of data.  Let’s move forward into each step of installing PostgreSQL with detailed explanations on Ubuntu. Step 1: Refresh Ubuntu Repository First, refresh the Ubuntu package indexes. It is useful for maintaining system stability and security: sudo apt update Step 2: PostgreSQL Installation  PostgreSQL is included in Ubuntu's default repositories, making installation straightforward. To install it with some additional tools, execute the below command: sudo apt install -y postgresql postgresql-contrib Here: postgresql: The core PostgreSQL DB server. postgresql-contrib: Additional utilities and extensions useful for DB. Step 3: Start and Enable Services It is essential to enable the PostgreSQL service after installation and ensure it starts automatically upon bootup. The installed package utilizes the systemd daemon, which deals with the DB server runtime operations.  Run the commands below to make sure the DB server automatically initializes when the server boots up. Let’s initialize the service: sudo systemctl start postgresql And enable it so that it launches automatically when the machine boots up: sudo systemctl enable postgresql Step 4: Verify Installation To verify if the installed package is operating properly, check out its status through the below: sudo systemctl status postgresql In the figure, you can see an active status. It represents the services that are correctly running. Step 5: Access Shell Finally, switch to the PostgreSQL user account and launch the CLI to interact with database operations. Here, the -i flag provides an interactive login shell: sudo -i -u postgres The above display gives access to a user account. Once you're in the user environment, launch the CLI through the given command: psql As you can see in the above screenshot, this command launchs the CLI, where users can perform multiple operations by executing commands. Step 6: Basic Database Commands The creation of a database and a new user for any application is a good practice rather than using the root. In this way, a particular user can access the shell interface and run basic statements on the particular database. Here are general commands with thorough explanations and examples: Creation of the New Database To prevent conflicts, ensure data integrity and control access privileges for different applications or users, you need to create a new database. For creation, use the given command within the shell: CREATE DATABASE hostmandb; The screenshot shows that a database has been created. Creation of the New User Create a customized user and set a strong password: CREATE USER hostman_user WITH ENCRYPTED PASSWORD 'Qwer1234'; We have created a hostman_user with the password Qwer1234. Give Privileges to the Created User You can grant hostman_user complete privileges to the hostmandb through the given command. This allows controlled accessibility to database objects, enhancing data integrity as well as security: GRANT ALL PRIVILEGES ON DATABASE hostmandb TO hostman_user; Exit Shell For closing the shell, you can utilize the \q option as below: \q The figure shows that the shell has been exited. Finally, you can exit the user environment by executing the given command: exit The output confirms that you have returned to the main system user account. Access a Database as the Particular User You can connect to the particular database from the specific user account through the -U flag: psql -U hostman_user -d hostmandb -h 127.0.0.1 -p 5432 Here: -U hostman_user: Indicates the user. -d hostmandb: Indicates the database name. -h 127.0.0.1: Indicates the host (local machine). -p 5432: Indicates the PostgreSQL default port. In the given output, you can see that the user hostman_user has accessed the hostmandb console. Listing of All Databases View all databases and check whether the hostmandb database is available or not: \l In the figure, you can see that the database hostmandb is listed. Switch/Connect to the Particular Database To switch to a specific database, such as hostmandb, within PostgreSQL, use the \c command: \c hostmandb The above output confirms that the postgres user has successfully connected to the hostmandb database. Creation of the Particular Table To create a customized table, use the below statement. In our example, we create a hostmantb table: CREATE TABLE hostmantb(    id SERIAL PRIMARY KEY,    name VARCHAR(100),    age INTEGER,    department_id INTEGER); Here: id SERIAL PRIMARY KEY: It creates an auto-incrementing primary key column with the name id. name VARCHAR(100): It creates a name column that can store up to 100 characters. age INTEGER: It creates an age column that stores integer values. department_id INTEGER: This line creates a department_id column that stores integer values. The outcome of the above screenshot confirms that the table hostmantb is successfully created with specific attributes. List All Tables in the Particular Database For listing all tables in the hostmandb database, use the \dt command: \dt It displays all tables as well as confirms that the hostmantb is listed above. Overview a Table's Structure You can view the structure of the created table through the \d command. Let’s display the structure of hostmantb table: \d hostmantb In the above figure, you can see the complete structure of hostmantb table with id, name, age, and department_id having specific types. Input Entries into a Particular Table To input entries into a hostmantb table, use the below statement. This way, we input the values Peter, 35, and 1 to the columns name, age, and department_id, respectively: INSERT INTO hostmantb(name, age, department_id) VALUES ('Peter', 35, 1); The output confirms that we have successfully input data into the hostmantb table. Select All Data from a Particular Table You can select all data from the hostmantb table through the below statement: SELECT * FROM hostmantb; Modify Data in Particular Table For modifying data in hostmantb, you can utilize the below statement. For example, set the age column to 40 for the row where the name column equals Peter: UPDATE hostmantb SET age = 40 WHERE name = 'Peter'; The output confirms that the age column is updated. Remove Data from the Particular Table In this section, you can remove data from the specific table through the DELETE statement. It deletes all entries from the hostmantb table where the value in the name column is Peter: DELETE FROM hostmantb WHERE name = 'Peter'; In the screenshot, one entry from the hostmantb table is removed. Exit CLI You can easily exit the CLI via the \q utility: \q This tutorial has given you thorough guidelines for every step involved in installing as well as setting PostgreSQL on Ubuntu.  Conclusion By installing PostgreSQL on Ubuntu, you can optimize the DB infrastructure. PostgreSQL is often chosen for its freely available nature, which allows for customization, the system's stability and security features. In addition, PostgreSQL's supporters' help and comprehensive guide make it simpler to enhance operations and troubleshoot problems.  This combination makes sure that the DB system is both powerful as well as adaptable to several needs. In this tutorial, there are a lot of fundamental DB commands to get you started with database administration. Therefore, you will be able to create databases, and users and perform basic tasks.
24 January 2025 · 7 min to read
Firewall

How to Install CSF (ConfigServer Security & Firewall) on Ubuntu 22.04

ConfigServer Security & Firewall (CSF) is a highly regarded tool for securing Linux servers against varying cyberattacks. Its robust functionality and simple interface proves that it is the best choice for system administrators. Whether you're managing a small server or large network, this tool provides an effective defense mechanism which is easy to deploy and manage. The below manual discusses the installation process and configuration of this tool on Ubuntu 22.04 LTS to maximize protection and performance of the server. Advantages of Usage of CSF Firewall on Ubuntu 22.04 LTS This versatile security solution has a variety of benefits tailored for servers using Linux as an operating system. User-Friendly Management With an easy-to-edit configuration file and simple command-line utilities, it ensures even novice administrators can quickly implement server security measures. Powerful Security Features Port Restrictions: Secure sensitive services like MySQL (port 3306) and SSH (port 22) by allowing or denying specific traffic. DDoS Attack Mitigation: Safety against high-traffic denial-of-service attempts. False Login Notifications: Automatically blocks IPs after repeated false login attempts to protect from brute force attacks. GeoIP Filtering: Restriction ofentry from certain geographic regions which gives enhanced security Effortless Update Integrated with the system's package manager, CSF updates seamlessly, making sure that firewall contains the latest security patches. Low Resource Consumption Optimized for performance, this tool works without placing unnecessary strain on system resources. Custom Alerts and Logs Receive real-time notifications for security events and go through detailed logs to monitor server activity. Step-by-Step Guide to Install CSF on Ubuntu 22.04 LTS Below is a detailed manual which explains installing it on Ubuntu 22.04 LTS. Step 1: Updating the System First, update the system’s package repository to make sure you have the latest software. To update the system’s package repository, use the following command: sudo apt update && sudo apt upgrade -y Step 2: Installation of Dependencies CSF relies on some dependencies to function appropriately. To install dependencies, use command below: sudo apt install -y perl libwww-perl liblwp-protocol-https-perl iptables nano Essential Dependencies: Perl: It is a programming language. Many of the CSF scripts and configuration tools are written in Perl. Installing perl will ensure that the system will run necessary scripts to manage firewall operations properly. libwww-perl and liblwp-protocol-https-perl: These libraries handle HTTP & HTTPS requests. CSF uses them to fetch updates, download remote blocklists, and securely manage real-time threat data feeds over HTTPS, enhancing firewall’s ability to keep itself updated with the new security information. iptables: Serving as the foundation for the Linux firewall functionality, iptables is integral for operations. It allows to define and implement traffic filtering rules, block specific ports, and restrict connectivity by IP addresses at the kernel level. nano: While optional, it is included to simplify the method of editing the configuration files directly from the terminal. It enables system administrators for doing quick modifications to firewall settings while staying in terminal. Step 3: Download and install CSF The package is available to download through its official website. For downloading, run these commands: cd /usr/srcsudo wget https://download.configserver.com/csf.tgz Extract the files: sudo tar -xvzf csf.tgz For installation, go to the extracted directory:  cd csf And execute the installer by running the following command: sudo sh install.sh When the installation is complete, it will look like the following: To confirm installation, check the CSF version by running: sudo csf -v CSF version will appear on the screen: Step 4: Configure CSF Firewall Settings CSF needs to be configured according to the user’s needs. There are two ways to configure it, through GUI and through terminal. By Terminal For this, we will perform changes in csf.conf located at /etc/csf/csf.conf. Use the following command to open the csf.conf file: sudo nano /etc/csf/csf.conf Output: Do the following changings for basic firewall protection: Testing mode (TESTING = "1") temporarily clears firewall rules to prevent being locked out during configuration. Enable it until you verify all settings, then disable it (TESTING = "0") to activate full protection. TESTING = "0" Allow MySQL Port: If you need to allow using MySQL, update csf.conf as below: TCP_IN = "22,3306" After modifications have been done in configuration, apply them, using: sudo csf -rsudo systemctl restart csf By GUI This tool already has a GUI mode built in. It needs to be configured through the csf.conf and a few commands. Following is the procedure of enabling it. 1. Install prerequisites: To install prerequisites, use the following command: apt-get install libio-socket-ssl-perl libcrypt-ssleay-perl \                    libnet-libidn-perl libio-socket-inet6-perl libsocket6-perl 2. Perform amendments in csf.conf: Perform edits in csf.conf to enable the UI mode and allow endpoints. Also update the username and password for UI. Note that the default username and password have to be updated. So to access the csf.conf, use the following command: sudo nano /etc/csf/csf.conf Now find ui = "0" and convert it to "1". This will enable the UI mode. Then find UI_PORT =  and write an entry of 7171. This will be the specific gateway on which you can interact with the GUI. Be sure that the port number is always bigger than 1024. After these, also edit the UI_USER and UI_PASSWORD. If the default UI_USER and UI_PASSWORD are not updated the UI will not work. Its a MUST to edit these from default values. Place the same port in TCP_IN and TCP_OUT.  Enter this command to add your IP address to ui.allow file: sudo echo "your_IP_adress" >> /etc/csf/ui/ui.allow In this command you have to paste your IP address. If you do not know your IP address, then you can just google "Whats my IP" and it will show you your IP. Just copy and paste in the above command and hit enter. Then in the terminal, type: csf -rsystemctl restart csfsystemctl restart lfd This will properly apply the ammendmets you have performed. Now, your UI has been set up. Now you need to enter your IP address with the endpoint you allowed (7171). Finally, interact with the UI. To connect with the GUI, you need to type the IP of the server along with the port that you set (7171) in your browser. In my case it was the following: 195.133.93.222:7171 195.133.93.222: The public IP address of the server 7171: Gateway number which I set Now you have the GUI. Additional CSF Firewall Commands With the tool now installed, you can make additional commands that can be highly useful for enhancing firewall management. Following is some detail: To block an IP address: sudo csf -d <IP_ADDRESS> To allow an IP address: sudo csf -a <IP_ADDRESS> To view status: sudo csf -l To restart: sudo csf -r Setting Up Alerts in CSF Activating notifications allows the admins of the server to get timely updates on important events, such as IP blocks, failed login attempts, and other security incidents. These are important in quickly detecting, as well as addressing safety risks. Below is the explanation about setting up notifications via email. Updating the Configuration File Use a text editor like Nano to open the tool’s main configuration file by writing: sudo nano /etc/csf/csf.conf Search for the line starting with LF_EMAIL_ALERT. This setting determines whether CSF sends email notifications. LF_EMAIL_ALERT = "0" Change the value from 0 to 1 to enable email notifications. LF_EMAIL_ALERT = "1" Find the LF_ALERT_TO option in the file, which defines the recipient email for alerts. Add the preferred email here: LF_ALERT_TO = "[email protected]" Define email of the sender by utilizing the option LF_ALERT_FROM. The notifications will be sent from this email address: LF_ALERT_FROM = "[email protected]" Press CTRL + O to save changes and CTRL + X to exit Nano. Restart CSF and LFD: sudo csf -rsudo systemctl restart lfd Customizing Alert Types You can customize which types of events would trigger email notifications. A few common options in the config are below: Login Failures: Controlled by LF_ALERT_LOGIN. Blocked IP Alerts: Enabled by LF_EMAIL_ALERT. Excessive Resource Usage: Configured via LF_ALERT_RESOURCE. For example, to enable login failure notifications, set: LF_ALERT_LOGIN = "1" Benefits of Email Notifications Real-Time Monitoring: Immediate awareness of suspicious activities or potential threats. Quick Response: Reduces the time between detecting and mitigating safety issues. Audit Trail: Email warnings provide a record of important safety events. By enabling notifications, it becomes an even more proactive tool in managing server safety. Example: Configuring CSF for WordPress Here's how to configure CSF to meet the requirements for a server hosting WordPress (WP), MySQL, and Redis: 1: Open the CSF configuration file: sudo nano /etc/csf/csf.conf 2: Allow endpoints 80 (HTTP) and 443 (HTTPS). These are required for serving the WordPress site. Find the line that starts with TCP_IN and modify it as follows: TCP_IN = "22,80,443,3306,6379" Explanation: 22: SSH access 80: HTTP for WordPress 443: HTTPS for WordPress 3306: MySQL gateway 6379: Redis gateway 3: Add a custom rule to limit interaction to Redis (port 6379) from the internal network only. Find the csf.allow file and add: 192.168.1.0/24 6379 # Internal network access to Redis Replace 192.168.1.0/24 with your internal network's CIDR notation. 4: Restrict MySQL connectivity. Allow MySQL authorization from internal network. In the csf.allow file, add: 192.168.1.0/24 3306 # Internal network access to MySQL Allow MySQL access from an external developer IP. In the same csf.allow file, add: 203.0.113.5 3306 # Developer IP access to MySQL Replace 203.0.113.5 with the developer's external IP address. 5: Restrict SSH Access. To allow SSH visibility only from a specific subnet, add the subnet to csf.allow: 192.168.1.0/24  # SSH access from the specific subnet Also, explicitly deny SSH visibility from all other IPs in csf.deny: ALL 22 # Block SSH for all except explicitly allowed IPs 6: Apply changes by restarting CSF and LFD: sudo csf -rsudo systemctl restart lfd 7: Verify that the connections points are correctly opened: sudo csf -l Check specific IP connectivity using: csf -g <IP_ADDRESS> Conclusion Using ConfigServer Security & Firewall on Ubuntu 22.04 LTS significantly improves the safety of the server. Along with its advanced functions like managing gateways, DDoS protection, and warnings in real-time, it also provides a comprehensive solution for safeguarding servers of Linux. To find more about different options and settings of this tool, check its official website. By utilizing this guide, you'll establish a robust firewall infrastructure capable of defending against modern cyber threats while maintaining optimal server performance. In addition, you can install Ubuntu on our cloud VPS server.
21 January 2025 · 9 min to read
Ubuntu

How To Add Swap Space on Ubuntu 22.04

Managing resources efficiently is vital for maintaining the performance and stability of the OS. In this article, the methods of adding swap space to Ubuntu 22.04 is outlined to help users boost their platform's capacity to carry on memory-intensive activities. Swap space acts as a virtual extension of physical memory (RAM), allowing the system to offload inactive processes when it is fully utilised. While Ubuntu 22.04 is highly efficient in memory management, adding or increasing paging area can be a practical solution for environments with small data storage unit or when running resource-heavy applications. This article provides a step-by step approach in creation, configuration, and optimisation of swap space, ensuring a smooth and efficient setup tailored to everyone's needs. Prerequisites Before adding swap space on Ubuntu 22.04, make sure the following prerequisites are satisfied to avoid potential issues: Administrative Privileges: User must have root or sudo access to the platform to execute commands for creating and configuring swap space. Existing Disk Volume: Confirm that the instance has sufficient free disk storage to allocate for the desired swap size. Deploy the following instruction to check disk space: df -h Current Status: Determine whether a swap space already exists and come up with the decision to expand it. Utilise the instruction below to verify: sudo swapon --show Suitable Performance Needs Assessment: Determine the required capacity of the swap space according to the current storage resource and workload. A common rule is to have at least same amount as the RAM size, but this may vary depending on your use case. What is Swap A crucial part of Linux memory management, swap space is intended to improve system performance and stability by increasing the system's accessible capacity beyond the physical random-access memory (RAM). The OS frees up memory for running processes by offloading idle or seldom used data to the paging space area when the RAM is completely utilised. This procedure enables the system to manage resource-intensive tasks more effectively and keeps apps from crashing because of memory shortages. Depending on the demands of the user, swap can be implemented in Ubuntu as a file or as a separate disc. This can be useful, but it cannot take the place of enough RAM. Because disc storage has slower read and write rates than physical memory, an over-reliance on this might result in performance loss. Optimising system performance requires an understanding of swap's operation and proper configuration, especially for tasks like managing apps on platforms with limited RAM, operating virtual machines, or compiling huge codebases. Swap Advantages Swap space is an important part of Linux environment memory management because it provides a number of benefits. The following advantages are offered by swap: Prevents System Crashes Supports Memory-Intensive Applications Enhances Multitasking Smoother multitasking without sacrificing speed for platforms managing numerous processes at once by balancing memory use by offloading less important operations. Provides Flexibility Swap space allows for the dynamic addition or resizing of paging space, which facilitates system requirements adaptation without requiring disc repartitioning. Extends Uptime Period It is a short-term fix to increase stability and prolong its uptime under high loads in situations where replacing physical memory is not immediately practical. Facilitates Hibernation Swap is crucial for systems set up to utilise the hibernate feature since it keeps the contents of the RAM in place when the system is turned off, enabling a smooth restart. Supports Low-Memory Systems For lightweight systems, this is beneficial because it guarantees that critical operations continue to run even when memory is limited on devices with little physical memory. Swap is essential for increasing overall system resilience and flexibility, especially in resource-constrained contexts, even while it cannot replace physical RAM and shouldn't be over-relied upon. Swap Disadvantages Although swap space has several benefits for memory management, there are a few significant drawbacks that should be taken into account when setting it up. Slower Performance Compared to RAM Increased Disk Wear Latency in Resource-Intensive Tasks When the system relies heavily on swap, tasks that require high memory bandwidth, such as video editing or large-scale data analysis, may experience significant delays due to slower data transfer rates. Limited Effectiveness in Low-RAM Scenarios While swap can extend memory, it is not a substitute for adequate RAM. On systems with extremely low physical memory, relying on swap may not be enough to handle modern applications efficiently. Hibernation Dependency If the swap space is insufficient, hibernation may fail as it requires swap to store the contents of the RAM. Misconfigured swap sizes can lead to system errors during hibernation attempts. Additional Storage Allocation Allocating swap space reduces the available storage for other purposes. For systems with limited disk capacity, dedicating a portion to swap may not be feasible. Complexity in Configuration Optimising swappiness and settings require careful planning and monitoring. Poor configuration may lead to either underutilisation or excessive reliance, both of which impact system performance. How to Add Swap Space by Creating a Swap File Making a swap file in Ubuntu 22.04 to increase swap space is a simple procedure that can assist boost system performance, particularly on systems with low RAM. Here is a thorough, step-by-step guide to assist you with the process: Make sure swap space is enabled before making a new file. Run the instruction below. sudo swapon --show Based on the RAM capacity and usage needs, choose the swap file's size. A typical rule of thumb is: For systems with less than 2 GB of RAM, swap size is equal to RAM size × 2. For systems with more than 2 GB of RAM, swap size equals RAM size. Choose the location of the file, which is often the root directory. Adjust to the user's preferred swap size. To do it, use the fallocate command. sudo fallocate -l 4G /swapfile If fallocate is unavailable or gives an error, employ the dd command. sudo dd if=/dev/zero of=/swapfile bs=1M count=4096 bs=1M: Sets the block size to 1 Megabyte. count=4096: Creates a 4GB file (4096 × 1MB). Verify that the permissions are configured appropriately to prevent unauthorised access. Execute the following command. sudo chmod 600 /swapfile It is necessary to format the file as swap space. After that, swap can be activated. Execute the command listed below.       sudo mkswap /swapfile sudo swapon /swapfile To verify if it has been added, use the instructions listed below, appropriately. sudo swapon --show free -h Add the swap file to the /etc/fstab file to guarantee it stays active following a reboot. Perform the following steps. Backup the fstab file before editing. sudo cp /etc/fstab /etc/fstab.bak Add the swap record in fstab. echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab Validate using command below. cat /etc/fstab Configuring Swappiness (Optional) Swappiness controls the kernel's use of swap space. 60 is the default value. Usage rises with higher values and falls with lower values. Verify current swappiness value by running command below. cat /proc/sys/vm/swappiness Use the sysctl utility to temporarily modify the swappiness. The value is lowered to 40 from 60 by the subsequent command. sudo sysctl vm.swappiness=40 To make the changes permanent, run these commands respectively. echo 'vm.swappiness=40' | sudo tee -a /etc/sysctl.conf sudo sysctl -p Modify Cache Pressure (Optional) Cache pressure regulates the kernel's propensity to recover caching memory, which can be lessened with lower values. If for example, a user wants to set VFS Cache Pressure to 40, this can be set using the commands below respectively. echo 'vm.vfs_cache_pressure=40' | sudo tee -a /etc/sysctl.conf sudo sysctl -p Verify that the swap file is operational and set up properly. Use the commands below to check it. sudo swapon --show free -h Increasing Swap Space with Swap File To resize the system's swap file, use the following actions. Temporarily disable the swap file. sudo swapoff /swapfile Change the size of the swap file to the preferred size. Replace 8G with your desired new size. Using the fallocate command sudo fallocate -l 8G /swapfile Using the dd command sudo dd if=/dev/zero of=/swapfile bs=1M count=8192 To adjust for the new size, reinitialise the swap file. sudo mkswap /swapfile Activate the swap file that has been resized. sudo swapon /swapfile Validate that the swap space has been updated from 4GB to 8GB. sudo swapon --show free -h Conclusion To sum up, creating a swap file in Ubuntu is a simple procedure that can greatly improve system speed, especially when working with memory-demanding apps or when physical RAM is at limited availability. Without the need for intricate partitioning, users can rapidly increase the virtual memory of their system by following the instructions to create, format, and activate a swap file. The swap space will also be active across reboots if the swap file is made permanent via the /etc/fstab file. The memory management can be further optimised by modifying variables like swappiness. All things considered, making a swap file is a practical and adaptable way to enhance Ubuntu system efficiency and stability. You can install Ubuntu on a VPS on Hostman.
23 December 2024 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support