How to Install and Configure SSH on Ubuntu 22.04

How to Install and Configure SSH on Ubuntu 22.04
Hostman Team
Technical writer
Ubuntu
24.11.2023
Reading time: 7 min

SSH is a network protocol that provides a secure connection between a client and a server. All communication is encrypted, preventing theft of data transmitted over the network and other remote network attacks.

Let’s say you have ordered a cloud server from Hostman. You will need SSH installed and configured to connect to and administer the server.

The guide below will describe how to install SSH on Ubuntu 22.04 and configure it.

Prerequisites

Before proceeding with the installation and configuration of the Secure Shell service, ensure the following requirements are met:

  • Linux Command Line Skills for Configuration

Having a solid grasp of basic Linux commands like sudo, apt, nano, and systemctl is essential when setting up the service. These commands will be frequently used during the installation and configuration process. It's crucial to be comfortable working within the command line environment to manage the service effectively.

  • Root or Sudo Access for Setup

To install and configure the server, administrative (root) privileges are required. Users must either have sudo access or be logged in as root. Without these privileges, the setup process cannot proceed.

  • Internet Connection for Package Download

A stable internet connection is necessary to install the OpenSSH server and any additional related packages. Without a functional connection, the system cannot retrieve the required software components.

  • Configuring Firewall for Access

If a firewall, like ufw, is enabled on the system, it may block remote access by default. It is essential to configure your firewall to allow incoming connections. Use ufw or another firewall tool to ensure port 22 is open and accessible.

  • Access to the System (Local or Remote)

You need physical access to your machine to configure the service locally, or it must be remotely accessible via its IP address. Ensure the system is properly connected to the network to establish a connection.

Step 1: Prepare Ubuntu

The first thing you need to do before you start installing SSH on Ubuntu is to update all apt packages to the latest versions. To do this, use the following command:

sudo apt update && sudo apt upgrade

Step 2: Install SSH on Ubuntu

OpenSSH is not pre-installed on the system, so let's install it manually. To do this, type in the terminal:

sudo apt install openssh-server

The installation of all the necessary components will begin. Answer "Yes" to all the system prompts. 

After the installation is complete, go to the next step to start the service.

Step 3: Start SSH

Now you need to enable the service you just installed using the command below:

sudo systemctl enable --now ssh

On successful startup, you will see the following system message.

The --now key helps you launch the service and simultaneously set it to start when the system boots.

To verify that the service is enabled and running successfully, type:

sudo systemctl status ssh

The output should contain the Active: active (running) line, which indicates that the service is successfully running.

If you want to disable the service, execute: 

sudo systemctl disable ssh

It disables the service and prevents it from starting at boot.

Step 4: Configure the firewall

Before connecting to the server via SSH, check the firewall to ensure it is configured correctly.

In our case, we have the UFW installed, so we will use the following command:

sudo ufw status

In the output, you should see that SSH traffic is allowed. If you don't have it listed, you need to allow incoming SSH connections. This command will help with this:

sudo ufw allow ssh

Step 5: Connect to the server

Once you complete all the previous steps, you can log into the server using the SSH protocol.

To do this, you will need the server's IP address or domain name and the name of a user created on the server.

In the terminal line, enter the command:

ssh username@IP_address

Or: 

ssh username@domain

Important: To successfully connect to a remote server, SSH must be installed and configured on the remote server and the user's computer from which you make the connection. 

-

Step 6 (optional): Create Key Pair for Secure Authentication

For enhanced security, consider configuring a key pair instead of relying on password authentication. To generate one, use the following command:

ssh-keygen

Step 7: Configure SSH

Having completed the previous five steps, you can already connect to the server remotely. However, you can further increase the connection's security by changing the default connection port to another or changing the password authentication to key authentication. These and other changes require editing the SSH configuration file.

The main OpenSSH server settings are stored in the main configuration file sshd_config (location: /etc/ssh). Before you start editing, you should create a backup of this file: 

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.initial

If you get any errors after editing the configuration file, you can restore the original file without problems.

After creating the backup, you can proceed to edit the configuration file. To do this, open it using the nano editor:

sudo nano /etc/ssh/sshd_config

In the file, change the port to a more secure one. It is best to set values from the dynamic range of ports (49152 - 65535) and use different numbers for additional security. For example, let's change the port value to 49532. To do this, we uncomment the corresponding line in the file and change the port as shown in the screenshot below.

4fd580df 7710 49f3 Ba88 5f79663f289e

In addition to this setting, we recommend changing the password authentication mode to a more secure key authentication mode. To do this, uncomment the corresponding line and make sure the value is "Yes", as shown in the screenshot.

B78f6db1 010f 48a7 A5ff Ce4e6f665691

Now, let's prohibit logging on to the server as a superuser by changing the corresponding line as shown in the picture below.

B06df4a0 5d22 4c7a Ba90 47fabd8d0bf5

There are other settings you can configure to increase the server security: 

  • UseDNS checks if the hostname matches its IP address. The value "Yes" enables this parameter.

  • PermitEmptyPasswords prohibits using empty passwords for authentication if the value is "No."

  • MaxAuthTries limits the number of unsuccessful attempts to connect to the server within one communication session. 

  • AllowUsers and AllowGroups are responsible for the list of users and groups allowed to access the server:

# AllowUsers User1, User2, User3
# AllowGroups Group1, Group2, Group3
  • Login GraceTime sets the time provided for successful authorization. We recommend reducing the value of this parameter by four times.

  • ClientAliveInterval limits the time of user inactivity. After exceeding the specified limit, the user is disconnected.

After making all the changes in the main configuration file, save them and close the editor. 

Restart the service to make the changes take effect:

sudo systemctl restart ssh

If you have changed the port in the configuration file, you should connect using the new port: 

ssh -p port_number username@IP_address

Or:

ssh -p port_number_port_username@domain
Cloud servers for your needs from $4/mo

Troubleshooting Connection Issues

  • Ensure the service is running with:
sudo systemctl status ssh
  • Restart it if necessary:
sudo systemctl restart ssh
  • Check firewall settings to allow traffic on port 22:
sudo ufw allow 22
  • Confirm the system is reachable by running:
ping <server-ip-address>

Disabling the Service

If you need to disable remote access for any reason, follow these steps:

  1. Stop the Service

To temporarily stop accepting connections:

sudo systemctl stop ssh
  1. Prevent Automatic Startup

To disable it from starting on reboot:

sudo systemctl disable ssh
  1. Confirm Inactive Status

Verify that the service is no longer running:

sudo systemctl status ssh
  1. Uninstall the Server

If the service is no longer needed, remove it and its associated configuration files:

sudo apt remove openssh-server

Conclusion

This article presents a step-by-step guide on installing and configuring SSH in Ubuntu 22.04 and describes how to edit the main configuration file to improve security. We hope this guide helps you to set up a secure remote connection to your Ubuntu server.

Ubuntu
24.11.2023
Reading time: 7 min

Similar

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
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

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