How to Set Up a Firewall with UFW on Ubuntu

How to Set Up a Firewall with UFW on Ubuntu
Mohammad Waqas Shahid
Technical writer
Ubuntu Firewall
02.04.2024
Reading time: 10 min

In this comprehensive tutorial, users are guided through the process of setting up a robust firewall using the Uncomplicated Firewall (UFW) on Ubuntu. UFW provides an intuitive interface for managing netfilter firewall rules, offering an accessible solution for securing Ubuntu systems effectively.

Introduction to UFW

UFW, or Uncomplicated Firewall, is a user-friendly interface for managing iptables, the standard firewall management tool for Linux systems. It simplifies the process of creating and managing firewall rules, making it accessible even to users with limited networking knowledge.

Understanding Firewall Basics

Before diving into the configuration process, it's essential to understand some fundamental concepts related to firewalls and how they operate.

What is a Firewall?

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. It acts as a barrier between a trusted internal network and untrusted external networks, such as the internet.

On Hostman, you can buy a cloud firewall that provides cutting-edge defense tailored for businesses of all sizes.

Types of Firewalls

There are several types of firewalls, including packet-filtering firewalls, stateful inspection firewalls, proxy firewalls, and application layer firewalls. Each type operates differently but serves the common purpose of protecting networks and systems from unauthorized access and malicious activity.

Creating Account and Server on Hostman

To kick off the process, prospective server hosts are encouraged to visit the official Hostman website. Sign up for a new account by providing essential details and create a strong password. Following this, check your email for a verification link, click on it, and swiftly log in to your Hostman account.

Image1

Within the Hostman control panel, the user-friendly interface offers to start a new server. By navigating to the Create button, users can initiate the server creation process. Select the parameters you need, including software (for the purposes of this guide, we need a server with the Ubuntu operating system), configuration, geographical region, and backups, choose the project for this server, then click Order to create your server. 

The server will be installed in a couple of minutes and you will see the server's dashboard. Later on, to find your server you can go directly to Cloud servers or to the project the server is added to. 

234567

Click on your server, start it by the play button and scroll down to see the SSH command and root password for your Ubuntu server.

593f4dc2 53df 4468 8352 F2309e4ffb7f

Accessing Your Server

Access the server through the web-based terminal provided by Hostman or use preferred SSH client. For this tutorial accessing through SSH is used.

Image5

Updating System Packages

The following code is to be written in terminal to update system packages of Ubuntu:

sudo apt-get update
sudo apt-get upgrade

Image7

Type “y” and hit Enter.

After the upgrade, the following screen may appear. (If there is nothing to upgrade on your server, i/e. you already had the latest versions of the installed packages, you will not see this window and can proceed to the next step.)

Image6

In this popup, you are prompted to select which services should be restarted after the installation process. The services listed are part of the systemd system and are related to various system functionalities.

Here's a brief explanation of the options:

  • systemd-journald.service: The journal service, which handles system logs.

  • systemd-logind.service: The login service, which manages user logins.

  • systemd-manager: The service manager for the system.

  • systemd-networkd.service: The network service, responsible for network configuration.

  • systemd-resolved.service: The DNS resolver service.

  • systemd-timesyncd.service: The time synchronization service.

  • unattended-upgrades.service: A service for automatically applying package updates.

  • [email protected]: A user-specific service (user 0 refers to the root user).

Given the importance of network-related services for firewall functionality, it is recommended to restart the following services after the upgrade:

  • systemd-networkd.service: This service is responsible for network configuration. Restarting it ensures that any changes made during the upgrade, particularly those related to networking or firewall rules, take effect.
  • systemd-resolved.service: The DNS resolver service handles DNS resolution. Restarting it is advisable if there were changes to DNS configurations or updates to the DNS resolver service, which could impact firewall rules that rely on domain name resolution.

  • systemd-timesyncd.service: The time synchronization service ensures accurate timekeeping on the system. Proper time synchronization is crucial for security measures such as certificate validation and timestamping of firewall logs.

These services are crucial for maintaining system functionality and security, especially in the context of firewall configuration. 

Installing UFW on Ubuntu

Before starting the firewall configuration, it's essential to ensure that UFW is installed on your Ubuntu system. Here's how to do it:

Checking UFW Installation Status

Open the terminal and run the following command to check if UFW is installed:

sudo ufw status

You should see the status Active (running). If the status is inactive, start the service using the command:

sudo ufw enable

If UFW is not installed, the terminal will output the message Command ‘ufw’ not found. Follow the instruction below to install it.

