How to install Linux, Apache, MySQL, PHP (LAMP) on Ubuntu

0 Shares
0
0
0
0

Introduction

The “LAMP” stack is a group of open source software that are usually installed together to enable a server to host dynamic websites and web applications written in PHP. The term stands for Linux operating system with Apache web server. The site data is stored in a MySQL database and the dynamic content is processed by PHP.

In this guide, you will set up a LAMP stack on an Ubuntu 22.04 server. These steps are consistent for Ubuntu 18.04 and above.

Prerequisites

To complete this tutorial, you will need a server running Ubuntu, along with a non-root user with sudo privileges, and an active firewall. For instructions on how to set these up, please select your distribution from this list and follow our initial server installation guide.

Step 1 – Install Apache and Update Firewall

The Apache web server is one of the most popular web servers in the world. It is well documented, has an active community of users, and has been widely used throughout much of the web's history, making it a great choice for website hosting.

Start by updating the package manager cache. If this is your first time using sudo in this session, you will be prompted to provide your user password to verify that you have the appropriate privileges to manage system packages with apt:

sudo apt update

Then start Apache using:

sudo apt install apache2

You will be asked to confirm the installation of Apache. Confirm by pressing Y and then ENTER.

Once the installation is complete, you need to configure your firewall settings to allow HTTP traffic. Ubuntu's default firewall configuration tool is called Uncomplicated Firewall (UFW). It has various application profiles that you can use. To list all available UFW application profiles, run this command:

sudo ufw app list
Output
Available applications:
Apache
Apache Full
Apache Secure
OpenSSH

Here is what each of these profiles means:

  • Apache: This profile only opens port 80 (normal, unencrypted web traffic).
  • Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
  • Apache Secure: This profile only opens port 443 (TLS/SSL encrypted traffic).

For now, it's best to only allow connections on port 80, since this is a new Apache installation and you haven't yet configured a TLS/SSL certificate to allow HTTPS traffic on your server.

To allow traffic only on port 80, use the Apache profile:

sudo ufw allow in "Apache"

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

Traffic on port 80 is now allowed through the firewall.

You can immediately do a quick check to make sure everything went according to plan by visiting your server's public IP address in a web browser (see the note below the next heading to find out what your public IP address is if you don't have this information. Previously, previously):

http://your_server_ip

The default Apache Ubuntu web page is for informational and testing purposes. Below is an example of the default Apache web page for Ubuntu 22.04:

If you can see this page, your web server is properly installed and accessible through your firewall.

How to find your server's public IP address

If you don't know what your server's public IP address is, there are a few ways to find it. Typically, this is the address you use to connect to your server via SSH.

There are a few different ways to do this from the command line. First, you can use the iproute2 tool to get your IP address by typing this:

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

This will return two or three lines. They are all valid addresses, but your computer may only be able to use one of them, so try each one.

An alternative method is to use the curl tool to contact an external party to tell it how it sees your server. This is done by asking a specific server what your IP address is:

curl http://icanhazip.com

Whichever method you choose, type your IP address into your web browser to check that your server is running.

Step 2 – Install MySQL

Now that you have a web server, you need to install a database system so that you can store and manage data for your site. MySQL is a popular database management system used in PHP environments.

Use apt again to obtain and install this software:

sudo apt install mysql-server

When prompted, confirm the installation by typing Y and then ENTER Confirm.

Once the installation is complete, it is recommended to run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system.

Start the interactive script by running the following:

sudo mysql_secure_installation

This question asks you if you want to VALIDATE PASSWORD PLUGIN Configure.

To continue without activating, answer Y, yes, or anything else.

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:

If you answer "Yes," you will be asked to select a password validation level. Keep in mind that if you enter 2 for the strongest level, you will receive errors when trying to set a password that does not contain numbers, uppercase and lowercase letters, and special characters:

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

Regardless of whether you choose to set the VALIDATE PASSWORD PLUGIN, your server will next ask you to choose and confirm a password for the MySQL root user. This should not be confused with the system root. The database root user is an administrative user with full privileges on the database system. Even though the default authentication method for the MySQL root user does not involve the use of a password, even when a password is set, you should define a strong password here as an additional security measure.

If you have password verification enabled, you will be shown the password strength of the root password you just entered, and your server will ask you if you want to continue with that password. If you are happy with your current password, enter Y for “yes” at the prompt:

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

For the rest of the questions, press Y and press ENTER at each prompt. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL will immediately honor the changes you made.

