How To Install Linux, Apache, MySQL, PHP (LAMP) Stack On Ubuntu 22.04 - DigitalOcean
How To Install Linux, Apache, MySQL, PHP (LAMP) Stack On Ubuntu 22.04 - DigitalOcean
Prerequisites
Step 1 — Installing Apache and Updating the Firewall
Step 2 — Installing MySQL
Step 3 — Installing PHP
Step 4 — Creating a Virtual Host for your Website
Step 5 — Testing PHP Processing on your Web Server
Step 6 — Testing Database Connection from PHP (Optional)
Conclusion
// Tutorial //
on Ubuntu 22.04
Introduction
A “LAMP” stack is a group of open source software that is typically installed together in
order to enable a server to host dynamic websites and web apps written in PHP. This
term is an acronym which represents the Linux operating system with the Apache web
server. The site data is stored in a MySQL database, and dynamic content is processed
by PHP.
In this guide, you’ll set up a LAMP stack on an Ubuntu 22.04 server.
Prerequisites
In order to complete this tutorial, you will need to have an Ubuntu 22.04 server with a
non-root sudo -enabled user account and a basic firewall. This can be configured using
our initial server setup guide for Ubuntu 22.04.
Step 1 — Installing Apache and Updating the Firewall
Output
Available applications:
Apache
Apache Full
Apache Secure
OpenSSH
Output
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Apache ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Apache (v6) ALLOW Anywhere (v6)
The default Ubuntu 22.04 Apache web page is there for informational and testing
purposes. Below is an example of the Apache default web page:
Now that you have a web server up and running, you need to install the database
system to be able to store and manage data for your site. MySQL is a popular database
management system used within PHP environments.
Again, use apt to acquire and install this software:
$ sudo apt install mysql-server Copy
When prompted, confirm installation by typing Y , and then ENTER .
When the installation is finished, it’s recommended that you 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.
Warning: As of July 2022, an error will occur when you run the
mysql_secure_installation script without some further configuration. The reason is that
this script will attempt to set a password for the installation’s root MySQL account but,
by default on Ubuntu installations, this account is not configured to connect using a
password.
Prior to July 2022, this script would silently fail after attempting to set the root account
Thispassword and continue
site uses cookies on with
and related the rest ofasthedescribed
technologies, prompts.in However, as of this writing the
our privacy policy
policy,
scriptenhanced , for purposes
will returnuser that
theexperience, may
following error include site operation,
after you enter and confirm a password:
analytics, or advertising. You may
choose to consent to our use of these technologies, or manage
your own preferences.
Output
... Failed! Error: SET PASSWORD has no significance for user 'root'@'localhost'
New password:
This will lead the script into a recursive loop which you can only get out of by closing
your terminal window.
Because the mysql_secure_installation script performs a number of other actions that
are useful for keeping your MySQL installation secure, it’s still recommended that you run
it before you begin using MySQL to manage your data. To avoid entering this recursive
loop, though, you’ll need to first adjust how your root MySQL user authenticates.
First, open up the MySQL prompt:
$ sudo mysql Copy
Then run the following ALTER USER command to change the root user’s authentication
method to one that uses a password. The following example changes the authentication
method to mysql_native_password :
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY ' Copy
If you answer “yes”, you’ll be asked to select a level of password validation. Keep in mind
that if you enter 2 for the strongest level, you will receive errors when attempting to set
any password which does not contain numbers, upper and lowercase letters, and
special characters:
There are three levels of password validation policy:
Regardless of whether you chose to set up the VALIDATE PASSWORD PLUGIN , your server
will next ask you to select and confirm a password for the MySQL root user. This is not
to be confused with the system root. The database root user is an administrative user
with full privileges over the database system. Even though the default authentication
method for the MySQL root user doesn’t involve using a password, even when one is
set, you should define a strong password here as an additional safety measure.
If you enabled password validation, you’ll be shown the password strength for the root
password you just entered and your server will ask 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 f
For the rest of the questions, press Y and hit the ENTER key 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 immediately respects the changes you have made.
When you’re finished, test whether you’re able to log in to the MySQL console by typing:
This site uses cookies and related technologies, as described in
our privacy policy
policy,
, for purposes that may include site operation, Copy
analytics, enhanced user experience, or advertising. You may
$ sudo mysql
choose to consent to our use of these technologies, or manage
your own preferences.
This will connect to the MySQL server as the administrative database user root, which is
inferred by the use of sudo when running this command. Below is an example 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)
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
For increased security, it’s best to have dedicated user accounts with less expansive
privileges set up for every database, especially if you plan on having multiple databases
hosted on your server.
Note: There are some older versions of PHP that doesn’t support
caching_sha2_password , the default authentication method for MySQL 8. For that reason,
when creating database users for PHP applications on MySQL 8, you may need to
Thisconfigure
site uses cookies and relatedtotechnologies,
your, forapplication use theinclude as described in plug-in instead. This
our privacy policy
policy, purposes that may site operation,
mysql_native_password
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 php-mysql ,
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 be installed as dependencies.
To install these packages, run the following command:
$ sudo apt install php libapache2-mod-php php-mysql Copy
Once the installation is finished, run the following command to confirm your PHP
version:
$ php -v Copy
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
At this point, your LAMP stack is fully operational, but before testing your setup with a
PHP script, it’s best to set up a proper Apache Virtual Host to hold your website’s files
and folders.
Step 4 — Creating 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 this with your own domain name.
ThisNote
site usescase
cookies and
are related technologies, asas DNS
described in provider, check out our product
our privacy: Inpolicy, youpurposes
policy, for usingthatDigitalOcean hosting
may include site operation,
documentation
analytics, for detailed
enhanced user instructions
experience, on howYoutomay
or advertising. set up a new domain name and point
choose to consent to our use of these technologies, or manage
youritown
to your server.
preferences.
Apache on Ubuntu 22.04 has one virtual host enabled by default that is configured to
serve documents from the /var/www/html directory. While this works well for a single
site, it can become unwieldy if you are hosting multiple sites. Instead of modifying
/var/www/html , we’ll create a directory structure within /var/www for the your_domain
site, leaving /var/www/html in place as the default directory to be served if a client
request doesn’t match any other sites.
Create the directory for your_domain as follows:
$ sudo mkdir /var/www/ your_domain Copy
Next, assign ownership of the directory with the $USER environment variable, which will
reference your current system user:
$ sudo chown -R $USER:$USER /var/www/ your_domain Copy
Then, open a new configuration file in Apache’s sites-available directory using your
preferred command-line editor. Here, we’ll use nano :
$ sudo nano /etc/apache2/sites-available/ your_domain .conf Copy
This will create a new blank file. Add in the following bare-bones configuration with your
own domain name:
/etc/apache2/sites-available/your_domain.conf
<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>
Save and close the file when you’re done. If you’re using nano , do that by pressing
CTRL+X , then Y and ENTER .
With this VirtualHost configuration, we’re telling Apache to serve your_domain using
/var/www/ your_domain as the web root directory. If you’d like to test Apache without a
domain
This
ourbyprivacy
name,
site uses
policy
policy,
,
you
cookies
for
canrelated
and remove
purposes
or comment
technologies,
that may include
as out the options
described
site
in ServerName and ServerAlias
operation,
adding
analytics, a poundusersign
enhanced ( # ) the beginning
experience, of each
or advertising. option’s lines.
You may
choose to consent to our use of these technologies, or manage
Now,ownusepreferences.
your a2ensite to enable the new virtual host:
$ sudo a2ensite your_domain Copy
You might want to disable the default website that comes installed with Apache. This is
required if you’re not using a custom domain name, because in this case Apache’s
default configuration would override your virtual host. To disable Apache’s default
website, type:
$ sudo a2dissite 000-default Copy
To make sure your configuration file doesn’t contain syntax errors, run the following
command:
$ sudo apache2ctl configtest Copy
Finally, reload Apache so these changes take effect:
$ sudo systemctl reload apache2 Copy
Your new website is now active, 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 works as expected:
$ nano /var/www/ your_domain /index.html Copy
Include the following content in this file:
/var/www/your_domain/index.html
<html>
<head>
<title> your_domain website</title>
</head>
<body>
<h1>Hello World!</h1>
Save and close the file, then go to your browser and access your server’s domain name
This IPsiteaddress:
uses cookies and related technologies, as described in
ouror privacy policy, for purposes that may include site operation,
policy,
analytics, enhanced user experience, or advertising. You may
choose to consent to our use of these technologies, or manage
yourhttp://
own preferences.
server_domain_or_IP
Your web page should reflect the contents in the file you just edited:
You can leave this file in place as a temporary landing page for your application until you
set up an index.php file to replace it. Once you do that, remember to remove or rename
the index.html file from your document root, as it would take precedence over an
index.php file by default.
With the default DirectoryIndex settings on Apache, a file named index.html will always
take precedence over an 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 to visitors. Because this page will take precedence over the index.php page, it
will then become the landing page for the application. Once maintenance is over, the
index.html is renamed or removed from the document root, bringing back the regular
application page.
In case you want to change this behavior, you’ll need to edit the /etc/apache2/mods-
enabled/dir.conf file and modify the order in which the index.php file is listed within the
DirectoryIndex directive:
After saving and closing the file, you’ll need to reload Apache so the changes take
effect:
This$sitesudo
usessystemctl
cookies andreload
relatedapache2
technologies, as described in Copy
our privacy policy,
policy, for purposes that may include site operation,
analytics, enhanced user experience, or advertising. You may
In the tonext
choose step,towe’
consent ourll use
create a PHPtechnologies,
of these script to test that PHP is correctly installed and
or manage
your own preferences.
configured on your server.
Step 5 — Testing PHP Processing on your Web Server
Now that you have a custom location to host your website’s files and folders, create a
PHP test script to confirm that Apache is able to handle and process requests for PHP
files.
Create a new file named info.php inside your custom web root folder:
$ nano /var/www/ your_domain /info.php Copy
This will open a blank file. Add the following text, which is valid PHP code, inside the file:
/var/www/your_domain/info.php
<?php Copy
phpinfo();
Note: The previous ALTER USER statement sets the root MySQL user to authenticate with
the caching_sha2_password plugin. Per the official MySQL documentation,
caching_sha2_password is MySQL’s preferred authentication plugin, as it provides more
secure password encryption than the older, but still widely used,
mysql_native_password .
However, some versions of PHP don’t work reliably with caching_sha2_password . PHP
has reported that this issue was fixed as of PHP 7.4, but if you encounter an error when
trying to log in to phpMyAdmin later on, you may want to set root to authenticate with
mysql_native_password instead:
Next, create a test table named todo_list. From the MySQL console, run the following
statement:
mysql> CREATE TABLE example_database . todo_list ( Copy
mysql> item_id INT AUTO_INCREMENT,
mysql> content VARCHAR(255),
mysql> PRIMARY KEY(item_id)
This site uses cookies and related technologies, as described in
mysql> );
our privacy policy,
policy, for purposes that may include site operation,
analytics, enhanced user experience, or advertising. You may
choose
Insert toa consent
few rowsto ofourcontent
use of these
in thetechnologies,
test table.orRepeat
managethe next command a few times,
your own preferences.
using different values, to populate your test table:
Copy
mysql> INSERT INTO example_database . todo_list (content) VALUES (" My first important
To confirm that the data was successfully saved to your table, run:
mysql> SELECT * FROM example_database . todo_list ; Copy
The following is the output:
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 confirming that you have valid data in your test table, exit the MySQL console:
mysql> exit Copy
Now you can create the PHP script that will connect to MySQL and query for your
content. Create a new PHP file in your custom web root directory using your preferred
editor:
$ nano /var/www/ your_domain / todo_list.php Copy
The following PHP script connects to the MySQL database and queries for the content
of the todo_list table, exhibiting the results in a list. If there’s a problem with the
database connection, it will throw an exception.
Add this content into your todo_list.php script, remembering to replace the
example_user and password with your own:
/var/www/your_domain/todo_list.php
This<?php
site uses cookies and related technologies, as described in Copy
our$user
privacy= policy,
policy, for purposes that may include site operation,
analytics, enhanced user experience, or advertising. You may
" example_user ";
choose to consent
$password to our use";of these technologies, or manage
= " password
your$database
own preferences.
= " 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();
}
This web page should reveal the content you’ve inserted in your test table to your
visitor:
That means your PHP environment is ready to connect and interact with your MySQL
server.
Conclusion
In this guide, you’ve built a flexible foundation for serving 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
secured,
This site usesbycookies
ourEncrypt
serving
privacytopolicy,
policy, for
andthem
purposes
viathattechnologies,
related HTTPS.
may
In order
include
to accomplish
as described
site
in
operation,
that, you can use Let’s
secureuser
analytics, enhanced yourexperience,
site with ora free TLS/SSL
advertising. Youcertificate.
may
choose to consent to our use of these technologies, or manage
your own preferences.
Thanks for learning with the DigitalOcean Community. Check out our offerings
for compute, storage, networking, and managed databases.
Learn more about us ->
Leave a comment...
Once this is done, you can use mysql_secure_installation. Afterwards you can
change the authentication method back to how it was before.
Hope this helps.
Show replies Reply
Click below to sign up and get $200 of credit to try our products over 60 days!
Sign up
Popular Topics
Ubuntu
Linux Basics
JavaScript
Python
MySQL
Docker
Kubernetes
All tutorials ->
This siteManaged
uses cookiesHosting
and related technologies, as described in
ourFree
privacy policy, for purposes->
policy, that may include site operation,
analytics, enhanced user experience, or advertising. You may
choose to consent to our use of these technologies, or manage
your own preferences.
Get our biweekly
newsletter
Featured on Community
DigitalOcean Products
Enter your email to get $200 in credit for your first 60 days with DigitalOcean.
Email address
Send My Promo
New accounts only. By submitting your email you agree to our Privacy Policy.
Company
ourProducts
This site uses cookies and related technologies, as described in
privacy policy,
policy, for purposes that may include site operation,
analytics, enhanced user experience, or advertising. You may
choose to consent to our use of these technologies, or manage
Community
your own preferences.
Solutions
Contact