Installing UFW

Install UFW by executing the following commands in the terminal:

sudo apt update
sudo apt install ufw

After completing the installation, recheck the status by typing:

sudo ufw status

Basic Firewall Configuration with UFW

Once UFW is installed, it's time to configure the basic firewall settings. Here's how to get started:

Enabling UFW

Activate UFW by running the following command in the terminal:

sudo ufw enable

You will receive a confirmation message indicating that the firewall is now operational.

Allowing SSH Access

If SSH access is not permitted by default, allow SSH connections using the command:

sudo ufw allow ssh

Permitting Specific Ports

To enable specific ports for various services such as web servers or database servers, use the command:

sudo ufw allow <port_number>

Replace <port_number> with the designated port number you wish to allow.

Advanced UFW Configuration

For advanced users looking to customize their firewall settings, UFW offers a range of configuration options:

Denying Incoming Connections

For enhanced security, deny all incoming connections by default and allow only designated ones:

sudo ufw default deny incoming

Allowing Outgoing Connections

Allow all outgoing connections by default:

sudo ufw default allow outgoing

Implementing Custom Rules

Define custom rules based on specific requirements:

sudo ufw <rule>

Below are examples of configuring custom rules in UFW for various scenarios, including allowing SSH, HTTP/HTTPS, specifying port ranges, and denying access based on IP addresses or subnets:

Allowing SSH Connections

To allow SSH connections, you can use the service name or specify the port number:

sudo ufw allow ssh

Or:

sudo ufw allow 22

Allowing HTTP and HTTPS Connections

To allow HTTP and HTTPS traffic, use the respective service names or port numbers:

sudo ufw allow http
sudo ufw allow https

Or:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Allowing Access to a Specific Port Range

To allow access to a range of ports, specify the port range:

sudo ufw allow 8000:9000/tcp

Allowing Access from Specific IP Addresses or Subnets

To allow access from specific IP addresses or subnets, specify the IP address or subnet:

sudo ufw allow from 192.168.1.100
sudo ufw allow from 192.168.0.0/16

Denying Access to a Specific Port

To deny access to a specific port, use the deny command:

sudo ufw deny 1234

Denying Access from Specific IP Addresses or Subnets

To deny access from specific IP addresses or subnets, use the deny command:

sudo ufw deny from 10.0.0.1
sudo ufw deny from 172.16.0.0/24

Denying All Incoming Connections (Except Allowed Ones)

To deny all incoming connections by default and allow only specific ones, use the default deny command:

sudo ufw default deny incoming

Allowing All Outgoing Connections

To allow all outgoing connections by default, use the default allow command:

sudo ufw default allow outgoing

These examples demonstrate how to configure custom rules in UFW for different scenarios, including allowing or denying access based on services, ports, IP addresses, and subnets. Customise these rules according to your specific requirements to enhance the security and control of your firewall configuration.

A Brief Guide for Requirements for Custom Rules

Following is a brief elaboration on which requirements may necessitate specific customizations in firewall rules to enhance security and control:

  1. Requirement: Secure Remote Access

Allowing SSH access (port 22) for remote administration while restricting access from specific IP addresses or subnets to prevent unauthorised access.

  1. Requirement: Hosting Web Services

Allowing HTTP (port 80) and HTTPS (port 443) traffic to host web services, while potentially restricting access to specific IP addresses or subnets to limit exposure to the public internet.

  1. Requirement: Application with Specific Port Range

Allowing access to a range of ports required by a specific application (e.g., ports 8000-9000) while denying access to all other ports to reduce attack surface.

  1. Requirement: Network Segmentation

Defining rules to allow communication between different segments of the network while denying access from external networks to sensitive segments to enforce network segmentation and control.

  1. Requirement: Denial of Service (DoS) Protection

Implementing rate-limiting rules to mitigate DoS attacks by limiting the number of incoming connections per second from specific IP addresses or subnets.

  1. Requirement: Compliance with Regulatory Standards

Implementing firewall rules to enforce compliance with regulatory standards (e.g., PCI DSS, HIPAA) by restricting access to sensitive data and ensuring secure communication channels.

  1. Requirement: Log Monitoring and Analysis

Enabling logging for specific firewall rules to monitor and analyze network traffic for security incidents, compliance audits, and troubleshooting purposes.

  1. Requirement: Application-Specific Rules

Defining application-specific rules based on the requirements of the deployed applications, such as allowing access to database ports only from application servers.

  1. Requirement: BYOD (Bring Your Own Device) Policies

