Digity Republic

Tech News, Reviews, Deals, and How-To's

Installing LAMP (Linux, Apache, MySQL, and PHP) on Ubuntu 20.04

Installing LAMP

image of LAMP

Installing LAMP: Introduction


Installing LAMP: A “LAMP” stack is a collection of open source applications that commonly deploy together to allow a server to run dynamic webpages and PHP-coded web applications. This word is an abbreviation for the Apache web server and the Linux operating system. PHP processes dynamic content and a MySQL database store the site’s data.

Installing LAMP: Prerequisites

You will need an Ubuntu 20.04 server with a non-root sudo user account and a simple firewall in order to finish this tutorial. Using our first server setup tutorial for Ubuntu 20.04, this can be set up.

Installing LAMP: Installing Apache and updating the firewall is step one.

One of the most widely used web servers worldwide is Apache. It is a wonderful option for hosting a website since it is well-document, has a vibrant user base, and has been in use extensively for a significant portion of the history of the web.

sudo apt update

Install Apache next using:

sudo apt install apache2

Additionally, you’ll ask to confirm the installation of Apache by typing Y and then ENTER.

After the installation is complete, you must change the firewall settings to permit HTTP traffic.

sudo ufw app list

You’ll see the following output:

Output
Available applications:
  Apache
  Apache Full
  Apache Secure
  OpenSSH

What each of these profiles means is as follows:

Apache: This configuration only opens the port (normal, unencrypted web traffic).
Apache Full: This profile allows both ports, which use for regular, unencrypted web traffic, and port 443, which use for TLS/SSL-encrypted communication.
This profile only permits communication that is SSL/TLS encrypted on specified ports.
Since this is a brand-new Apache installation and you haven’t yet set up a TLS/SSL certificate to enable HTTPS traffic on your server.

Use the Apache profile to limit traffic to the port:

sudo ufw allow in "Apache"

You can verify the change with:

sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                                
Apache                     ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)                    
Apache (v6)                ALLOW       Anywhere (v6)     

The firewall is now allowing traffic on the port.

By going to your server’s public IP address in your web browser immediately, you may check that everything went according to plan (if you do not already know it.)

http://your_server_ip

The default Ubuntu 20.04 Apache web page, which is there for testing and informative reasons, will display to you.

Installing LAMP

Your web server is now successfully installed and reachable over your firewall if you can view this page.

How to locate the public IP address of your server

There are several ways to determine your server’s public IP address if you are unsure about it. Typically, you connect to your server using this IP while using SSH.

ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'

You will receive two or three lines in response. Please feel free to test each one as they are all valid addresses, but your computer might only be able to utilize one of them.

Utilizing the curl tool to get feedback from a third party about your server is an alternate approach. This accomplishes by requesting the IP address of a certain server:

curl http://icanhazip.com

Whatever method you choose to obtain your IP address, enter it into the address bar of your web browser to access the default Apache page.

Installing MySQL in Step 2

After setting up a web server, you must set up a database system so that you can manage and store data for your website. A common database management system used in PHP settings is MySQL.

sudo apt install mysql-server

When asked, enter after entering Y to confirm the installation.

It advises that you execute a security script that pre-installs with MySQL after the installation is complete.

sudo mysql_secure_installation

You will prompt to set up the VALIDATE PASSWORD PLUGIN by this.

Answer for yes, or anything else to continue without enabling.

VALIDATE PASSWORD PLUGIN can be used to test passwords
and improve security. It checks the strength of password
and allows the users to set only those passwords which are
secure enough. Would you like to setup VALIDATE PASSWORD plugin?

Press y|Y for Yes, any other key for No:

You will prompt to choose a degree of password validation if you respond “yes.” Remember that if you choose the toughest level of 2 and try to make a password that doesn’t include digits, upper. And lowercase letters, special characters, or based on a word from a common dictionary, you will get problems.

There are three levels of password validation policy:

LOW    Length >= 8
MEDIUM Length >= 8, numeric, mixed case, and special characters
STRONG Length >= 8, numeric, mixed case, special characters and dictionary              file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1

Your server will then request that you choose and confirm a password for the MySQL root user, regardless of whether you decided to configure the VALIDATE PASSWORD PLUGIN. Contrast this with the system root to avoid confusion. The database root user has complete control over the database system and is an administrator user. Even though the MySQL root user’s default authentication mechanism disallows the usage of passwords even when they are set, you should establish a strong password here as an extra layer of security. In a bit, we’ll talk about this.

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y

To answer the remaining questions, press Y and then press the ENTER key when prompted. This will stop remote root logins, delete some anonymous users, delete the test database, load these new rules, and make sure MySQL quickly complies with your modifications.

Once you’re doing, type the following to see if you can access the MySQL console:

sudo mysql

The use of sudo while running this command implies that it will connect to the MySQL server as the administrator database user root. The output should be as follows:

Output
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 22
Server version: 8.0.19-0ubuntu5 (Ubuntu)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Type: to close the MySQL console.

mysql> exit

Even though you specified a password when you ran the mysql secure installation script, you didn’t need to enter it in order to join as the root user. This is due to the administrator MySQL user’s default authentication method, Unix socket, not using a password.

Even though this might at first appear to be a security risk, it actually increases the security of the database server because only system users with sudo privileges connect from the console or through an application running with the same privileges permitting them to log in as the root MySQL user. In real words, that implies your PHP application won’t able to connect using the administrative database root account.

