Installing Apache, PHP, MariaDB or MySQL on Ubuntu (LAMP stack)

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, avrg: 5.00)

The LAMP (Linux, Apache, MySQL/MariaDB & PHP) is a group software package commonly used for web page or web application, NGINX is a web server, MySQL is a Database for storing data in the backend. PHP (Hypertext Preprocessor) is an Open Source server-side scripting language used for Web development.

Apache web server is designed to have the ability to host one or more HTTP-based websites. Notable features include the ability to support multiple programming languages.

Following below steps tutorial for basic installation and setup guides

Step 1: Update Ubuntu Package

To get the latest version of Ubuntu package use theapt by typing the command below:

sudo apt update&&upgrade

Step 2: Install Apache 2 as HTTP Server

Now we are going to install Apache 2 stable version that available in Ubuntu repositories, to do this type the following command

sudo apt install apache2

Once Apache 2 already installed, to check and verify the Apache service status type the command below

sudo service apache2 status

If it is running and working properly you will see the output Apche active (running) like below

● 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 Sat 2018-03-31 08:44:04 CEST; 15min ago
Main PID: 5727 (apache2)
Tasks: 55 (limit: 4915)
CGroup: /system.slice/apache2.service
├─5727 /usr/sbin/apache2 -k start
├─5728 /usr/sbin/apache2 -k start
└─5729 /usr/sbin/apache2 -k start

Mar 31 08:44:04 ubuntu1804 systemd[1]: Starting The Apache HTTP Server...
Mar 31 08:44:04 ubuntu1804 apachectl[5675]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. 
Mar 31 08:44:04 ubuntu1804 systemd[1]: Started The Apache HTTP Server.

To exit Apache service status just press q on the keyboard.

Apache service will start automatically. The following commands can be used to stop, start and enable Apache service.

sudo systemctl stop apache2.service
sudo systemctl start apache2.service
sudo systemctl enable apache2.service

Step 3: Configure Module Apache 2

To reduce latency for users on hosted site it’s recommended setting KeepAlive to allow Apache to be better utilize server-side memory. It will make a website faster it’s support for the server has enough memory and allowing Apache to reuse or new connections to every request.

Apche config file was located in directory /etc/apache2/apache2.conf and to edit a file use nano editor, use the following command

sudo nano /etc/apache2/apache2.conf

Apache config file and adjust setting for KeepAlive value

KeepAlive On
MaxKeepAliveRequests 50
KeepAliveTimeout 5

MPM (multi-processing module) is the prefork module. mpm_prefork it is compatible with most systems. Open the mpm_prefork.conf file located in /etc/apache2/mods-available/mpm_prefork.conf to edit a file use the following command

sudo nano /etc/apache2/mods-available/mpm_prefork.conf

Let’s see the MPM module and the following suggested value

<IfModule mpm_prefork_module>
        StartServers            4
        MinSpareServers         3
        MaxSpareServers         40
        MaxRequestWorkers       200
        MaxConnectionsPerChild  10000
</IfModule>

To enable and disable MPM module use the following comand

sudo a2dismod mpm_event
sudo a2enmod mpm_prefork

Changes made in the Apache configuration file will not be applied until the command to Restart

sudo systemctl restart apache2

Step 4: Configuration the Firewall with UFW

UFW (Uncomplicated Firewall) is an Iptable interface to easily configure a firewall on your system. If it does not yet enable, it’s recommended to enable and setup the rule for Apache

For the first, we have to add rule for SSH, let’s se the command line below

sudo ufw allow OpenSSH

Add the rule receive HTTP to Nginx

sudo ufw allow 'Apache Full'

Then you will see on terminal

Rule added
Rule added (v6)'

Now enable ufw for Firewall.

sudo ufw enable

If prompted just pres Y to accept and continue and to check UFW status type the command below

sudo ufw status

You will see the output UFW active (running) like below

Status: active

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

Step 5: Testing Apache on the Browser

Apache web server now is ready on Ubuntu, now you may go to your web browser and visit your domain or IP. If you have not configured domain name yet and don’t know your IP, use the following command find out

sudo ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'

If everything is OK you will be presented on your browser with the default Apache landing page as below


You may edit above default landing page. The file was located in the document root directory /var/www/html. If you want to edit you could use nano editor and use the following command