Implementing rules to allow access for authorised devices while restricting access for unauthorised devices based on device attributes or user credentials.

  1. Requirement: High Availability and Failover

Configuring redundant firewall rules across multiple firewall instances to ensure high availability and failover in case of hardware or network failures.

These customizations align with best practices and address specific requirements to enhance security, control, and compliance in firewall configurations without technical errors or inaccuracies.

Testing Firewall Configuration

After configuring the firewall, it's essential to verify that the rules are applied correctly and test connectivity:

Verifying Firewall Rules

Ensure the correct application of firewall rules:

sudo ufw status verbose

Testing Connectivity

Conduct connectivity tests to verify that permitted connections function as intended. Users can do this by attempting to establish connections to services running on the system from both local and remote hosts.

Monitoring and Managing UFW

Once the firewall is configured, it's important to monitor and manage UFW to ensure optimal security.

Checking UFW Status

Monitor the status of UFW at any time:

sudo ufw status

Disabling UFW

Temporarily disable UFW when necessary:

sudo ufw disable

Logging Firewall Activity

Enable logging to monitor firewall activity and identify potential security threats:

sudo ufw logging on

Conclusion

Implementing a firewall using UFW on Ubuntu is crucial for enhancing system security and safeguarding against potential threats. By following the steps outlined in this tutorial, users can effectively configure and manage their firewall settings, ensuring the protection of their Ubuntu systems. With UFW's user-friendly interface and powerful capabilities, users can easily create and enforce firewall rules to control network traffic and prevent unauthorized access. By understanding the basics of firewalls and utilizing the advanced configuration options provided by UFW, users can create a robust defense against cyber threats.

Ubuntu Firewall
02.04.2024
Reading time: 10 min

Similar

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
PHP

How to Install PHP and PHP-FPM on Ubuntu 24.04

