How to Install and set up PHP and Nginx (LEMP) on Ubuntu 22.04

In this guide we are going to install and set up PHP and Nginx in Ubuntu 22.04. We will also set up a virtual host to serve a simple php info page.

PHP is a general-purpose scripting language geared towards web development. It is one of the popular programming languages for the web. Popular tools such as WordPress are coded using php. Big companies like Facebook also uses php heavily.

Nginx is a web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache. It started out as a web server designed for maximum performance and stability. Nginx has grown in popularity since its release due to its light-weight resource utilization and its ability to scale easily on minimal hardware. Nginx excels at serving static content quickly and is designed to pass dynamic requests off to other software that is better suited for those purposes.

Table of Content

  1. Ensuring that the server is up to date
  2. Installing Mariadb in Ubuntu 22.04
  3. Installing PHP on Ubuntu 22.04
  4. Installing Nginx on Ubuntu 22.04
  5. Installing php-fpm in Ubuntu 22.04
  6. Creating a simple site and configuring virtual host
  7. Testing the configuration

1. Ensuring that the server is up to date

Before proceeding, it is always a good practice to ensure that the server is up to date. Use these commands to achieve this

sudo apt update
sudo apt upgrade -y

2. Installing Mariadb in Ubuntu 22.04

Mariadb is a popular Opensource relational management system. It is available in the default repositories as mariadb-server.

Install it with this command:

sudo apt install -y mariadb-server

Mariadb will be installed and started by default in Ubuntu 20.04. Check the status with this

$ sudo systemctl status mariadb
● mariadb.service - MariaDB 10.6.7 database server
     Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-10-02 11:37:36 UTC; 30s ago
       Docs: man:mariadbd(8)
             https://mariadb.com/kb/en/library/systemd/
    Process: 34957 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
    Process: 34958 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 34960 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_START_POSITION>
    Process: 35000 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
    Process: 35002 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
   Main PID: 34989 (mariadbd)
     Status: "Taking your SQL requests now..."
      Tasks: 12 (limit: 4392)
     Memory: 57.2M
        CPU: 376ms
     CGroup: /system.slice/mariadb.service
             └─34989 /usr/sbin/mariadbd

Oct 02 11:37:36 unstable-ubuntusrv mariadbd[34989]: Version: '10.6.7-MariaDB-2ubuntu1.1'  socket: '/run/mysqld/mysqld.sock'  port: 3306  Ubuntu 22.04
Oct 02 11:37:36 unstable-ubuntusrv systemd[1]: Started MariaDB 10.6.7 database server.

To ensure that mariadb starts on boot, enable it with this systemd command:

sudo systemctl enable mariadb

Once the mysql service is running, you need to secure it. Mysql provides a commandline utility that will do that:

sudo mysql_secure_installation

The above command will take you throuh prompts to secure and set a root password for the mysql instance.

Check more info on Installing and setting up Mariadb in this guide here.

3. Installing PHP on Ubuntu 22.04

PHP is available in the default Ubuntu 22.04 repos. The latest version of PHP as of writing this blog is PHP 8.1.

Install PHP and some common packages using this command:

sudo apt install -y \
    php \
    php-common \
    php-cli

Check the installed version of PHP

$ apt-cache policy php
php:
  Installed: 2:8.1+92ubuntu1
  Candidate: 2:8.1+92ubuntu1
  Version table:
 *** 2:8.1+92ubuntu1 500
        500 http://europe-west1.gce.archive.ubuntu.com/ubuntu jammy/main amd64 Packages
        100 /var/lib/dpkg/status

Check the installed php version using this command:

$ php -v
PHP 8.1.2 (cli) (built: Aug  8 2022 07:28:23) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2, Copyright (c), by Zend Technologies

4. Installing Nginx on Ubuntu 22.04

We will use Nginx to serve the PHP content. Nginx, as a stable high-performance web server and with a very low consumption of resources, is the perfect match for PHP-FPM. Nginx has an asynchronous architecture that is much more scalable, based on events.

Nginx is available in the default Ubuntu repos. Install it using this command:

sudo apt install -y nginx

Confirm the installed nginx

$ apt-cache policy nginx
nginx:
  Installed: 1.18.0-6ubuntu14.2
  Candidate: 1.18.0-6ubuntu14.2
  Version table:
 *** 1.18.0-6ubuntu14.2 500
        500 http://europe-west1.gce.archive.ubuntu.com/ubuntu jammy-updates/main amd64 Packages
        100 /var/lib/dpkg/status
     1.18.0-6ubuntu14.1 500
        500 http://security.ubuntu.com/ubuntu jammy-security/main amd64 Packages
     1.18.0-6ubuntu14 500
        500 http://europe-west1.gce.archive.ubuntu.com/ubuntu jammy/main amd64 Packages

5. Installing PHP FPM in Ubuntu 22.04

