Chat Zalo Chat Messenger Phone Number Đăng nhập
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu


A “LAMP” stack is a group of open source software that is typically installed together to allow a server to host dynamic websites and web applications. This term is actually an acronym that represents the Linux operating system, with the web server Apache. Site data is stored in an Mand SQL database and PHP processes the dynamic content.

In this guide, we will install a LAMP stack on an Ubuntu 18.04 server.

Prerequisites To

complete this tutorial, you will need to have an Ubuntu 18.04 server with a non-root sudo-enabled user account and a basic firewall configured. To set this up, you can follow our initial server setup guide for Ubuntu 18.04.

Step 1 — Installing Apache and updating the firewall

Apache web server

is a popular open source web server that can be used in conjunction with PHP to host dynamic websites. It is well documented and has been widely used for much of the web’s history.

First, make sure

your apt cache is up to date with: sudo apt update If this

is your first time using sudo in this session, you will be asked to provide your regular user’s password to validate your permissions.

Once the cache has been updated, you can install Apache with:

  1. sudo apt
  1. install apache2

After entering this command, apt will tell you which packages it plans to install and how much additional disk space they will take up. Press Y and press ENTER to confirm, and the installation will continue.

Adjust your firewall

to allow

web traffic Next,

assuming you have followed the initial server setup instructions and enabled the UFW firewall, make sure that your firewall allows HTTP and HTTPS traffic. You can verify

that UFW has an application profile for Apache like this:

  1. sudo ufw app list

OutputAvailable applications: ApacheApache FullApache Secure OpenSSH

If you look at the details of Apache’s full profile, you’ll see that it allows traffic to ports 80 and 443


  1. Sudo UFW “Apache Full” Application

Information OutputProfile: Apache Full title: Web server (HTTP, HTTPS) Description: Apache v2 is the next generation of the ubiquitous Apache web server. Ports: 80,443/tcp

To allow incoming HTTP and HTTPS traffic for this server, run:

  1. sudo ufw allow “Apache Full”

You can do a random check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser (see the note below the heading below to find out what your public IP address is if you don’t already have this information):


You will see the default Ubuntu 18.04 Apache webpage, which is there for informational and testing purposes. It should look something like this:


you see this page, then your web server is now 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


, there are several ways to find it. Usually, 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 iproute2 tools to get your IP address by typing this:

  1. ip addr show eth0 | grep inet | awk ‘{ print $2; }’ | sed ‘s//.*$//’

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

An alternative method is to use the curl utility to contact an external party to tell them how they see your server. This is done by asking a specific server what

its IP address is:

  1. sudo apt install curl curl

Regardless of which method you use to get your IP address, type it into your web browser’s address bar to see Apache’s default page.

Step 2 — Installing MySQL

Now that you have your web server up and running, it’s time to install MySQL. MySQL is a database management system. Basically, you will organize and provide access to databases where your site can store information.

Again, use apt to purchase and install this software:

  1. sudo apt install mysql-server

This command will also show you a list of the packages that will be installed, along with the amount of disk space they will occupy. Type Y to continue.

When the installation is complete, run a simple security script that comes pre-installed with MySQL that will remove some dangerous defaults and block access to your database system. Start the interactive script by running:

  1. sudo mysql_secure_installation

This will ask you if you want to configure the VALIDATE PASSWORD PLUGIN.

Answer Y 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 the password and allows users to set only those passwords that are strong enough. Do you want to configure the VALIDATE PASSWORD plug-in? Press y| And for Yes, any other key for No:

If you answer “yes”, you will be prompted to select a password validation level. Note that if you enter 2 for the strongest level, you will receive errors when trying to set any password that does not contain numbers, uppercase and lowercase letters, and special characters, or that is based on common dictionary words.

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 uppercase and lowercase, special characters, and dictionary file Enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1

Regardless of whether you chose to configure the VALIDATE PASSWORD ADD-ON, your server will ask you to select and confirm a password for the MySQL root user. This should not be confused with the root of the system. The root user of the database is an administrative user with full privileges on the database system. Although the default authentication method for the MySQL root user dispenses with the use of a password, even when one is set, you must define a strong password here as an additional security measure. We’ll talk about this in a moment.