In this guide, we will describe installing PHP and PHP-FPM on Ubuntu 24.04. PHP, which stands for Hypertext Preprocessor, is a language that is widely used and open-sourced, mainly for web development. PHP is the only PHP FastCGI implementation, that is extremely useful for high-traffic websites. At the end of this guide, you should be ready to go with PHP running on your server. Prerequisites Before we start, please confirm you have the following: Ubuntu 24.04 LTS installed on the server A user account with the sudo access An essential command-line operation understanding A reliable internet connection for downloading software packages To ensure that your system is up to date, run the following commands: sudo apt updatesudo apt upgrade Install Apache Launch the Apache web server using the following command: sudo apt install apache2 Install PHP Let's begin with installing the PHP package in Ubuntu 24.04 server. First, open a terminal on your Ubuntu system. PHP and common modules are included in the installation action: sudo apt install php That command installs the core PHP package, the command-line interface, and common libraries. Make sure the installation works: php -v Install PHP Extensions PHP extensions are the way to go to extending PHP installation with certain functions. Start by installing extensions: sudo apt install php-curl php-mbstring php-xml Short description: php-mysql: Allows MySQL database connection php-gd: Adds ability to manipulate images php-curl: Makes possible to communicate with servers php-mbstring: Provides multibyte string support php-xml: Enables XML support php-zip: Enables ZIP support Additional extensions can be installed as you see fit for your projects. You can search them using: apt-cache search php- Install and Configure PHP-FPM PHP-FPM is essential when dealing with high-traffic websites. To install and configure it: Install the package: sudo apt install php-fpm Launch PHP-FPM service. Depending on the installation, version number may differ. sudo systemctl start php8.3-fpm Tell PHP-FPM to go on boot: sudo systemctl enable php8.3-fpm Verfy PHP-FPM is working: systemctl status php8.3-fpm This will output a response that says "Active (Running)" if everything is working as expected. Test PHP and PHP-FPM To ensure that PHP and PHP-FPM are both running with no problems, create a test file then serve it via the website's server. Let's say it uses Apache in this example: Generate PHP Info File. To show PHP settings using the phpinfo() function, do the following: mkdir -p /var/www/htmlecho "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php Set Up Apache for PHP-FPM. Ensure Apache is made compatible for PHP-FPM, by first finding Apache configuration file (usually /etc/apache2/sites-available/000-default.conf) then inserting: <FilesMatch \.php$>   SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost/"</FilesMatch> Remember we must alter specific PHP version and socket path to suit individual settings of the server. Activate PHP and PHP-FPM. Enable PHP and PHP-FPM following these instructions: sudo apt install libapache2-mod-phpsudo a2enmod proxy_fcgi setenvif Reboot Apache. Apply changes by restarting Apache server: sudo systemctl restart apache2 Access PHP Info Page. First open your web browser and go to: http://your_server_ip/info.php Replace [server_ip] with the server IP address or domain. You can see details of your PHP installation. Install Multiple PHP Versions For particular projects you might need to run different applications, each one may require different functionalities. This is the way to manage and manipulate multiple PHP versions on Ubuntu 24.04. First, add PHP repository: sudo apt install software-properties-commonsudo add-apt-repository ppa:ondrej/php && sudo apt update Install PHP versions you need: sudo apt install php8.1 php8.1-fpm Deselect one PHP version and elect the other: sudo update-alternatives --set php /usr/bin/php8.1 If you are using multiple PHP versions, ensure that your web server is pointing to the appropriate PHP-FPM socket. Securing PHP and PHP-FPM: Best Practices As a web developer, you know the importance of incorporating both PHP and PHP-FPM into web applications that are safe and robust. In this section, we will introduce a number of security steps that you should adapt using PHP and PHP-FPM. 1. Keep PHP and PHP-FPM Updated PHP and PHP-FPM should be up to date. Doing regular updates will eliminate known security breaches and provide overall security improvements. You need to check for updates as often as possible then update the system as soon as the updates are available. 2. Configure PHP Securely To configure PHP securely, start by disabling unnecessary and potentially dangerous functions, such as exec, shell_exec, and eval, in the PHP configuration file (php.ini). Use open_basedir directive to restrict PHP’s access to specific directories, preventing unauthorized access to sensitive files. Set display_errors to Off in production to avoid exposing error messages that could provide insights to attackers. Limit file upload sizes and execution times to reduce the risk of resource exhaustion attacks. Besides, ensure that PHP runs under a dedicated, restricted user account with minimal permissions to prevent privilege escalation. Regularly update PHP to the latest stable version to patch vulnerabilities and improve security. 3. Use Safe Error Reporting To ensure an error-free application, it is quite handy locating and correcting code bugs in a development environment. In production environment, you have the possibility to hide the PHP errors by setting the display_error directive to be off, and you should also set the log_errors directive to be On, thus this will help you prevent PHP from showing errors to the users whereas your server will log it in a safe location without problems to users. 4. Implement Input Validation Being aware of the input validations is quite crucial during the programming of your software. Make sure that all deficiencies are tested and only SQL statements containing their SQL equivalent that can produce outwardly neutral queries via prepared statements is considered safe. 5. Secure PHP-FPM Configuration PHP-FPM is required to run using a non-usual user account with minium rights. Furthermore, access to the PHP-FPM socket or port should be very limited to the web application. 6. Enable Open_basedir You need to bind open_basedir directive in order to restrict access files within the given directory. In this case, if you attempt to visit a forbidden directory and the request is accidentally transmitted to the server, PHP will prevent you from doing so. 7. Use HTTPS We need to secure web calls by making apps HTTPS-only, which is the only prominent way to block all the known hacking tricks. Conclusion With this guide, you've successfully set up PHP and PHP-FPM on Ubuntu 24.04. Your server is now configured for dynamic web applications. To maintain security and performance, remember to keep the system and packages regularly updated.
09 December 2024 · 6 min to read
Ubuntu

How to Configure an Additional IP as an Alias in Ubuntu