Setting a password for the root MySQL account serves as a safety measure in the event that the Unix socket authentication mechanism is replaced with a password as the default.

Especially if you intend to host many databases on your server. It is recommended to set up separate user accounts with fewer rights for each database in order to boost security.

Your MySQL server has now been set up and protected. The LAMP stack’s last element, PHP, will then install.

Step 3 — Installing PHP

You have Apache installed to serve your content and MySQL installed to store and manage your data. PHP is the component of our setup that will process code to display dynamic content to the final user. In addition to the php package, you’ll need, a PHP module that allows PHP to communicate with MySQL-based databases. You’ll also need libapache2-mod-php to enable Apache to handle PHP files. Core PHP packages will automatically install as dependencies.

To install these packages, run:

sudo apt install php libapache2-mod-php php-mysql

The following command can use once the installation is complete to verify your PHP version:

php -v

Your LAMP stack is now completely functional. But it’s advisable to put up a good Apache Virtual Host to house the files and directories for your website before testing it with a PHP script. In the following phase, we’ll do that.

Output
PHP 7.4.3 (cli) (built: Jul  5 2021 15:13:35) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.3, Copyright (c), by Zend Technologies

Making a Virtual Host for your Website in Step 4

Using virtual hosts, which are analogous to server blocks in Nginx, you may host several domains on a single Apache web server by encapsulating configuration information. You should substitute your own domain name for the one we’ll set up in this article, which is your domain.

The directory for your domain should create as follows:

sudo mkdir /var/www/your_domain

After that, change the $USER environment variable to reflect your current system used to assign ownership of the directory:

sudo chown -R $USER:$USER /var/www/your_domain

Use your chosen command-line editor to then open a fresh configuration file in the sites-available directory of Apache. We’ll use nano in this case:

sudo nano /etc/apache2/sites-available/your_domain.conf

This will produce a brand-new, empty file. Paste the basic setup shown below:

<VirtualHost *:80>
    ServerName your_domain
    ServerAlias www.your_domain 
    ServerAdmin [email protected]
    DocumentRoot /var/www/your_domain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Now that the new virtual host has been enabled, a2ensite may be used:

sudo a2ensite your_domain

Type: to stop Apache from using its default webpage.

sudo a2dissite 000-default

To make sure your configuration file doesn’t contain syntax errors, run:

sudo apache2ctl configtest

Reload Apache to make these modifications effective.

sudo systemctl reload apache2

Although the web root, /var/www/your domain, is now live, it is still empty. In order to verify that the virtual host operates as planned, create an index.html file there:

nano /var/www/your_domain/index.html
<html>
  <head>
    <title>your_domain website</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <p>This is the landing page of <strong>your_domain</strong>.</p>
  </body>
</html>

Now access your server’s domain name or IP address once more in your browser:

Making a Virtual Host

It means your Apache virtual host working as expected.

Installing LAMP: Testing PHP Processing on Your Web Server is Step 5

  • Now that you have a unique place to store the files and directories for your website, let’s construct a PHP test script to make if Apache can handle and process requests for PHP files.
  • Make a new info.php file in your personalized web root folder:
  • Save your work and then exit the file.
  • Use your web browser to access the domain name or IP address of your server, followed by the script name, in this example info.php, to test the script.
http://server_domain_or_IP/info.php
PHP Processing

Installing LAMP: Step 6: PHP Database Connection Testing (Optional)

Create a test table with fictitious data and run a PHP script to query its contents to see if PHP can connect to MySQL and do database queries. Before doing that, we must first establish a test database and a new MySQL user with the necessary access permissions.

sudo mysql
mysql> CREATE DATABASE example_database;

Using mysql native password as the default authentication mechanism, the following command creates a new user with the name example user. The password for this user is defined as a password. However, you should change this value to a strong password of your own choosing.

mysql> CREATE USER 'example_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
mysql> GRANT ALL ON example_database.* TO 'example_user'@'%';
mysql> exit

You’ll get the following result as result:

Output
+--------------------+
| Database           |
+--------------------+
| example_database   |
| information_schema |
+--------------------+
2 rows in set (0.000 sec)

The PHP script that connects to MySQL and searches for your content may now be written. Using your chosen editor, create a new PHP file in your own web root directory. For that, nano will use:

<?php
$user = "example_user";
$password = "password";
$database = "example_database";
$table = "todo_list";

try {
  $db = new PDO("mysql:host=localhost;dbname=$database", $user, $password);
  echo "<h2>TODO</h2><ol>"; 
  foreach($db->query("SELECT content FROM $table") as $row) {
    echo "<li>" . $row['content'] . "</li>";
  }
  echo "</ol>";
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

When you are through editing, save and exit the file.

This page, displaying the content you added to your test table, should appear:

Now that your website’s domain name or public IP address has been set up, you may view this page in your web browser by typing /todo list.php into your browser’s address bar:

http://your_domain_or_IP/todo_list.php

You should see a page like this, showing the content you’ve inserted in your test table:

test table:

This indicates that your PHP environment is prepared to communicate with and connect to your MySQL server.

Conclusion: Installing LAMP

With the help of Apache as the web server and MySQL as the database system, we’ve constructed a versatile basis for delivering PHP websites and apps to your visitors in this book.

You should make sure that connections to your web server are safe right away by providing them over HTTPS. You may do that by securing your website with a free TLS/SSL certificate from Let’s Encrypt.

Do You Need More Help?

Visit our forum, describe your question briefly and get answers