If you have enabled password validation, you will be shown the password strength for the root password you just entered and your server will ask if you want to change that password. If you are satisfied with your current password, enter N for “no” when prompted: Use existing password for root

. Estimated password strength: 100 Change password for root? ((Press y| And for Yes, any other key for No) : n

For the rest of the questions, press Y and press the ENTER key on each request. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MySQL immediately honors the changes you’ve made.

When you’re done, test whether you can log in to the MySQL console by typing:


  1. mysql

This will connect to the MySQL server as the user root of the administrative database, which is inferred by using sudo when running this command. You should see output like this:

OutputWelcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection ID is 5 Server version: 5.7.34-0ubuntu0.18.04.1 (Ubuntu) Copyright (c) 2000, 2021, 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:

  1. exit

Note that you did not need to provide a password to connect as root, even if you defined one when you ran the mysql_secure_installation script. This is because the default authentication method for the MySQL administrative user is unix_socket instead of password. Although this may seem like a security issue at first, it makes the database server more secure because the only users authorized to log in as the root user of MySQL are system users with sudo privileges who connect from the console or through an application running with the same privileges. In practical terms, that means you won’t be able to use the root user of the administrative database to connect from your PHP application. Setting a password for the MySQL root account works as a protection, in case the default authentication method is changed from unix_socket to password.

To increase security, it’s best to have dedicated user accounts with less expansive privileges configured for each database, especially if you plan to have multiple databases hosted on your server. See our guide on How to create a new user and grant permissions in MySQL for detailed instructions on how to create MySQL users and configure database access rights.

Your MySQL server is now installed and protected. Next, we will install PHP, the final component on the LAMP stack.

Step 3 – PHP Installation PHP

is the

component of your configuration that will process the code to display dynamic content. You can run scripts, connect to your MySQL databases for insights, and deliver the processed content to your web server so you can display the results to your visitors.

Once again, take advantage of the apt system to install PHP. In addition to the php package, you will also need libapache2-mod-php to integrate PHP into Apache, and the php-mysql package to allow PHP to connect to MySQL databases. Run the following command to install all three packages and their dependencies:

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

This should install PHP without any problems. We’ll test this in a moment.

Changing the Apache directory index (optional)

In some cases, you’ll want to modify how Apache serves files when a directory is requested. Currently, if a user requests a directory from the server, Apache will first look for a file called index.html. We want to tell the web server to prefer PHP files over others, to make Apache look for a file .php index first. If you do not, an index file placed at the root .html the application document will always take precedence over a file .php index.

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


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

It will look

like this: <IfModule mod_dir.c> DirectoryIndex index.html index.cgi index.php index.xhtml index.htm </IfModule>

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

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

When you are finished, save and close the file by pressing CTRL+X. Confirm the save by typing Y, and then press ENTER to verify the save location of the file.

After this, restart the Apache web server so that the changes are recognized. You can do this with the following command

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

  1. sudo systemctl status

apache2 Sample Output● apache2.service – The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; provider preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─

  1. apache2-systemd.conf

Active: active (running) since Thu 2021-07-15 09:


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: The fully qualified domain name of the server could not be reliably determined, using Set the ‘ServerName’ di Jul 15 09:22:59 ubuntu1804 systemd[1]: Apache HTTP server started.

Press Q to exit this state output.

Installing PHP extensions (optional)

To extend the functionality of PHP, you have the option to install some additional modules. To see the options available for PHP modules and libraries, pipe apt search results into less, a pager that allows you to scroll through the output of other commands:

  1. apt search php- | less

Use the arrow keys to scroll up and down, and press Q to exit


The results are all optional components that you can install. It will give you a brief description for each:

bandwidthd-pgsql/bionic 2.0.1+cvs20090917-10ubuntu1 amd64 Track TCP/IP usage and create html files with Bluefish/Bionic 2.2.10-1 graphics AMD Advanced Gtk + text editor for web and software development Cacti / Bionic 1.1.38 + DS1-1 All web interface to graph 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 similar to PHP Compression and file 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 transition package for kdevelop-php kdevelop-php-docs-l10n/bionic 5.2.1-1ubuntu2 all transition package for kdevelop-php-l10n … : For more

information about what each module does, you can search the internet to learn more about them. Alternatively, look at the long description of the package by typing

: apt show package_name There will

be a lot of output, with a field called Description that will have a longer explanation of the functionality the module provides


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


  1. apt show php-cli

Along with a lot of other information, you’ll find something that looks like this:

Output… Description: Command line interpreter for PHP scripting language (default) This package provides the /usr/bin/php shell, 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 suitable for web development and can be embedded in HTML. . This package is a dependency package, which depends on the default PHP version of Ubuntu (currently 7.2). …

If, after investigating, you decide you want to install a package, you can do so using the apt install command as you have been doing for the other software.

If you decided php-cli is

something 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 one, separated by a space, by following the

apt install command, like this:

  1. sudo apt install
  1. package1package2…

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

Step 4 — Configuring a Virtual Host (recommended


When using Apache web server, you can use virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. We’ll set up a domain called your_domain, but you need to replace it with your own domain name. For more information on setting up a domain name with DigitalOcean, see our Introduction to DigitalOcean DNS.

Apache in Ubuntu 18.04 has a server block 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 host multiple sites. Instead of modifying /var/www/html, let’s create a directory structure within /var/www for your_domain site, leaving /var/www/html instead as the default directory to be served if a client request doesn’t match any other site.

Create the directory


your_domain as follows: sudo

  1. mkdir


Next, assign the directory property with the $USER environment variable, which refers to the current registered user


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

The permissions of your web root directory must be correct if you have not modified its umask value, but you can make sure by typing


  1. sudo chmod -R 755 /var/www/your_domain

Next, create a sample index.html page using nano or your favorite editor: nano


Inside, add the following example HTML:

<html> <head> <title>Welcome to Your_domain!</title> <

  1. /

head> <body> <h1>Success! The your_domain server block is working!</h1> </body> </html>

Save and close the file when you are done


For Apache to serve this content, you need to create a virtual host file with the correct directives. Instead of modifying

the default configuration file located in /etc/apache2/sites-available/000-default.conf directly, let’s make a new one in /etc/apache2/sites-available/your_domain.conf:

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

Paste the following configuration block, which is similar to the default, but updated for our new directory and domain name:

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

Note that we have updated DocumentRoot to our new directory and ServerAdmin to an email that your_domain The site administrator can access it. We’ve also added two directives: ServerName, which sets the base domain that must match this virtual host definition, and ServerAlias, which sets other names that must match as if they were the base name.

Save and close the file when you are finished.

Let’s enable the file with

the a2ensite tool: sudo a2ensite your_domain.conf Disable the default site defined in 000-default.conf: sudo

  1. a2dissite 000-default.conf

Next, let’s test the configuration errors

: sudo apache2ctl configtest

You should see the following output

: OutputSyntax OK

Restart Apache to deploy your changes:

  1. sudo systemctl restart apache2

Apache should now be serving your domain name. You can test this by navigating to http://your_domain, where you should see something like this:

With that, your virtual host is fully configured. However, before making any further changes or deploying an application, it would be helpful to proactively test your PHP configuration in case there are any issues that need to be addressed.

Step 5 — Testing PHP processing on your web server

To test that your system is properly configured for PHP, create a PHP script called info.php. For Apache to find this file and serve it properly, it must be saved in your web root directory.

Create the file in

the web root you created in the previous step by running:

  1. sudo nano /var/www/your_domain/info.php

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

<?php phpinfo();

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

You can now test if your web server is capable of correctly displaying the content generated by this PHP script. To test this, visit this page in your web browser. You will need the public IP address or domain name of your server again.


address you’ll want to visit is

: http://your_domain/info.php The page

you arrive at should look like this:

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

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

You probably want to delete this file after this test, as it might actually provide information about the server to unauthorized users. To do this, run the following command:

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

You can always re-create this page if you need to access the information again later



Now that you have a LAMP stack installed, you have plenty of options on what to do next. You have installed a platform that will allow you to install most types of websites and web software on your server.

As an immediate next step, you need to make sure that connections to your web server are secure, serving them over HTTPS. Follow our guide on how to secure Apache with Let’s Encrypt to protect your site with a free TLS/SSL certificate.

Some other popular options are:

  • Install WordPress, the most popular content management system on the internet
  • .

  • Configure PHPMyAdmin to help manage your MySQL databases from a web browser
  • .

  • Learn how to use SFTP to transfer files to and from your server.

Contact US