In the network administration world, the task of setting up additional IP addresses on a single network interface is commonly performed. The technique of IP aliasing, which is a system for a device to reply to several IP addresses on one network interface, penetrates this model. All Ubuntu users should be familiar with modifying and applying these settings to ensure robust networking administration. This guide will detail the methods of creating an extra IP address in Ubuntu as an alias for both the versions of Ubuntu 24.04 and 22.04. Prerequisites Obviously, one first needs to set up the system in a way that would allow for the manipulation of all IP addresses over the same network, using Ubuntu. Here is the list: A system running either Ubuntu 24.04 or Ubuntu 22.04 Admin access to the system (sudo privileges) Basic knowledge of command-line interface operations An additional IP address assigned by a network administrator or ISP Network interface name information (e.g., eth0, ens3) When troubleshooting problems, we are in danger of causing even more difficulty, as network interfaces provided by networks are not reliable. With this in mind, it would be wise to keep a backup of the configuration files before proceeding with the changes. Configuring an Additional IP Address within Ubuntu 24.04 Ubuntu 24.04, the latest long-term support release, uses Netplan for network configuration. This configuration is also applicable for Ubuntu 22.04 and beyond. Netplan is a utility for configuring networking on Linux systems. Here's how to create an additional IP address: Check the Network Interface Primarily, it is necessary to define the network interface that will carry the new address. You can achieve this by running the following command: ip addr show The output of this command will display all the interfaces. Find the name of the interface (e.g. ens3, eth0) currently in use. Edit the Netplan Configuration File Normally Netplan configuration files are found in the /etc/netplan/ directory. The file name may be different but most of them end with a .yaml extension. To change the file, use a text editor with root privileges: sudo nano /etc/netplan/50-cloud-init.yaml Insert the New IP Address In the YAML file, add the new IP address under the addresses section of the appropriate network interface. The configuration may appear like this: network: version: 2 renderer: networkd ethernets: eth0: addresses: - "195.133.93.70/24" - "166.1.227.189/24" #New IP address - "192.168.1.2/24" #Private IP address nameservers: addresses: - "1.1.1.1" - "1.0.0.1" dhcp4: false dhcp6: false routes: - to: "0.0.0.0/0" via: "195.133.93.1" Apply the Changes Upon saving your edits, you need to apply the new version of the configuration by running this command: sudo netplan apply Validate the Configuration After completing the steps above, you will need to repeat the ip addr show command to confirm that the new IP address is in place. Now the output of this command should also include the new IP address. Additional Considerations Persistent Configuration The choices made by Netplan are stable and will last through the restart of the device. But, it's a good idea to verify the configuration with a system reboot to make sure everything goes well after the restart. Firewall Configuration When adding a new IP address, you may need to update the firewall rules. Ubuntu traditionally uses UFW (Uncomplicated Firewall). To avoid blocking the new IP, you will have to create new rules to UFW. Network Services If the system has some services running which are linked to specific IP addresses, then you must update their configurations to recognize and utilize the new IP address as well. IPv6 Considerations The above examples talk about IPv4. If you have to use IPv6 addresses, then the procedure is relatively the same; you will have to use a different style of address though. Netplan supports both IPv4 and IPv6 configurations. Troubleshooting In case of issues emerging during the configuration stage, try: Check for syntax errors in the YAML file with the command: sudo netplan --debug generate. Ensure that there are no conflicts with other devices using the same IP address on the network. Verify correct setting of the subnet mask and the gateway. Check the system logfile for error messages: journalctl -xe. Advanced IP Aliasing Techniques Network administrators can see how advanced IP aliasing plays a key role in improving network management: virtual interfaces make it possible to have several logical interfaces on a physical network interface, wherein all have their IP and network settings. Dynamic IP Aliasing There are cases where network administrators would have to implement dynamic IP aliasing. With the help of scripts, it is possible to add or remove IP aliases according to certain conditions or occurrences. For example, a script can be made to insert an IP alias whenever a particular service starts and remove it every time the service stops. IP Aliasing in Containerized Environments The popularity of containerization in the present age necessitates having IP aliasing in order to control network configuration of Docker containers and any other containerized applications. In such cases, IP aliases are quite often employed to expose multiple services on a container at different IP addresses or assist containers to communicate with one another. Docker Network Aliases In Docker, network aliases can be used to allow multiple containers to respond to the same DNS name on a custom network. Among other things, this is indispensable in microservices architectures where service discovery is a very important issue. Security Implications of IP Aliasing Though IP aliasing has a multitude of advantages, the issue of security deserves also to be looked into. Among other things, the more IP addresses you put, the larger the possible security breach of a system. The network administrators must guarantee the applications are protected with: Configurations of a firewall that will secure all the IP aliases Intrusion Detection Systems (IDS) to record the traffic of all IP addresses Periodically checking the use and need of each IP alias Enabling of appropriate security tools for those services bound to specific IP aliases Conclusion Putting a new IP address as an alias into Ubuntu is a highly efficient process as their utility of Netplan helps greatly. Whether you are using Ubuntu 24.04 or 22.04, the steps remain the same including editing the Netplan configuration file, adding the new IP address, and applying the changes. A system with multiple IP addresses on a single network interface of a single computer can be used to do different tasks on such a network. The ability to respond to several IP addresses on one network interface becomes very useful in several networking situations. Through these steps, you can increase the Ubuntu computer networking capabilities quickly and effectively. The sequence is always to first back up existing configurations then to make changes followed by in-depth test post-installation. With these skills, a network infrastructure manager or an IT technician can effectively manage and optimize his Ubuntu-powered network infrastructure to cater to diverse networking requirements.
29 November 2024 · 6 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