sudo nano /var/www/html/index.html

To save and close nano, press Ctrl/Cmd + X and then press Y and ENTER to save changes and Reload Apache service by using the following command

sudo systemctl restart apache2

Go back to your browser and refresh….. see the changed…..!!!!


Step 6: Install MariaDB or MySQL

There two options using MariaDB or MySQL Database, please choose one that you prefer with. To install MariaDB or MySQL on Ubuntu server let’s following steps:

Installing MariaDB

MariaDB is a fork of MySQL, the database structure and indexes of MariaDB are the same as MySQL. This allows you to switch from MySQL to MariaDB without having to alter your applications since the data and data structures will not need to change.

To install MariaDB packages from the MariaDB repository use the following command

sudo apt-get install mariadb-server mariadb-client

Press Y and ENTER when prompted on installing process
MariaDB service will start automatically, the commands below can be used to stop, start and enable MariaDB service.

sudo systemctl stop mariadb.service
sudo systemctl start mariadb.service
sudo systemctl enable mariadb.service

To check and verify MariaDB is working, use the command below

sudo systemctl status mariadb

The output MariaDB active (running) like below

● mariadb.service - MariaDB 10.3.8 database server
Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/mariadb.service.d
        └─migrated-from-my.cnf-settings.conf
Active: active (running) since Sun 2018-07-29 19:36:30 UTC; 56s ago
    Docs: man:mysqld(8)
        https://mariadb.com/kb/en/library/systemd/
Main PID: 16417 (mysqld)
Status: "Taking your SQL requests now..."
    Tasks: 31 (limit: 507)
CGroup: /system.slice/mariadb.service
        └─16417 /usr/sbin/mysqld

Press q on the keyboard to exit service status

To check MariaDB server version use the command below

mysql -V

If you already installed MariaDB server above, you should ignore below Installation MySQL and jump to step 7


Installing MySQL

MySQL is an open-source relational database management system (RDBMS). Just like all other relational databases, MySQL uses tables, constraints, triggers, roles, stored procedures and views as the core components

To install MySQL packages from the MySQL repository use the following command

sudo apt update && sudo apt install mysql-server

Press Y and ENTER when prompted on installing process

MySQL service will start automatically, the commands below can be used to stop, and start MySQL service.

sudo service mysql stop
sudo service mysql start

To check and verify MySQL is working, use the command below

sudo service mysql status

The output MySQL active (running) like below

● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since since Wed 2018-05-09 21:10:24 UTC; 16s ago
 Main PID: 30545 (mysqld)
    Tasks: 27 (limit: 1153)
   CGroup: /system.slice/mysql.service
           └─30545 /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid

Press q on the keyboard to exit service status

To check MySQL server version use the command below

mysql -V

Step 7: Configuration MySQL Security

To improve MySQL security it’s recommended to enable mysql_secure_installation. These packed to create a root password and disallow remotely root access. To install packages use the following ways

sudo mysql_secure_installation

On installation process will prompt and to be asked the validate password plugin, it can be used for password strength checking

  • Enter current password for root (enter for none): Just press the Enter
  • Set root password? [Y/n]: Y
  • New password: Enter password
  • Re-enter new password: Repeat password
  • Remove anonymous users? [Y/n]: Y
  • Disallow root login remotely? [Y/n]: Y
  • Remove test database and access to it? [Y/n]:  Y
  • Reload privilege tables now? [Y/n]:  Y

If you didn’t create a root password, you have to generate a strong password

For testing MySQL server and run the following command.

sudo mysqladmin -p -u root version

Enter the MySQL root password you created before and see the following output

mysqladmin  Ver 8.42 Distrib 5.7.22, for Linux on x86_64
Copyright (c) 2000, 2018, 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.

Server version          5.7.22-0ubuntu18.04.1
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/run/mysqld/mysqld.sock
Uptime:                 4 min 28 sec

Threads: 1  Questions: 15  Slow queries: 0  Opens: 113  Flush tables: 1  Open tables: 106  Queries per second avg: 0.055

Configured MySQL server on Ubuntu now is successful


Step 8: Install PHP-FPM

Let’s install PHP with Latest version package on Ubuntu. Below there are two commands will update the package and get the package to install. Once installation there are questions just pressing Yand ENTERto continue.

