Sign In
Sign In

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 Install Flatpak on Ubuntu 22.04

Flatpak is a modern solution for handling applications on Linux. Unlike standard software managers, it installs programs in a sandboxed environment, ensuring greater security and reliability. Each program operates independently, reducing the risk of system corruption and conflicts. This separation assures that issues in one program don't affect others. Additionally, it offers consistent environments across Linux distributions, allowing developers to distribute apps without system dependency worries. This compatibility provides a reliable experience, making it versatile for any user. Overview Flatpak revolutionizes Linux application management by providing a unified and secure method to install and run applications. It encapsulates apps in a sandbox, isolating them from the core system to prevent conflicts and ensure stability. It offers several benefits: Security: Sandboxing isolates applications, reducing the risk of security vulnerabilities. Compatibility: Works across various Linux distributions, providing a consistent environment. Independence: Applications operate independently, preventing system corruption. Developer-Friendly: Simplifies app distribution without worrying about system dependencies. Installation Guide for Ubuntu 22.04 This guide covers Flatpak framework installation on Ubuntu 22.04, preparing your distribution to manage apps easily. Follow these instructions to master installation and manage apps efficiently. Prerequisites Before starting, you must have: Ubuntu 22.04 Terminal access with sudo privileges. Method 1: Via apt Installing this framework via terminal and configuring its repository is straightforward and efficient. This method uses the apt package manager, common in Ubuntu and Debian. By following these instructions, the framework can be set up and ready to use in no time. Update the packages list with: sudo apt update && sudo apt upgrade -y Install Flatpak with this command: sudo apt install flatpak -y To unlock a wide selection of utilities, include the Flathub repo using: sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo Reboot your machine to apply changes: sudo reboot After rebooting, check the installed utility by applying: flatpak --version If installed, the release number will display. To install an app, employ the following command with the app name. For example, to get Wireshark, apply: sudo flatpak install flathub org.wireshark.Wireshark -y To launch the app, enter the command below with the app ID. For example, to launch Wireshark, enter: flatpak run org.wireshark.Wireshark Method 2: Via Team APT PPA This approach includes adding the Flatpak Team APT PPA repo for installation. Making use of a PPA (Personal Package Archive) allows access to the latest release provided by the developers. It's useful for up-to-date features or patches not available in the standard repository list. Here are the steps: First, include the Team PPA via: sudo add-apt-repository ppa:flatpak/stable Refresh your source list again to incorporate the new PPA repo: sudo apt update Perform the framework installation using: sudo apt install flatpak -y Post-installation, include the FlatHub repository via: sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo Additional Configuration To enhance your experience, configure additional settings or install other useful applications. For that, follow the below instructions. Installing Plugins  Plugins improve the functionality and integration of Flatpak apps with your desktop. Install them with: sudo apt install gnome-software-plugin-flatpak -y NOTE: This allows you to browse and set up Flatpak utilities directly from the GNOME Software program. From Ubuntu versions 20.04 to 23.04, GNOME Software is included as a Snap package, which doesn't support Flatpak. In version 23.10, it changes to the App Center, which also doesn't support the framework. To fix this, you'll need to install a plugin that adds another version of GNOME Software. As a result, you'll have two "Software" apps in versions 20.04 to 23.04 and one "Software" app in version 23.10. To solve the issue of integrating framework with Ubuntu's desktop, while avoiding the confusion of multiple "Software" applications, here's what to do: Remove the Snap version of GNOME to avoid having two "Software" apps: sudo apt remove gnome-software -y Get the plugin along with the deb version of GNOME: sudo apt install gnome-software-plugin-flatpak -y Run the GNOME by applying: gnome-software Manage Permissions Flatpak apps run in a sandboxed environment with limited system access. These permissions are managed by utilizing Flatseal, which can be installed via: sudo flatpak install flathub com.github.tchx84.Flatseal Launch Flatseal from the applications menu to adjust permissions for Flatpak apps. Troubleshooting Common Errors In case of any error during the process, here are some common problems and their solutions. Issue 1: Command Not Found If you receive a 'command not found' error, verify the framework is correctly configured. Reinstall it if necessary. Issue 2: Repository Not Enabled Incase of failure, get an app from Flathub, verify the repository with: sudo flatpak remotes If FlatHub is not listed, add it through the repository enable command provided earlier. Issue 3: Application Fails to Launch If an app won't launch, try executing it from the terminal to check for error messages. Hit the aforementioned run command followed by the app ID. If the issue persists, employ this command to repair it: sudo flatpak repair Updating Flatpak  You must keep the app up-to-date to have the latest features and security updates. To update all Flatpak’s added utilities, utilize: sudo flatpak update Uninstalling Flatpak  To remove the framework from Ubuntu, do it via the following instructions. Before removing the main utility, uninstall any app by executing: sudo flatpak uninstall <application-id> -y Then remove the framework itself by applying: sudo apt remove flatpak -y Finally, remove the FlatHub repo via: sudo flatpak remote-delete flathub Integrating Flatpak with Desktop Integrating Flatpak apps with your desktop guarantees a smooth user experience. This section covers the integration process with your Ubuntu desktop. Make sure Flatpak utilities are integrated with your desktop by installing necessary plugins: sudo apt install gnome-software-plugin-flatpak Check if the apps appear in your application menu. If not, log out and back in to refresh the menu. Frequently Asked Questions (FAQ) 1. Can Flatpak be used alongside other package managers? Yes, it can be utilized alongside traditional package managers like apt, yum, or dnf. The utility operates independently, allowing you to manage programs without interfering with system tools. 2. How do I list all Flatpak installed Tools? To list all Flatpak’s installed tools, execute: flatpak list 3. What is the benefit of using Flatpak over traditional package managers? It provides a consistent workspace across different Linux distributions, ensuring programs work as intended regardless of the underlying system. It also enhances security by running programs in a sandboxed environment. Conclusion You've successfully set up Flatpak on your Ubuntu distribution through multiple methods. Whether you utilized the terminal or the graphical user interface, you now have a powerful utility for managing tools in a secure interface. By integrating the application with your desktop environment and keeping it updated, you can further enhance your user experience and ensure optimal performance. With access to a vast library of utilities on Flathub, you can easily find, install, and run your favorite apps with confidence. This flexibility not only enhances your productivity but also allows you to explore a wide range of software that suits your needs.
21 February 2025 · 7 min to read
Ubuntu

How to Install .DEB Files on Ubuntu

Ubuntu is a standout Linux distribution, appreciated by a vast number of people around the world. Among the various software package formats it supports, .DEB formats are particularly common in Debian-based systems like Ubuntu. Installing such packages on Ubuntu is a simple task that brings a wealth of applications within reach. Mastering the installation of these packages is crucial for effective application management on Ubuntu. This blog details multiple strategies: apt, dpkg, GDebi, alien, and GUI. Follow these approaches for the installation and management of .DEB files on Ubuntu. Overview of .DEB Packages Let's define what .DEB packages are before we move on to the installation procedures. Within a .DEB package, you'll find everything required to install software, including compiled code, metadata, and scripts. These packages streamline software distribution and installation on Debian-based systems such as Ubuntu. Adopting .DEB packages comes with several benefits: Ease of Installation: It simplifies installation by including all essential files and dependencies. Consistency: It guarantees consistent software installation across various systems. Security: The verified packages from trusted sources often include security updates, keeping your system secure. Prerequisites Confirm you have: An Ubuntu-running machine Elevated (sudo) permissions for terminal access A Debian File Method 1: Via apt  apt is a reliable and versatile terminal utility for handling package management on Ubuntu. The tool's independent dependency management makes it an excellent way for installing Debian files. Here's the way to utilize it: Access Terminal: Use Ctrl + Alt + T to launch the terminal. Access the Directory: Run the cd command to head to the directory holding your Debian package. For instance: cd ~/Downloads Install the package: Leverage the apt utility for installing the package, ensuring filename.deb is correctly named: sudo apt install ./filename.deb Method 2: Via dpkg dpkg is a crucial utility for installing packages on Ubuntu. While it provides more control during installation, you'll need to manage dependencies manually. Experienced users seeking more control over the process will find this method advantageous. Here's how: Begin by opening the terminal. Access the folder containing the .DEB package you want to install: cd ~/Downloads Apply the dpkg tool for installation, changing filename.deb to your exact file name: sudo dpkg -i filename.deb Fix dependencies. If dependencies are missing, rectify this with: sudo apt install -f Method 3: Via GDebi Installer GDebi offers a simple interface specifically aimed at handling .DEB installations while efficiently managing dependencies. Providing both terminal and graphical interfaces, it guarantees that the installation process is clear and accessible. Here's how to utilize it: Install GDebi: Initially, make sure GDebi is installed if it hasn’t been set up on your system yet: sudo apt install gdebi Open .DEB File: Reach the directory holding the .DEB file and open it with GDebi: cd ~/Downloadssudo gdebi filename.deb Another option is to leverage the GDebi GUI: Right-click the .DEB package, then choose Open With Other Application. Go with GDebi Package Installer. Give GDebi a moment to analyze the file and show the installation details. Click Install Package. Method 4: Via alien Though typically employed for format conversion, the alien tool can directly install the .DEB file. If alien is not already installed, install it by applying: sudo apt install alien Use the cd command to reach the directory holding the .DEB file: cd ~/Downloads Utilize alien for installing .DEB: sudo alien -i filename.deb Let alien handle the rest, converting the .DEB file if required. Way 5: Via GUI If you avoid the terminal, the Software Center offers a GUI alternative. Access the system’s file manager and move to the folder containing your Debian file. Using the file manager makes it simple to browse through your file system and locate the file you need. Right-click the package, pick Open with Other Application, then go for Open with Software Install. Once opened, the Software Center will display an easy-to-use interface to install the chosen package. Hit the Install button to start the installation. Let the center manage the rest, including handling and installing any necessary dependencies. Troubleshooting If you encounter problems, here are some common fixes: Dependency Errors Solution: Fix any such issues by running: sudo apt install -f Package Not Found Solution: Verify that you're in the correct directory and the file name is accurate. Ensuring you have the correct file name and directory path is crucial for a successful installation. Permission Denied Solution: Make sure you are utilizing sudo for commands that require elevated privileges. Executing commands with sudo grants the required permissions to carry out administrative tasks. Corrupted Debian Package Solution: Validate the file's integrity by checking its checksum: sha256sum filename.deb Insufficient Disk Space Solution: Check available disk space and free up space if necessary. df -h Unclear Error Messages Solution: Inspect relevant logs for detailed error information: tail -f /var/log/dpkg.log Best Practices for .DEB Packages Management Below are several essential practices to ensure the secure and seamless handling of .DEB: Regular Updates: Keep your system and utilities up to date to avoid compatibility problems. Utilize Trusted Sources: Only download .DEB packages from reputable sources to avoid malware and maintain software integrity. Backup Important Data: Before setting up a new app, especially from Debian types, backup your important data to prevent data loss in case of issues. Remove Unused Packages: Periodically clean up unused packages to maintain system performance. FAQ How to resolve installation issues related to missing dependencies? In case of missing dependencies, apply: sudo apt install -f How to uninstall a .DEB package on Ubuntu? Employ the below command to uninstall the .DEB package: sudo apt remove <package-name> -y Update <package-name> with the appropriate package name you want to remove. Conclusion With these techniques, installing .DEB packages on Ubuntu becomes effortless. No matter if you utilize apt, dpkg, GDebi, alien, or GUI, you can go with the method that aligns with your preferences. Each has its own advantages, so consider your comfort level and the specific requirements of the Debian file you are installing. Stick to these instructions, and installing packages on Ubuntu will be smooth and seamless. The key is to choose the one that suits you best and to troubleshoot any concern through the provided fixes. 
21 February 2025 · 6 min to read
Ubuntu