When you're done, test if you can log in to the MySQL console by typing the following:

sudo mysql

This connects to the MySQL server as the administrative database user root, which is inferred using sudo when running this command. Below is a sample output:

Output
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 10
Server version: 8.0.28-0ubuntu4 (Ubuntu)
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
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>

To exit the MySQL console, type:

exit

Note that you do not need to provide a password to connect as the root user, even if you defined a password when you ran the mysql_secure_installation script. This is because the default authentication method for the administrative MySQL user is unix_socket instead of a password. While this may seem like a security concern, it makes the database server more secure because the only users allowed to log in as the MySQL root user are system users with sudo privileges who connect from the console or through a program running with the same privileges. . In practical terms, this means that you cannot use the administrative database root user to connect from your PHP application. Setting a password for the MySQL root account acts as a safeguard in case the default authentication method changes from unix_socket to password.

For increased security, it's best to set up dedicated user accounts with less extensive privileges for each database, especially if you plan to host multiple databases on your server.

Your MySQL server is now installed and secured. Next, you will install PHP, the final component in the LAMP stack.

Step 3 – Install PHP

You have installed Apache to serve your content and MySQL to store and manage your data. PHP is the part of our setup that processes the code to display dynamic content to the end user. In addition to the php package, you need php-mysql, a PHP module that allows PHP to communicate with MySQL-based databases. You also need libapache2-mod-php to enable Apache to handle PHP files. The core PHP packages are automatically installed as dependencies.

To install these packages, run the following command:

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

Once the installation is complete, run the following command to verify your PHP version:

php -v
Output
PHP 8.1.2 (cli) (built: Mar 4 2022 18:13:46) (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
Change Apache directory (optional)

In some cases, you want to change the way Apache serves files when requesting a directory. Currently, if a user requests a directory from the server, Apache first looks for a file called index.html. We want to tell the web server to prioritize PHP files over others so that Apache looks for an index.php file first. If you don't do this, an index.html file placed in the application's document root will always take precedence over the index.php file.

To make this change, open the dir.conf configuration file in a text editor of your choice. Here, we will use nano:

sudo nano /etc/apache2/mods-enabled/dir.conf

It will look like this:

<IfModule mod_dir.c>
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>

Move the PHP index file (specified above) to the first position after the DirectoryIndex specification, like this:

<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

When you're done, save and close the file by pressing CTRL+X. Confirm the save by typing Y and then press ENTER to confirm the location where you want to save the file.

After this, restart the Apache web server to make your changes take effect. You can do this with the following command:

sudo systemctl restart apache2

You can also check the status of the apache2 service using systemctl:

sudo systemctl status apache2
Sample Output
● apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Drop-In: /lib/systemd/system/apache2.service.d
└─apache2-systemd.conf
Active: active (running) since Thu 2021-07-15 09:22:59 UTC; 1h 3min ago
Main PID: 3719 (apache2)
Tasks: 55 (limit: 2361)
CGroup: /system.slice/apache2.service
├─3719 /usr/sbin/apache2 -k start
├─3721 /usr/sbin/apache2 -k start
└─3722 /usr/sbin/apache2 -k start
Jul 15 09:22:59 ubuntu1804 systemd[1]: Starting The Apache HTTP Server...
Jul 15 09:22:59 ubuntu1804 apachectl[3694]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' di
Jul 15 09:22:59 ubuntu1804 systemd[1]: Started The Apache HTTP Server.

To get out of this situation, Q Press .

Install PHP extensions (optional)

To extend PHP's functionality, you can install a few additional modules. To see the available options for PHP modules and libraries, enter the apt search results into less, a pager that lets you scroll through the output of other commands:

apt search php- | less

Use the arrow keys to move up and down and press the Q button to exit.

The results are all the optional components you can install. It gives you a brief description for each:

bandwidthd-pgsql/bionic 2.0.1+cvs20090917-10ubuntu1 amd64
Tracks usage of TCP/IP and builds html files with graphs
bluefish/bionic 2.2.10-1 amd64
advanced Gtk+ text editor for web and software development
cacti/bionic 1.1.38+ds1-1 all
web interface for graphing of monitoring systems
ganglia-webfrontend/bionic 3.6.1-3 all
cluster monitoring toolkit - web front-end
golang-github-unknwon-cae-dev/bionic 0.0~git20160715.0.c6aac99-4 all
PHP-like Compression and Archive Extensions in Go
haserl/bionic 0.9.35-2 amd64
CGI scripting program for embedded environments
kdevelop-php-docs/bionic 5.2.1-1ubuntu2 all
transitional package for kdevelop-php
kdevelop-php-docs-l10n/bionic 5.2.1-1ubuntu2 all
transitional package for kdevelop-php-l10n
…

To learn more about what each module does, you can search the internet for more information about them. Also, look at the long package descriptions by typing:

apt show package_name

There will be a lot of output, with a field called Description that provides a further explanation of the module's functionality.

For example, to find out what the php-cli module does, you can type this:

apt show php-cli

Along with a wealth of other information, you'll find something like this:

Output
…
Description: command-line interpreter for the PHP scripting language (default)
This package provides the /usr/bin/php command interpreter, useful for
testing PHP scripts from a shell or performing general shell scripting tasks.
.
PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used
open source general-purpose scripting language that is especially suited
for web development and can be embedded into HTML.
.
This package is a dependency package, which depends on Ubuntu's default
PHP version (currently 7.2).
…

If, after research, you decide that you want to install a package, you can do so using the apt install command, just like you would with any other software.

If you decide that php-cli is what you need, you can type:

sudo apt install php-cli

If you want to install more than one module, you can do so by listing each module, separated by a space, followed by the apt install command, like this:

sudo apt install package1 package2 ...

At this point, your LAMP stack is installed and configured. Before doing anything else, we recommend setting up an Apache virtual host so that you can store your server configuration details.

At this point, your LAMP stack is fully operational, but before testing your setup with a PHP script, it's a good idea to set up a suitable Apache virtual host to hold your website files and folders.

Step 4 – Create a virtual host for your website

When using the Apache web server, you can create virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. In this guide, we'll set up a domain called your_domain, but you should replace that with your own domain name.

Apache on Ubuntu has a virtual host enabled by default that is configured to serve documents from the /var/www/html directory. While this works fine for a single site, it can get cumbersome if you host multiple sites. Instead of changing /var/www/html, we will create a directory structure in /var/www for the your_domain site and leave /var/www/html as the default directory to serve unless requested by the client. Match any other site

Create a directory for your_domain as follows:

sudo mkdir /var/www/your_domain

Next, assign ownership of the directory with the environment variable $USER, which will refer to the current user on your system:

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

Next, open a new configuration file in the Apache sites-available directory using your favorite command line editor. Here, we'll use nano:

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

This will create a new empty file. Add the following bare-bones configuration with your domain name:

<VirtualHost *:80>
ServerName your_domain
ServerAlias www.your_domain
ServerAdmin webmaster@localhost
DocumentRoot /var/www/your_domain
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

When you're done, save and close the file. If you're using nano, do this by pressing CTRL+X, then Y, and ENTER.

With this VirtualHost configuration, we tell Apache to serve your_domain using /var/www/your_domain as the web root directory. If you want to test Apache without a domain name, you can remove or comment out the ServerName and ServerAlias ​​options by adding a pound sign (#) at the beginning of each option line.

Now, use a2ensite to activate the new virtual host:

sudo a2ensite your_domain

You may want to disable the default website installed with Apache. This is necessary if you are not using a custom domain name, as in this case Apache will override your default virtual host settings. To disable the default Apache website, type:

sudo a2dissite 000-default

To ensure that your configuration file does not contain syntax errors, run the following command:

sudo apache2ctl configtest

Finally, reload Apache for these changes to take effect:

sudo systemctl reload apache2

Your new website is now live, but the web root /var/www/your_domain is still empty. Create an index.html file in that location to test that the virtual host is working as expected:

nano /var/www/your_domain/index.html

Place the following content in this file:

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

Save and close the file, then go to your browser and access your server's domain name or IP address:

http://server_domain_or_IP

Your web page should reflect the contents of the file you just edited:

You can leave this file as a temporary landing page for your application until you set up an index.php file to replace it. Once you do this, remember to remove or rename the index.html file from your document root, as it takes precedence over the index.php file by default.

A note about DirectoryIndex in Apache

With the default DirectoryIndex settings in Apache, a file named index.html always takes precedence over the index.php file. This is useful for setting up maintenance pages in PHP applications, by creating a temporary index.html file containing an informative message for visitors. Since this page takes precedence over the index.php page, it then becomes the application's landing page. After the maintenance is complete, index.html is renamed or removed from the document root, restoring the normal application page.

If you want to change this behavior, you need to edit the /etc/apache2/mods-enabled/dir.conf file and change the indexing order of the index.php file in the DirectoryIndex directive:

sudo nano /etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

After saving and closing the file, you need to reload Apache for the changes to take effect:

sudo systemctl reload apache2

Next, we will create a PHP script to test that PHP is properly installed and configured on your server.

Step 5 – Test PHP processing on your web server

Now that you have a custom location to host your website files and folders, create a PHP test script to verify that Apache is able to handle and process requests for PHP files.

Create a new file named info.php in your custom web root folder:

nano /var/www/your_domain/info.php

This will open a blank file. Add the following text, which is valid PHP code, to the file:

<?php
phpinfo();

When you're done, save and close the file.

To test this script, go to your web browser and access your server's domain name or IP address, followed by the script name, which in this case is info.php:

http://server_domain_or_IP/info.php

Here is an example of a default PHP web page:

This page provides information about your server from a PHP perspective. It is useful for debugging and ensuring that your settings are being applied correctly.

If you see this page in your browser, your PHP installation is working as expected.

After reviewing the information about your PHP server through that page, it is best to delete the file you created as it contains sensitive information about your PHP environment and your Ubuntu server. To do this, use rm:

sudo rm /var/www/your_domain/info.php

You can always recreate this page if you need to access the information again.

Step 6 – Testing the Database Connection from PHP (Optional)

If you want to test whether PHP is able to connect to MySQL and execute database queries, you can create a test table with test data and query its contents from a PHP script. Before doing this, you need to create a test database and a new MySQL user that is properly configured to access it.

Create a database named example_database and a user named example_user. You can replace these names with different values.

First, connect to the MySQL console using the root account:

sudo mysql

To create a new database, run the following command from your MySQL console:

CREATE DATABASE example_database;

Now create a new user and give it full privileges on the custom database you just created.

The following command creates a new user named example_user that is authenticated with the caching_sha2_password method. We define the password for this user as password, but you should replace this value with a secure password of your choice.

CREATE USER 'example_user'@'%' IDENTIFIED BY 'password';

Now grant this user permissions on the example_database database:

GRANT ALL ON example_database.* TO 'example_user'@'%';

This gives the user example_user full privileges to the database example_database, while preventing the user from creating or modifying other databases on your server.

Now exit the MySQL shell:

exit

Test whether the new user has the appropriate permissions by logging into the MySQL console again, this time using custom user credentials:

mysql -u example_user -p

Note the -p flag in this command, which asks you to choose the password you used when creating the example_user user. Once you're logged in to the MySQL console, verify that you have access to the example_database database:

SHOW DATABASES;

This will give you the following output:

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

Then create a test table called todo_list. From the MySQL console, run the following statement:

CREATE TABLE example_database.todo_list (
item_id INT AUTO_INCREMENT,
content VARCHAR(255),
PRIMARY KEY(item_id)
);

Insert a few rows of data into the test table. Repeat the following command several times using different values to populate your test table:

INSERT INTO example_database.todo_list (content) VALUES ("My first important item");

To verify that the data was successfully saved to your table, run:

SELECT * FROM example_database.todo_list;

The output is as follows:

Output
+---------+--------------------------+
| item_id | content |
+---------+--------------------------+
| 1 | My first important item |
| 2 | My second important item |
| 3 | My third important item |
| 4 | and this one more thing |
+---------+--------------------------+
4 rows in set (0.000 sec)

After verifying that you have valid data in your test table, exit the MySQL console:

exit

Now you can create the PHP script that will connect to MySQL and search your content. Create a new PHP file in the root directory of your custom web using your favorite editor:

nano /var/www/your_domain/todo_list.php

The following PHP script connects to a MySQL database, searches the contents of the todo_list table, and displays the results in a list. It throws an exception if there is a problem with the database connection.

Add this content to your todo_list.php script, remembering to replace example_user and your password:

<?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();
}

Save and close the file when you are finished editing.

You can now access this page in your web browser by visiting the domain name or public IP address configured for your website followed by /todo_list.php:

http://your_domain_or_IP/todo_list.php

This web page should display the content you included in your test table to your visitor:

This means that your PHP environment is ready to connect and interact with your MySQL server.

Result

In this guide, you have created a flexible foundation for delivering PHP websites and applications to your visitors using Apache as a web server and MySQL as a database system.

As an immediate next step, you should ensure that connections to your web server are secure, by serving over HTTPS. To do this, you can use Let's Encrypt on Ubuntu 22.04 / 20.04 / 18.04 to secure your site with a free TLS/SSL certificate.

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like