sudo apt update && sudo apt install php-fpm

Let’s install PHP Modules package, use the following command

sudo apt install php libapache2-mod-php php-common php-mbstring php-xmlrpc php-soap php-gd php-xml php-intl php-mysql php-cli php-zip php-curl

After installing, now check PHP version.

php --version

The output PHP version (running) like below

PHP 7.2.3-1ubuntu1 (cli) (built: Mar 14 2018 22:03:58) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.2.3-1ubuntu1, Copyright (c) 1999-2018, by Zend Technologies

Step 9: Modify the PHP Configuration File (php.ini)

The php.ini file is a default configuration file that read on PHP starts up. If you want to change the PHP settings on Ubuntu, php.ini file is an easy and most effective way to do it. Follow the below steps to modify the PHP configuration file (php.ini) using the command line on Ubuntu.

Edit the configuration file located in /etc/php/7.2/apache2/php.ini to enable more descriptive errors, logging, and better performance. The following modifications provide a good starting point The version number determines the location of PHP default configuration file. For PHP 7.2, the location is as shown below. Replace the version number above with the version of PHP installed.

sudo nano /etc/php/7.2/apache2/php.ini

Find or you can use Cmd/Ctrl W to search and replace it as the following

error_reporting = E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR
max_input_time = 30
error_log = /var/log/php/error.log
file_uploads = On
allow_url_fopen = On
memory_limit = 256M
upload_max_filesize = 100M
max_execution_time = 360
date.timezone = America/Los_Angeles

Create the log directory for PHP and give ownership to the Apache system user

sudo mkdir /var/log/php
sudo chown www-data /var/log/php

Restart Apache

sudo systemctl restart apache2

Step 10: Configuration Virtual Hosts on Apache

If you wish to host multiple or one sites/domain, the way should to do is setting up virtual hosts. There are several ways to set up virtual hosts on Apache. The recommended method is the following steps outline will make things a lot easier for you.

The Virtual Host files are located in /etc/apache2/sites-available/  to allow web server respond to various domain requests.

To create a configuration file, copy default file new file with the example.com (replace it with your domain name)

sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.conf

Open the new configuration file example.com with nano editor use the following command

sudo nano /etc/apache2/sites-available/example.com.conf

Uncomment the ServerNameoption and update it with your domain. Enter the document root path and log directories as shown below, and add Directory  block before <VirtualHost>:

<Directory /var/www/html/example.com/public_html>
        Require all granted
</Directory>
<VirtualHost *:80>
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/example.com/public_html

        ErrorLog /var/www/example.com/logs/error.log
        CustomLog /var/www/example.com/logs/access.log combined

</VirtualHost>

Replace example.com (red mark) and  press Ctrl/Cmd + X and then press Y and ENTER to save changes and close nano

Create new directories referenced above in the directory /var/www/

sudo mkdir -p /var/www/example.com/public_html

Change ownership to the current user $(whoami) for directory access.

sudo chown -R $(whoami):$(whoami) /var/www/example.com/public_html

Change the permission for /var/www and its contents.

sudo chmod -R 755 /var/www

Step 11: Create Testing PHP File

To verify above configuration is working on the Apache server, let’s a create a new PHP file whit a name test.php into directory /var/www/example.com/

Create a file using nano editor use the following command line

sudo nano /var/www/example.com/info.php

Copy and paste the following code

<?php
echo phpinfo();

Press Ctrl/Cmd + X, then press Y and ENTER to save and close


Step 12: Enable Virtual Hosts

To enable virtual host file use a2ensite tool to link file from the sites-available directory to the sites-enabled directory:

sudo a2ensite example.com

To minimize security risks, disable the default virtual host (optional)

sudo a2dissite 000-default.conf

Changes made in the Apache configuration file will not be applied until the command to Restart

sudo systemctl reload apache2

You can now view this page in your web browser by visiting your server’s domain name or public IP address followed by /test.phphttp://your_domain_or_IP/info.php …Congrats..!!


If this tutorial could help you, please rate above Star button rating and share to help others find it! Feel free to leave a comment below.

Recommended For You

Axfon

About the Author: Axfon

Team committed to share our IT skills and experience through our website which may assist to formulate a task easy