How to Install and Use Composer on Ubuntu

Composer is a cross-platform tool for managing dependencies in projects written in PHP. With Composer, you can manage numerous libraries and frameworks, known as "packages." Installing the required packages allows you to extend the standard PHP functionality, speeding up and simplifying development. All installed packages become project dependencies. Thus, Composer can be considered a full-fledged dependency manager, similar to those used in many programming languages. Additionally, Composer has a comprehensive package repository called Packagist, where you can search for, download, and install the required packages. This guide provides detailed instructions on installing Composer on an Ubuntu server and using it for PHP projects. Prerequisites In this tutorial, we use: A VPS server running Ubuntu 22.04 PHP interpreter version 8.1.2 Composer dependency manager version 2.8.2 Installing Composer First, update the list of existing APT repositories: sudo apt update Next, install the packages required to download and use Composer: sudo apt install curl php-cli unzip -y These packages include: curl: A tool for making HTTP requests. php-cli: An interpreter to run PHP scripts. unzip: A utility to extract ZIP archives. The -y flag answers "yes" to all installation prompts. Composer installation is automated using a PHP script provided by its developers. Download the installation script from the official Composer website using an HTTP request: curl -sS https://getcomposer.org/installer -o composerInstall.php The -sS flag runs curl in silent mode, suppressing all output except for errors. The -o flag specifies the filename and the directory where the file will be placed. To ensure the file has been downloaded, check the contents of the current directory: ls You should see the following output in the terminal, including the installation script: composerInstall.php  resize.log  snap This guide covers the global installation of Composer, meaning it can be run from any directory without specifying the absolute path. To perform a global installation, execute the downloaded PHP script with additional parameters: php composerInstall.php --install-dir=/usr/local/bin --filename=composer The --install-dir flag specifies the directory where Composer will be installed. The --filename flag defines the name of the binary file accessible from the terminal. In this case, Composer is installed in the system's binary directory: /usr/local/bin. After running the script, you'll see the following output in the terminal: All settings correct for using Composer Downloading... Composer (version 2.8.2) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer Since the installation script is no longer needed, you can delete it: rm composerInstall.php To launch Composer for the first time, run: composer You may see the following message in the terminal: Do not run Composer as root/super user! See https://getcomposer.org/root for details Continue as root/super user [yes]? Composer warns against running it as the root user due to potential risks but allows you to proceed. For this guide, we will continue using Composer as-is by confirming with yes. Afterward, you will see a welcome message along with a list of available options and commands with brief descriptions. Composer is now fully installed. Configuring Composer The main file used to manage dependencies is composer.json, which describes the packages required for the proper functioning of a project. Composer follows the Infrastructure as Code (IaC) approach, describing the local project infrastructure through a configuration file rather than manual settings adjustments in a graphical interface. However, Composer allows configuration management not only by manually editing the file in a text editor but also through console commands, providing a more interactive way to handle configurations. Basic Commands Using Composer involves several fundamental commands that interact with the composer.json configuration file: init: Initializes a project. require: Adds a package. install: Installs dependencies. update: Updates packages. Although Composer offers many more commands, these are the most frequently used. Creating a Directory Create a separate directory for the PHP project: mkdir phptest Then navigate to the directory: cd phptest This directory will store both the project’s source code and the required dependency files. Searching for a Library Suppose we are working on a small project that performs various string transformations. As a dependency, we need a specific library that provides functions for manipulating string content. In this guide, we will implement a common programming function called slugify, which converts a sequence of words into a single long word containing only lowercase ASCII characters and hyphens. The slugify function is often used to transform arbitrary headings into URL-friendly formats without spaces. Rather than writing this function ourselves, we will use Composer to find a suitable library in the official package registry, add it as a dependency, and let Composer handle its download, installation, and integration into the project. To find the necessary library, follow these steps: Open the Composer's official package registry in a browser. Enter "slugify" in the search bar. Look for the most suitable package based on its parameters and description. The search results display key metrics for each available package: The number of installations via Composer (top right) The number of GitHub stars (bottom right) In general, popular packages tend to be more stable since they are used by a larger number of developers. Selecting a Package In this guide, we will use the package cocur/slugify. The package name, similar to a GitHub repository, contains the author (provider) and the library name separated by a forward slash (/). We can navigate to the package's page by clicking its name to see more details about the library’s implementation, such as dependency lists, descriptions with code examples, test coverage badges, license type, and more. Additionally, pay attention to the available package versions, as you need to specify the version during dependency installation. By following this process, you can search for and select suitable packages for a PHP project, which can later be used as dependencies to provide specific functions. Installing a Dependency To install the required package, use the require command. This either records the dependency in the composer.json configuration file or creates it if it does not exist: composer require cocur/slugify:4.6 In this guide, we are using cocur/slugify version 4.6.0. After running the command, you might encounter an error indicating missing system libraries: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages. Problem 1 - Root composer.json requires cocur/slugify 4.1 -> satisfiable by cocur/slugify[v4.1.0]. - cocur/slugify v4.1.0 requires ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension. This console output informs us that the ext-mbstring system library is missing, which is necessary for cocur/slugify to work correctly. You can manually search for the library using the APT package manager: sudo apt search mbstring The search results will show: Sorting... Done Full Text Search... Done php-mbstring/jammy 2:8.1+92ubuntu1 all MBSTRING module for PHP [default] php-patchwork-utf8/jammy 1.3.1-1 all UTF-8 strings handling for PHP php-symfony-polyfill-mbstring/jammy 1.24.0-1ubuntu2 all Symfony polyfill for the Mbstring extension php-symfony-polyfill-util/jammy 1.24.0-1ubuntu2 all Symfony utilities for portability of PHP codes php8.1-mbstring/jammy-updates,jammy-security 8.1.2-1ubuntu2.19 amd64 MBSTRING module for PHP The first result is the library we need. Install it with: sudo apt install php-mbstring -y Once the missing library is installed, rerun the command to install the package: composer require cocur/slugify:4.6 This time, the console output should confirm a successful installation: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking cocur/slugify (v4.6.0) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading cocur/slugify (v4.6.0) - Installing cocur/slugify (v4.6.0): Extracting archive Generating autoload files No security vulnerability advisories found. Check the directory contents with: ls You will see new files generated by Composer: composer.json  composer.lock  vendor Each file and directory serves a specific purpose: composer.json — Contains information about the required dependencies composer.lock — Records details about installed dependencies vendor — Stores the project’s installed dependencies If you use a version control system like Git, exclude the vendor directory from the repository. Take a look inside composer.json: cat composer.json It should look like this: { "require": { "cocur/slugify": "4.6" } } You’ll notice the require block specifying the package cocur/slugify version 4.6. You can find more detailed information about possible version values in the official Composer documentation. Using Composer Including Dependencies Once you have installed a dependency, you can include it in the project code using the automatically generated autoload.php script, located in the vendor directory. When this script is included in the PHP application, the functions and classes of the installed dependencies become available for use. Let's create the main file of our application: sudo nano main.php Then, fill it with the following content: <?php require __DIR__ . '/vendor/autoload.php'; use Cocur\Slugify\Slugify; $slugify = new Slugify(); // PHP_EOL is needed for line breaks in the console echo '[english]: ' . $slugify->slugify('How to deal with composer') . PHP_EOL; ?> Now, you can run the script: php main.php The output in the console terminal should look like this: [english]: how-to-use-composer Updating Dependencies Composer allows you to check for new versions of libraries based on version ranges defined in the composer.json configuration file: composer update Alternatively, you can update a specific package by specifying its name: composer update cocur/slugify Installing Dependencies If your PHP project contains a composer.json file, but the specified dependencies are not yet installed, you need to install them. Let’s first remove all existing packages and related information: rm -R vendor composer.lock The -R flag is necessary for recursive deletion of files and directories. After that, try running the script: php main.php You will see the expected error message in the console because the dependencies are missing: PHP Warning: require(/root/phptest/vendor/autoload.php): Failed to open stream: No such file or directory in /root/phptest/main.php on line 2 PHP Fatal error: Uncaught Error: Failed opening required '/root/phptest/vendor/autoload.php' (include_path='.:/usr/share/php') in /root/phptest/main.php:2 Stack trace: #0 {main} thrown in /root/phptest/main.php on line 2 Now, let's reinstall the dependencies based on the data from the configuration file: composer install After that, run the script again: php main.php The console should display the expected result without any errors: [english]: how-to-install-and-use-composer Conclusion You can install Composer on Ubuntu 22.04 automatically using an installation script from the official Composer website. Although Composer has many commands to manage the composer.json configuration file, in practice, only a few basic ones are commonly used: composer init composer require composer install composer update You can find comprehensive information on how to use Composer in the official documentation.
14 February 2025 · 10 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