---
title: How to Install Apache, MySQL, PHP (LAMP Stack) on Ubuntu 20.04
url: https://docs.vultr.com/how-to-install-apache-mysql-php-lamp-stack-on-ubuntu-2004
description: Learn how to install and configure the LAMP stack (Linux, Apache, MySQL, PHP) on Ubuntu 20.04 with our step-by-step guide for beginners and system administrators.
publish_date: 2025-05-07T12:54:53.392000Z
last_updated: 2025-05-07T13:56:07.418000Z
author: Aashish Chaurasiya
header_image: https://docs.vultr.com/public/doc-assets/2195/94e7b308-6238-46b3-9835-f193a99d0709.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

The LAMP stack—Linux, Apache, MySQL, and PHP—is a collection of open-source tools used to develop and serve dynamic web applications. In this setup:

- **Linux** acts as the operating system,
- **Apache** serves web content,
- **MySQL** manages databases, and
- **PHP** handles dynamic content processing.

This article explains how to install and configure the LAMP stack on Ubuntu 20.04 to host web applications on your server.

## Prerequisites

Before you begin:

* Have an [Ubuntu 20.04 server](https://www.vultr.com/servers/ubuntu/).

* Access the server using SSH as a non-root user with sudo privileges.

* [Set up a new A record for your domain that points to the server IP address](https://docs.vultr.com/introduction-to-vultr-dns).

* [Update the server](https://docs.vultr.com/how-to-update-a-vultr-cloud-server#how-to-update-debian-&-ubuntu).

## Install Apache

The latest version of Apache is available in Ubuntu 20.04’s default APT repositories. Follow the steps below to update the package index and install Apache.

1. Update the server's package index.

    ```console
    $ sudo apt update
    ```

1. Install Apache.

    ```console
    $ sudo apt install apache2 -y
    ```

1. Start the Apache service.

    ```console
    $ sudo systemctl start apache2
    ```

1. Enable the Apache service to start automatically at boot time.

    ```console
    $ sudo systemctl enable apache2
    ```

1. Verify that the Apache server service is running.

    ```console
    $ sudo systemctl status apache2
    ```

    Output:

    ```
    ● apache2.service - The Apache HTTP Server
         Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
         Active: active (running) since Sun 2025-04-06 10:56:28 UTC; 20s ago
           Docs: https://httpd.apache.org/docs/2.4/
       Main PID: 2622 (apache2)
          Tasks: 55 (limit: 9415)
         Memory: 6.9M
         CGroup: /system.slice/apache2.service
                 ├─2622 /usr/sbin/apache2 -k start
                 ├─2623 /usr/sbin/apache2 -k start
                 └─2624 /usr/sbin/apache2 -k start
    ```

1. Allow connections to the HTTP port `80` through the default firewall configuration.

    ```console
    $ sudo ufw allow 80/tcp
    ```

1. Access your domain or server IP using a web browser such as Chrome and verify that the default Apache web page displays.

    ```
    http://SERVER-IP
    ```

    ![Test access to the default Apache web page](https://docs.vultr.com/public/doc-assets/1864/647389e165e84af7.png)

## Install MySQL

MySQL serves as the database backend in the LAMP stack, but you can also substitute it with MariaDB if needed. The latest MySQL package is available in Ubuntu 20.04’s default repositories. Follow the steps below to install MySQL using the APT package manager.

1. Install the MySQL database server package.

    ```console
    $ sudo apt install -y mysql-server
    ```

1. Enable the MySQL service to start automatically at boot time.

    ```console
    $ sudo systemctl enable mysql
    ```

1. Start the MySQL service.

    ```console
    $ sudo systemctl start mysql
    ```

1. View the MySQL service status and verify that it's running.

    ```console
    $ sudo systemctl status mysql
    ```

    Output:

    ```
    ● mysql.service - MySQL Community Server
         Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
         Active: active (running) since Sun 2025-04-06 10:58:51 UTC; 41s ago
       Main PID: 17189 (mysqld)
         Status: "Server is operational"
         Tasks: 38 (limit: 9415)
         Memory: 364.8M
         CGroup: /system.slice/mysql.service
                 └─17189 /usr/sbin/mysqld
    ```

    Based on the `active (running)` result in the above output, the MySQL database server is active and running on your server.

1. Run the MySQL secure installation script to disable insecure defaults and enable authentication on your database server.

    ```console
    $ sudo mysql_secure_installation
    ```

    During the MySQL installation, you’ll be prompted with several options. Respond as follows to configure your server:

    * **VALIDATE PASSWORD**: Enter `y` to enable password strength checks.
    * **Password strength policy**: Enter `2` to enforce multi-character passwords.
    * **Remove anonymous users**: Enter `y` to remove anonymous users.
    * **Disallow root login remotely**: Enter `y` to disable remote access for the `root` user.
    * **Remove test database**: Enter `y` to delete the default MySQL test database.
    * **Reload privileges tables now**: Enter `y` to reload the MySQL privilege tables and apply your changes.

    Your output should look like the one below when successful:

    ```
    Success.

    All done! 
    ```

1. Log in to the MySQL console as the `root` user.

    ```console
    $ sudo mysql
    ```

1. Alter the `root` database user to use a new strong password. Replace `Strong@@password123` with your desired password.

    ```sql
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Strong@@password123';
    ```

    Replace `password` with a strong password.

1. Flush the MySQL privileges table to apply the new user changes.

    ```sql
    mysql> FLUSH PRIVILEGES;
    ```

1. Exit the MySQL console.

    ```sql
    mysql> EXIT;
    ```

1. Log in to the MySQL console again as the `root` user and enter the password you set earlier when prompted.

    ```console
    $ mysql -u root -p
    ```

1. Create a new sample database `content_database`.

    ```sql
    mysql> CREATE database content_database;
    ```

1. View all databases and verify that the new database is available.

    ```sql
    mysql> SHOW DATABASES;
    ```

    Output:

    ```
    +--------------------+
    | Database           |
    +--------------------+
    | information_schema |
    | content_database   |
    | mysql              |
    | performance_schema |
    | sys                |
    +--------------------+
    5 rows in set (0.01 sec)
    ```

1. Create a new MySQL user such as `dbadmin` with a strong password. Replace `Strong@@password123` with your desired password.

    ```sql
    mysql> CREATE USER 'dbadmin'@'localhost' IDENTIFIED BY 'Strong@@password123';
    ```

1. Grant the user full privileges to your sample database `content_database`.

    ```sql
    mysql> GRANT ALL PRIVILEGES ON content_database.* TO 'dbadmin'@'localhost';
    ```

1. Flush the MySQL privileges table to apply changes.

    ```sql
    mysql> FLUSH PRIVILEGES;
    ```

1. Exit the MySQL shell.

    ```sql
    mysql> EXIT;
    ```

## Install PHP and Configure PHP-FPM

PHP is a key component of the LAMP stack, responsible for processing dynamic content and interacting with the MySQL database. PHP-FPM (FastCGI Process Manager) optimizes performance by managing connections to PHP using pools of worker processes.

1. Install PHP and the PHP-FPM module.

    ```console
    $ sudo apt install -y php php-fpm
    ```

1. Install common PHP extensions on your server.

    ```console
    $ sudo apt install -y php-mysql php-opcache php-cli libapache2-mod-php
    ```

    The above command installs the following PHP modules:

    * **php-mysql**: Allows PHP to connect and interact with the MySQL database server.
    * **libapache2-mod-php**: Enables Apache to process and run PHP scripts.
    * **php-opcache**: Caches precompiled PHP scripts in memory for faster execution.
    * **php-cli**: Allows access to PHP via the command line on your server.

1. View the installed PHP version on your server.

    ```console
    $ php -v
    ```

    Output:

    ```
    PHP 7.4.3-4ubuntu2.29 (cli) (built: Mar 25 2025 18:57:03) ( NTS )
    Copyright (c) The PHP Group
    Zend Engine v3.4.0, Copyright (c) Zend Technologies
        with Zend OPcache v7.4.3-4ubuntu2.29, Copyright (c), by Zend Technologies
    ```

1. Start the PHP-FPM service based on the installed PHP version on your server. For example, `PHP 7.4`.

    ```console
    $ sudo systemctl start php7.4-fpm
    ```

1. Enable PHP-FPM to start at boot time.

    ```console
    $ sudo systemctl enable php7.4-fpm
    ```

1. View the PHP-FPM service status and verify that it's running.

    ```console
    $ sudo systemctl status php7.4-fpm
    ```

    Output:

    ```
    ● php7.4-fpm.service - The PHP 7.4 FastCGI Process Manager
         Loaded: loaded (/lib/systemd/system/php7.4-fpm.service; enabled; vendor preset: enabled)
         Active: active (running) since Sun 2025-04-06 11:11:45 UTC; 10min ago
           Docs: man:php-fpm7.4(8)
        Process: 27868 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.4/fpm/pool.d/www.conf 74 (code=exited, status=0/SUCCESS)
       Main PID: 27851 (php-fpm7.4)
         Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
          Tasks: 3 (limit: 9415)
         Memory: 7.3M
         CGroup: /system.slice/php7.4-fpm.service
                 ├─27851 php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)
                 ├─27866 php-fpm: pool www
                 └─27867 php-fpm: pool www
    ```

### Configure PHP-FPM

PHP-FPM optimizes PHP application performance by managing pools of worker processes, depending on your server’s memory. Follow the steps below to configure PHP-FPM to work with the Apache web server and adjust the default pool settings for better resource management.

1. Enable the required Apache modules.

    ```console
    $ sudo a2enmod proxy_fcgi setenvif
    ```

    The above command enables the following modules on your web server:

    * `proxy_fcgi`: Enables Apache to work as a proxy with PHP-FPM.
    * `setenvif`: Sets the necessary environment variables to enable connections between Apache and PHP-FPM.

1. Enable the default PHP-FPM configuration.

    ```console
    $ sudo a2enconf php7.4-fpm
    ```

1. Restart the Apache web server to apply the changes.

    ```console
    $ sudo systemctl restart apache2
    ```

1. Switch to the PHP-FPM pool configurations directory.

    ```console
    $ cd /etc/php/7.4/fpm/pool.d/
    ```

1. Open the default `www.conf` PHP-FPM pool configuration.

    ```console
    $ sudo nano /etc/php/7.4/fpm/pool.d/www.conf
    ```

    Verify that the default PHP-FPM pool name `www`.

    ```ini
    [www]
    ```

    Find and verify the following directives are set to `www-data` to enable PHP-FPM to use the default web server user profile.

    ```ini
    user = www-data
    group = www-data
    listen.owner = www-data
    listen.group = www-data
    ```

    * Find the following pool configurations and modify them to suite your desired server needs:

    - **`pm`**: Defines the process manager. Set to `dynamic` to allow PHP child processes to adjust based on server demand.
    - **`pm.start_servers`**: Sets the number of PHP child processes to create at startup. Default value: `2`.
    - **`pm.max_children`**: Defines the maximum number of PHP child processes that can run simultaneously. Default value: `5`.
    - **`pm.min_spare_servers`**: Specifies the minimum number of idle PHP child processes. Default value: `1`.
    - **`pm.max_spare_servers`**: Specifies the maximum number of idle PHP child processes. Default value: `3`.
    - **`pm.max_requests`**: Limits the number of requests a PHP child process can handle before being recycled to ensure optimal performance.

    Save and close the file.

1. Restart the PHP-FPM service to apply your configuration changes.

    ```console
    $ sudo systemctl restart php7.4-fpm
    ```

## Configure Apache with PHP-FPM

Apache communicates with PHP-FPM through the `mod_proxy_fcgi` module, either using a UNIX socket or the default TCP port `9000`, depending on your PHP-FPM pool configuration. Follow these steps to set up a new Apache virtual host and connect it to PHP-FPM using the UNIX socket.

1. Remove the default Apache virtual host configuration files.

    ```console
    $ sudo rm -rf /etc/apache2/sites-enabled/000-default.conf && sudo rm -rf /etc/apache2/sites-available/000-default.conf
    ```

1. Create a new Apache virtual host configuration file. For example, `app.example.com.conf`.

    ```console
    $ sudo nano /etc/apache2/sites-available/app.example.com.conf
    ```

1. Add the following configurations to the file. Replace `app.example.com` with your actual domain.

    ```ini
    <VirtualHost *:80>
    ServerAdmin webmaster@app.example.com
    ServerName app.example.com
    DocumentRoot /var/www/html/app.example.com

    <Directory /var/www/html/app.example.com>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php$>
       SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/app.example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/app.example.com_access.log combined
    </VirtualHost>
    ```

    Save and close the file.

    The above sets up a new Apache virtual host that listens for incoming traffic on port `80` and serves content for the `app.example.com` domain. PHP file requests are forwarded to the PHP-FPM process via the `/var/run/php/php7.4-fpm.sock` UNIX socket. The key components of this configuration include:

    - **`<VirtualHost *:80>`**: Configures the virtual host to listen on port `80`.
    - **`<Directory /var/www/html/app.example.com>`**: Sets the root directory for web application files.
    - **`<FilesMatch \.php$>`**: Forwards PHP file requests to the PHP-FPM socket using the FastCGI protocol.
    - **`ErrorLog`, `CustomLog`**: Defines custom paths for the virtual host's error and access logs.

1. Enable the new Apache virtual host configuration.

    ```console
    $ sudo a2ensite app.example.com.conf
    ```

1. Test the Apache configuration for syntax errors.

    ```console
    $ sudo apache2ctl configtest
    ```

    Output:

    ```
    Syntax OK
    ```

1. Create the virtual host web root directory `/var/www/html/app.example.com` defined in your configuration.

    ```console
    $ sudo mkdir -p /var/www/html/app.example.com
    ```

1. Create a new sample PHP file `info.php`.

    ```console
    $ sudo nano /var/www/html/app.example.com/info.php
    ```

1. Add the following contents to the file.

    ```php
    <?php
    phpinfo();
    ?>
    ```

    Save and close the file.

    The above application code displays information about the PHP version and installed modules on your server when accessed in a web browser.

1. Restart Apache to apply your configuration changes.

    ```console
    $ sudo systemctl restart apache2
    ```

1. Access your domain using a web browser such as Chrome and append the `/info.php` path to verify that your PHP application information displays.

    ```
    http://app.example.com/info.php
    ```

    ![Screenshot of PHP 7.4 information web page](https://i.postimg.cc/FFcL9mN8/Screenshot-2025-04-06-at-9-32-45-PM.png)

## Secure the server

Uncomplicated Firewall (UFW) is enabled by default on Vultr Ubuntu 20.04 servers. The Apache web server uses the default HTTP port `80` to serve dynamic web applications, while other LAMP stack components, such as MySQL (`3306`) and PHP-FPM (`9000`), use internal TCP ports. Follow the steps below to configure UFW to allow connections on port `80` for the web server and set up trusted SSL certificates to enable HTTPS on port `443`.

### Configure the Firewall

1. View the default firewall status and verify that it's active.

    ```console
    $ sudo ufw status
    ```

    Output:

    ```
    Status: active
    ...
    ```

1. View the available UFW application profiles and verify that the Apache profile is available.

    ```console
    $ sudo ufw app list
    ```

    Output:

    ```
    Apache
    Apache Full
    Apache Secure
    OpenSSH
    ```

1. Allow the `Apache Full` profile to enable HTTP and HTTPS connections on the server.

    ```console
    $ sudo ufw allow "Apache Full"
    ```

1. Reload the firewall rules to apply changes.

    ```console
    $ sudo ufw reload
    ```

1. View the UFW status and verify that the Apache connection rules are available in the firewall table.

    ```console
    $ sudo ufw status
    ```

    Output:

    ```
    To                         Action      From
    --                         ------      ----
    1022/tcp                   ALLOW       Anywhere
    Apache Full                ALLOW       Anywhere
    1022/tcp (v6)              ALLOW       Anywhere (v6)
    Apache Full (v6)           ALLOW       Anywhere (v6)
    ```

### Generate Trusted Let's Encrypt SSL Certificates

1. Install the Certbot Let's Encrypt client tool using Snap.

    ```console
    $ sudo snap install certbot --classic
    ```

1. Request a new SSL certificate for your domain. Replace `app.example.com` with your actual domain and `admin@example.com` with your email.

    ```console
    $ sudo certbot --apache -d app.example.com -m admin@example.com --agree-tos
    ```

    Output:

    ```
    Requesting a certificate for app.example.com

    Successfully received certificate.
    Certificate is saved at: /etc/letsencrypt/live/app.example.com/fullchain.pem
    Key is saved at:         /etc/letsencrypt/live/app.example.com/privkey.pem
    This certificate expires on 2025-07-05.
    These files will be updated when the certificate renews.
    Certbot has set up a scheduled task to automatically renew this certificate in the background.

    Deploying certificate
    Successfully deployed certificate for app.example.com to /etc/apache2/sites-available/000-default-le-ssl.conf
    Congratulations! You have successfully enabled HTTPS on https://app.example.com
    ```

1. Test the Certbot automatic SSL certificate renewal process.

    ```console
    $ sudo certbot renew --dry-run
    ```

1. Restart the Apache web server to apply your SSL configuration changes.

    ```console
    $ sudo systemctl restart apache2
    ```

## Test the LAMP Stack Installation

Follow the steps below to create a new sample table in your existing `content_database` MySQL database. This table will connect with your PHP application and display the message `Hello World! Greetings from Vultr` when accessed through a web browser.

1. Log in to the MySQL console using the sample database user `dbadmin` you created earlier.

    ```console
    $ mysql -u dbadmin -p
    ```

    Enter the `dbadmin` user password when prompted to access the MySQL console.

1. Switch to the sample database `content_database`.

    ```sql
    mysql> USE content_database;
    ```

1. Create a new sample table `messages` with two columns, `content_id` and `content` to store your data.

    ```sql
    mysql> CREATE TABLE IF NOT EXISTS messages (
           content_id INT AUTO_INCREMENT PRIMARY KEY,
           content VARCHAR(255) NOT NULL
          );
    ```

    The above SQL query creates a new table with the following specifications:

    * `content_id`: Contains numeric values and automatically increments unique data on each new row.
    * `content`: Holds mixed content data with up to `255` characters.

1. Insert new data to the `messages` table. For example, add a new `Hello World! Greetings from Vultr` string to the `content` column.

    ```sql
    mysql> INSERT INTO messages (content) VALUES ('Hello World! Greetings from Vultr');
    ```

1. View all table data to verify that the new string is added to the column.

    ```sql
    mysql> SELECT * from messages;
    ```

    Output:

    ```
    +----+------------------------------------------+
    | content_id | content                           |
    +------------+-----------------------------------+
    |  1         | Hello World! Greetings from Vultr |
    +------------+-----------------------------------+
    1 row in set (0.00 sec)
    ```

1. Exit the MySQL console.

    ```sql
    mysql> EXIT;
    ```

1. Create a new sample PHP application file `setup.php` in your web root directory `/var/www/html/app.example.com`.

    ```console
    $ sudo nano /var/www/html/app.example.com/setup.php
    ```

1. Add the following contents to the file.

    ``` php
    <?php
    $hostname = "localhost";
    $username = "dbadmin";
    $password = "Strong@@password123";
    $dbname = "content_database";

    // Establish Connection
    $conn = new mysqli($hostname, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection Failed: " . $conn->connect_error);
    }

    $sql = "SELECT content FROM messages";
    $result = $conn->query($sql);

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        echo "<h2 style='color: blue; text-align: center; margin-bottom: 15px;'>"
            . htmlspecialchars($row["content"]) . "</h2>";
    } else {
        echo "<h1>No records found.</h1>";
    }

    $conn->close();
    ?>
    ```

    Save and close the file.

    The PHP application code above connects to the `content_database` MySQL database and retrieves data from the `content` column in the `messages` table. If no records are found in the database, it will display a `No records found` message. If the connection to the database server fails, it will show a `Connection Failed` message.


1. Grant the Apache user `www-data` full privileges to your web root directory.

    ```console
    $ sudo chown -R www-data:www-data /var/www/html/app.example.com/
    ```

1. Access your domain using the `/setup.php` path in your web browser to verify that your PHP application displays the `Hello World! Greetings from Vultr` string content from your MySQL database.

    ```
    https://app.example.com/setup.php
    ```

    ![A Greetings From Vultr PHP application](https://i.postimg.cc/QtFZ6Nrg/image.png)

## Conclusion

You have successfully installed and configured Apache, MySQL, and PHP (LAMP stack) on your Ubuntu 20.04 server. Additionally, you created sample dynamic applications to test the interaction between all LAMP stack components and ensured secure execution on your server.