PHP-FPM (an acronym of FastCGI Process Manager) is a hugely-popular alternative PHP (Hypertext Processor) FastCGI implementation. PHP-FPM is the most popular alternative implementation of PHP FastCGI. It has additional features which are really useful for high-traffic websites. When using Nginx with PHP-FPM, performance at the level of memory consumption is improved.

PHP runs as a separated service when using PHP-FPM. By using this PHP version as language interpreter, requests are processed through a TCP/IP socket; so that the Nginx web server only handles the HTTP requests and PHP-FPM interprets the PHP code. The fact of having two separate services is key for increasing efficiency.

Install php-fpm using this command:

sudo apt install -y php-fpm

The service will be started by default. Check its status using this command:

$ sudo systemctl status php8.1-fpm
● php8.1-fpm.service - The PHP 8.1 FastCGI Process Manager
     Loaded: loaded (/lib/systemd/system/php8.1-fpm.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2022-10-02 11:40:28 UTC; 3min 57s ago
       Docs: man:php-fpm8.1(8)
   Main PID: 49130 (php-fpm8.1)
     Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
      Tasks: 3 (limit: 4392)
     Memory: 9.9M
        CPU: 80ms
     CGroup: /system.slice/php8.1-fpm.service
             ├─49130 "php-fpm: master process (/etc/php/8.1/fpm/php-fpm.conf)" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
             ├─49131 "php-fpm: pool www" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" >
             └─49132 "php-fpm: pool www" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" >

Oct 02 11:40:27 unstable-ubuntusrv systemd[1]: php8.1-fpm.service: Deactivated successfully.
Oct 02 11:40:27 unstable-ubuntusrv systemd[1]: Stopped The PHP 8.1 FastCGI Process Manager.
Oct 02 11:40:27 unstable-ubuntusrv systemd[1]: Starting The PHP 8.1 FastCGI Process Manager...
Oct 02 11:40:28 unstable-ubuntusrv systemd[1]: Started The PHP 8.1 FastCGI Process Manager.

To enable php-fpm on boot, use this command:

sudo systemctl enable php8.1-fpm

6. Creating a simple site and configuring virtual host

Nginx allows you to serve multiple sites using virtual hosts. The concept of virtual hosts allows more than one Web site on one system or Web server. The servers are differentiated by their host name. Visitors to the Web site are routed by host name or IP address to the correct virtual host. Virtual hosting allows companies sharing one server to each have their own domain names.

In this example, we will use the domain site1.citizix.com for the virtual host but be free to use the domain of your choice. Please note that the DNS for the domainto be used should already be configured to point to the IP address of the server. Confirm that with:

dig -t A site1.citizix.com

Creating a directory and adding sample content

The default page of nginx is configured as a default virtual host serving content from /var/www/html. It’s a best practice to create the directory of your site in the /var/www directory since its a best practice to serve from there.

Lets create a directory for our site with the following command:

sudo mkdir /var/www/site1.citizix.com

Lets create a simple index.php page to serve from our site. You will require vim installed for this to work, if not use this command:

sudo apt install -y vim

Edit the file:

sudo vim /var/www/site1.citizix.com/index.php

Add content to the file:

<?php phpinfo(); ?>

Creating virtual host (Server blocks)

An Nginx server blocks  can be used to encapsulate configuration details and host more than one domain on a single server. We are going to create a virtual host for our site (site1.citizix.com).

Nginx virtual hosts configurations are stored in the directory /etc/nginx/conf.d/. Lets create a config for our site:

sudo vim /etc/nginx/conf.d/site1.citizix.com.conf

Add the following content

server {
    listen 80;
    server_tokens off;
    client_max_body_size 100M;
    server_name site1.citizix.com;

    access_log /var/log/nginx/site1.citizix.com.log;
    error_log  /var/log/nginx/site1.citizix.com.log;

    root /var/www/site1.citizix.com;
    index index.php;

    if ($host !~* ^(site1.citizix.com)$) {
        return 444;
    }

    location / {
        proxy_read_timeout 600;
        proxy_connect_timeout 600;
        proxy_send_timeout 600;
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_index index.php;
        include /etc/nginx/fastcgi_params;
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

Let us restart the nginx and php-fpm service for the configuration to apply

sudo systemctl restart php8.1-fpm
sudo systemctl restart nginx

7. Testing the configuration

To test the configuration, open your browser and load the domain you set up. In my case it is http://site1.citizix.com. You should see the php info page.

If you haven’t yet configured your DNS settings or simply do not want the site to go live yet, you can modify your computer’s hosts file. To do this, use the following command in your local computer’s CLI

sudo vim /etc/hosts

Then, add the IP address of your actual server followed by the domain name you are configuring, for example:

# Virtual Hosts Local Test
10.2.11.11 site1.citizix.com

Now you should be able to save the file and access it from within a web browser.

Conclusion

Nginx virtual hosts or server blocks are a great way to add additional websites to the same origin server. The number of configuration possibilities for a given site are nearly endless when you start modifying the virtual host configuration file to suit your the specific needs of your site.

In this guide we learnt how to set up a virtual host to serve php content in Ubuntu 22.04.

comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy