Tutorial

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

Updated on November 30, 2021
English
How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu 16.04
Not using Ubuntu 16.04?Choose a different version or distribution.
Ubuntu 16.04

Introduction

The LAMP stack is a set of open source software that is typically installed together to enable a server to host dynamic websites and web apps. 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, we’ll get a LAMP stack installed on an Ubuntu 16.04 server. Ubuntu will fulfill our first requirement: a Linux operating system.

Prerequisites

Before you begin with this guide, you should have a separate, non-root user account with sudo privileges set up on your server. You can learn how to do this by completing steps 1–4 in our initial server setup for Ubuntu 16.04 tutorial.

Step 1 — Installing Apache and Adjusting the Firewall

The Apache web server is among the most popular web servers in the world. It’s well-documented, and has been in wide use for much of the history of the web, which makes it a great default choice for hosting a website.

We can install Apache easily using Ubuntu’s package manager, apt. A package manager allows us to install most software pain-free from a repository maintained by Ubuntu. You can learn more about how to use apt here.

For our purposes, we can get started by typing these commands:

  1. sudo apt-get update
  2. sudo apt-get install apache2

Since we are using a sudo command, these operations get executed with root privileges. It will ask you for your regular user’s password to verify your intentions.

Once you’ve entered your password, apt will tell you which packages it plans to install and how much extra disk space they’ll take up. Press y and hit ENTER to continue, and the installation will proceed.

Setting Global ServerName to Suppress Syntax Warnings

Next, we will add a single line to the /etc/apache2/apache2.conf file to suppress a warning message. While harmless, if you do not set ServerName globally, you will receive the following warning when checking your Apache configuration for syntax errors:

  1. sudo apache2ctl configtest
Output
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

Open up the main configuration file with your text edit:

  1. sudo nano /etc/apache2/apache2.conf

Inside, at the bottom of the file, add a ServerName directive, pointing to your primary domain name. If you do not have a domain name associated with your server, you can use your server’s public IP address:

Note: If you don’t know your server’s IP address, skip down to the section on how to find your server’s public IP address to find it.

/etc/apache2/apache2.conf
. . .
ServerName server_domain_or_IP

Save and close the file when you are finished.

Next, check for syntax errors by typing:

  1. sudo apache2ctl configtest

Since we added the global ServerName directive, all you should see is:

Output
Syntax OK

Restart Apache to implement your changes:

  1. sudo systemctl restart apache2

You can now begin adjusting the firewall.

Adjusting the Firewall to Allow Web Traffic

Next, assuming that you have followed the initial server setup instructions to enable the UFW firewall, make sure that your firewall allows HTTP and HTTPS traffic. You can make sure that UFW has an application profile for Apache like so:

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

If you look at the Apache Full profile, it should show that it enables traffic to ports 80 and 443:

  1. sudo ufw app info "Apache Full"
Output
Profile: Apache Full Title: Web Server (HTTP,HTTPS) Description: Apache v2 is the next generation of the omnipresent Apache web server. Ports: 80,443/tcp

Allow incoming traffic for this profile:

  1. sudo ufw allow in "Apache Full"

You can do a spot 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 under the next heading to find out what your public IP address is if you do not have this information already):

http://your_server_IP_address

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

Ubuntu 16.04 Apache default

If you see this page, then your web server is now correctly installed and accessible through your firewall.

Finding your Server’s Public IP Address

If you do not know what your server’s public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.

From the command line, you can find this a few ways. First, you can use the iproute2 tools to get your address by typing this:

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

This will give you two or three lines back. 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 outside party to tell you how it sees your server. You can do this by asking a specific server what your IP address is:

  1. sudo apt-get install curl
  2. curl http://icanhazip.com

Regardless of the method you use to get your IP address, you can type it into your web browser’s address bar to get to your server.

Step 2 — Installing MySQL

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

Again, we can use apt to acquire and install our software. This time, we’ll also install some other “helper” packages that will assist us in getting our components to communicate with each other:

  1. sudo apt-get install mysql-server

Note: In this case, you do not have to run sudo apt-get update prior to the command. This is because we recently ran it in the commands above to install Apache. The package index on our computer should already be up-to-date.

Again, you will be shown a list of the packages that will be installed, along with the amount of disk space they’ll take up. Enter Y to continue.

During the installation, your server will ask you to select and confirm a password for the MySQL “root” user. This is an administrative account in MySQL that has increased privileges. Think of it as being similar to the root account for the server itself (the one you are configuring now is a MySQL-specific account, however). Make sure this is a strong, unique password, and do not leave it blank.

When the installation is complete, we want to run a simple security script that will remove some dangerous defaults and lock down access to our database system a little bit. Start the interactive script by running:

  1. mysql_secure_installation

You will be asked to enter the password you set for the MySQL root account. Next, you will be asked if you want to configure the VALIDATE PASSWORD PLUGIN.

Warning: Enabling this feature is something of a judgment call. If enabled, passwords which don’t match the specified criteria will be rejected by MySQL with an error. This will cause issues if you use a weak password in conjunction with software which automatically configures MySQL user credentials, such as the Ubuntu packages for phpMyAdmin. It is safe to leave validation disabled, but you should always use strong, unique passwords for database credentials.

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

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, or which 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 case, special characters and dictionary                  file

Please enter 0 = LOW, 1 = MEDIUM and 2 = STRONG: 1

If you enabled password validation, you’ll be shown a password strength for the existing root password, and asked you if you want to change that password. If you are happy with your current password, enter n for “no” at the prompt:

Using existing password for root.

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

For the rest of the questions, you should 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 we have made.

At this point, your database system is now set up and we can move on.

Step 3 — Installing PHP

PHP is the component of our setup that will process code to display dynamic content. It can run scripts, connect to our MySQL databases to get information, and hand the processed content over to our web server to display.

We can once again leverage the apt system to install our components. We’re going to include some helper packages as well, so that PHP code can run under the Apache server and talk to our MySQL database:

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

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

In most cases, we’ll want to modify the way that 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 our web server to prefer PHP files, so we’ll make Apache look for an index.php file first.

To do this, type this command to open the dir.conf file in a text editor with root privileges:

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

It will look like this:

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

We want to move the PHP index file highlighted above to the first position after the DirectoryIndex specification, like this:

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

When you are finished, save and close the file by pressing Ctrl-X. You’ll have to confirm the save by typing Y and then hit Enter to confirm the file save location.

After this, we need to restart the Apache web server in order for our changes to be recognized. You can do this by typing this:

  1. sudo systemctl restart apache2

We can also check on the status of the apache2 service using systemctl:

  1. sudo systemctl status apache2
Sample Output
● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Wed 2016-04-13 14:28:43 EDT; 45s ago Docs: man:systemd-sysv-generator(8) Process: 13581 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 13605 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) Tasks: 6 (limit: 512) CGroup: /system.slice/apache2.service ├─13623 /usr/sbin/apache2 -k start ├─13626 /usr/sbin/apache2 -k start ├─13627 /usr/sbin/apache2 -k start ├─13628 /usr/sbin/apache2 -k start ├─13629 /usr/sbin/apache2 -k start └─13630 /usr/sbin/apache2 -k start Apr 13 14:28:42 ubuntu-16-lamp systemd[1]: Stopped LSB: Apache2 web server. Apr 13 14:28:42 ubuntu-16-lamp systemd[1]: Starting LSB: Apache2 web server... Apr 13 14:28:42 ubuntu-16-lamp apache2[13605]: * Starting Apache httpd web server apache2 Apr 13 14:28:42 ubuntu-16-lamp apache2[13605]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerNam Apr 13 14:28:43 ubuntu-16-lamp apache2[13605]: * Apr 13 14:28:43 ubuntu-16-lamp systemd[1]: Started LSB: Apache2 web server.

Install PHP Modules

To enhance the functionality of PHP, we can optionally install some additional modules.

To see the available options for PHP modules and libraries, you can pipe the results of apt-cache search into less, a pager which lets you scroll through the output of other commands:

  1. apt-cache search php- | less

Use the arrow keys to scroll up and down, and q to quit.

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

libnet-libidn-perl - Perl bindings for GNU Libidn
php-all-dev - package depending on all supported PHP development packages
php-cgi - server-side, HTML-embedded scripting language (CGI binary) (default)
php-cli - command-line interpreter for the PHP scripting language (default)
php-common - Common files for PHP packages
php-curl - CURL module for PHP [default]
php-dev - Files for PHP module development (default)
php-gd - GD module for PHP [default]
php-gmp - GMP module for PHP [default]
…
:

To get more information about what each module does, you can either search the internet, or you can look at the long description of the package by typing:

  1. apt-cache show package_name

There will be a lot of output, with one field called Description-en which will have a longer explanation of the functionality that the module provides.

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

  1. apt-cache show php-cli

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

Output
… Description-en: 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 Debian's default PHP version (currently 7.0). …

If, after researching, you decide you would like to install a package, you can do so by using the apt-get install command like we have been doing for our other software.

If we decided that php-cli is something that we need, we could type:

  1. sudo apt-get install php-cli

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

  1. sudo apt-get install package1 package2 ...

At this point, your LAMP stack is installed and configured. We should still test out our PHP though.

Step 4 — Testing PHP Processing on your Web Server

In order to test that our system is configured properly for PHP, we can create a very basic PHP script.

We will call this script info.php. In order for Apache to find the file and serve it correctly, it must be saved to a very specific directory, which is called the web root.

In Ubuntu 16.04, this directory is located at /var/www/html/. We can create the file at that location by typing:

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

This will open a blank file. We want to put the following text, which is valid PHP code, inside the file:

info.php
<?php
phpinfo();
?>

When you are finished, save and close the file.

Now we can test whether our web server can correctly display content generated by a PHP script. To try this out, we just have to visit this page in our web browser. You’ll need your server’s public IP address again.

The address you want to visit will be:

http://your_server_IP_address/info.php

The page that you come to should look something like this:

Ubuntu 16.04 default PHP info

This page basically gives you information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.

If this was successful, then your PHP is working as expected.

You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, you can type this:

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

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

Conclusion

Now that you have a LAMP stack installed, you have many choices for what to do next. Basically, you’ve installed a platform that will allow you to install most kinds of websites and web software on your server.

As an immediate next step, you should ensure that connections to your web server are secured, by serving them via HTTPS. The easiest option here is to use Let’s Encrypt to secure your site with a free TLS/SSL certificate.

Some other popular options are:

Spin up a Linux virtual machine with Apache, MySQL, and PHP pre-configured and attached in one simple click with DigitalOcean. Let us spin up a LAMP stack server for you in seconds, so you can focus on building a great application.

Learn more here

About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
113 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

How to find your droplets IP: type ‘ifconfig’ and it should be the top device/interface. inet addr: YOUR_IP

the easiest way would be: curl ip.mk

Very good suggestion @teddy . I’ve tested here.

I always use icanhazip.com, as shown in the tutorial.

Nice!

How can I restore a Full Backup done with Cpanel, in my new VPS after install wordpress?

Jon Schwenn
DigitalOcean Employee
DigitalOcean Employee badge
April 22, 2016

Hi,

The cPanel full backup is a compressed file that normally is named like backup-[date]_[time]_[cPanel user name].tar.gz. This file can be be uncompressed on a Mac by double clicking on it. For Windows, most unzip utilities should also be able to uncompress the file.

After uncompressing the file you’ll have a folder with many other folders and files in it. All of your website files should be in homedir/public_html and you’ll see the database backups under the mysql folder. Those two items will make up your WordPress site.

You can then follow a process very similar to the outlined here to migrate the WordPress site to your new server.

Thank you!

I can do this procedure in a Ubuntu 1 click to wordpress?

Jon Schwenn
DigitalOcean Employee
DigitalOcean Employee badge
April 23, 2016

In theory yes, but you may be better off using the phpMyAdmin one-click. you can upload all the files in the homedir/public_html folder of the backup to /var/www/html/ of the One-click based Droplet. Then you would create the database in phpMyAdmin and import your database backup also through the phpMyAdmin panel. You would need to update the database connection details in the /var/www/html/wp-config.php file, but after that the WordPress site should load.

I receive this error, after put my pass of user_db: mysql -h localhost -u (i change here) -p (and here for mu db name) < (and put correct file here)backup_db.sql.gz

Enter password: ERROR at line 1: Unknown command ’
'. What you think? It’s better start configuration a Ubuntu 16.04 manually?

Yo! It’s ok now. Backup restored and imported db… how I can configure my domain from bluehost here on my VPS? The Domain will still there.

Jon Schwenn
DigitalOcean Employee
DigitalOcean Employee badge
April 24, 2016

@Ablon - Here is a great tutorial on how to setup a Domain using our DNS feature.

Awesome tutorial!

PHP doesn’t seem to work with Apache though.

sudo a2enconf php7.0.conf returns ERROR: Conf php7.0 does not exist!. ls -la | grep php returns:

-rw-r--r-- 1 root root   867 Apr 14 13:13 php7.0.conf
-rw-r--r-- 1 root root    79 Apr 14 13:13 php7.0.load

I also ran sudo a2enmod php7.0, which returned:

Considering conflict php5 for php7.0:
Enabling module php7.0.
To activate the new configuration, you need to run:
  service apache2 restart

However, php5 is not installed. sudo a2dismod php5 returns another error saying it doesn’t exist.

I had the same problem, apache2 wasn’t restarting after enabling php7.0 and when I ran sudo apache2ctl configtest gave the error: /usr/lib/apache2/modules/libphp7.0.so: cannot open shared object file: No such file or directory then, I installed it with sudo apt-get install libapache2-mod-php7.0 and the restart the apache with sudo systemctl restart apache2 and after that, I am able to see phpinfo().

I successfully installed apache2 but there is not in ufw list. Why and how can I configured it?

Thank you, thank you, thank you! i cannot thank you enough. i could fall at your feet and kiss them. this tut saved my life!

Thx for helpful guide.

Unable to render php code after upgrading the ubuntu 16.04. By following to install the php with above process.

Hi,

I had the same issue. I followed the install guide above, but installed php5.6 instead of php7 (which comes with ubuntu 16.04).

output of: apachectl configtest “Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe. You need to recompile PHP”

I solved in this way (for apache to render php code): a2dismod mpm_event a2enmod mpm_prefork

check again with: apachectl configtest restart apache: service apache2 restart

Hope it works for you, too.

Should this work on 32 bit computers as well? Or do you need php7 in combination with 64 bit computer?

I try to install lamp on ubuntu 16.04 for 2 weeks already and guess that 32 bit will be the reason of my failures?

This comment has been deleted

    Step 3: Install PHP $ sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql Reading package lists… Done Building dependency tree Reading state information… Done E: Unable to locate package php E: Unable to locate package libapache2-mod-php E: Unable to locate package php-mcrypt E: Unable to locate package php-mysql

    Yeah, this works. Not.

    Had the same problem, for future references if someone else gets that error, I only had to add a 5 (the current version of php) after php to make it work:

    sudo apt-get install php5 libapache2-mod-php5 php5-mcrypt php5-mysql

    thank you very much for this. I had the same problem as JasonRawlings above. Your trick worked.

    Thumbs up for this ^^

    Currently this is not working. I tried changing to sudo apt-get install php5-mcrypt and still get the error.

    Nice Tutorial… Question though, I was able to install apache2, php, mysql but Web browser is displaying PHP codes instead of executing it… My guess is apache issue? any input? Thanks

      Would you like  send some information to my  mailbox(www.hq199@hotmail.com)  about the Ubuntu 16 LTS system ?
    

    Think very much.

    Please Update Tutorial I can’t install php with your command on 16.04 " sudo apt-get install php libapache2-mod-php php-mcrypt php-mysql "

    It’s not working

    “It’s not working” is not very helpful. The above commmand works for me and without an error message, nobody here can help you?

    For those who struggle with seeing the code in the browser instead of the phpinfo() page…

    <? phpinfo();
    

    PHP is installed by default with short tags off. Either change your code or change php.ini. This sed command will do the trick if you opt to turn short tags on.

    sed -i "s/short_open_tag = .*/short_open_tag = On/" /etc/php/7.0/apache2/php.ini 
    

    Looks like the default is ON. ; short_open_tag ; Default Value: On ; Development Value: Off ; Production Value: Off

    Hello everyone :D

    I have a problem. I can access the application, phpmyadmin, etc. But only inside the server.

    What I need to do, for external access. Like a computer in my network?

    Bobby Iliev
    Site Moderator
    Site Moderator badge
    March 9, 2020

    In case anyone else has this issue. This might be your Ubuntu Firewall, you need to make sure that port 80 and 443 are open.

    You can take a look at this tutorial here on how to manage your UFW:

    https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-18-04

    Thanks very nice tutorial!!!

    Awesome! you made my day!!

    Awesome! I Installed it in 10 minutes. Wow!! All thanks to your tutorial!!

    For very lazy sysadmins like me:

    sudo tasksel

    then choose LAMP-Server. Drink a coffee and enjoy

    this is great, this should be indicated at the very beginning of this tutorial as an alternative option!

    For goodness sake doesn’t matter how lazy you are DON’T USE TASKSEL! tasksel is practically a blackbox. When you want to uninstall something tasksel has installed it’ll remove half of your system, because it overzealously removes any and all dependencies. Google: tasksel uninstall issues

    You don’t know how it set things up, so modifying stuff it installed is guesswork.

    One of the best tutorials I have ever seen regarding servers. ALL steps worked (!) without any issue. This is highly professional. Well done.

    THANKS FOR THE BEST TUTORIALS ABOUT HOW TO INSTALL- LINUX. WITH ALL THE STEPS TO FOLLOW

    For those running into issues with missing php-modules (especially when using the php cli), you might want to install php-curl module.

    Thanks so much.I installed into my local computer and voila, it worked.

    Very useful.

    This comment has been deleted

      The info.php is not executing. Got below error;

       Package libapache2-mod-php7.0 is not configured yet.
      
      dpkg: error processing package libapache2-mod-php (--configure):
       dependency problems - leaving unconfigured
      Errors were encountered while processing:
       libapache2-mod-php7.0
       libapache2-mod-php
      E: Sub-process /usr/bin/dpkg returned an error code (1)
      

      Apache2 does not restart for me if I reboot my droplet. Does that work for everyone else? I thought that would have been a default thing…

      Thank you very much for this article. Your article is easily understandable and the commands correct.

      You have saved me a lot of time. Thanks once more.

      This is great! sudo apt-get install php5 was killing me, glad they went back to php for installs. I added webmin for managing everything so life is sweet.

      I configure the ServerName as you said. But I have troubles to see the apache welcome page through chrome.

      I have a TP Link router, Do I have to do something else in order to see the apache welcome page with my public ip from the browser?

      is mysql-client automatically installed when you install mysql-server?

      For those running into issues with missing php-modules (especially when using the php cli), you might want to install php-curl module.

      Thanks so much.I installed into my local computer and voila, it worked.

      Very useful.

      This comment has been deleted

        The info.php is not executing. Got below error;

         Package libapache2-mod-php7.0 is not configured yet.
        
        dpkg: error processing package libapache2-mod-php (--configure):
         dependency problems - leaving unconfigured
        Errors were encountered while processing:
         libapache2-mod-php7.0
         libapache2-mod-php
        E: Sub-process /usr/bin/dpkg returned an error code (1)
        

        Apache2 does not restart for me if I reboot my droplet. Does that work for everyone else? I thought that would have been a default thing…

        Thank you very much for this article. Your article is easily understandable and the commands correct.

        You have saved me a lot of time. Thanks once more.

        This is great! sudo apt-get install php5 was killing me, glad they went back to php for installs. I added webmin for managing everything so life is sweet.

        I configure the ServerName as you said. But I have troubles to see the apache welcome page through chrome.

        I have a TP Link router, Do I have to do something else in order to see the apache welcome page with my public ip from the browser?

        is mysql-client automatically installed when you install mysql-server?

        For those running into issues with missing php-modules (especially when using the php cli), you might want to install php-curl module.

        Thanks so much.I installed into my local computer and voila, it worked.

        Very useful.

        This comment has been deleted

          The info.php is not executing. Got below error;

           Package libapache2-mod-php7.0 is not configured yet.
          
          dpkg: error processing package libapache2-mod-php (--configure):
           dependency problems - leaving unconfigured
          Errors were encountered while processing:
           libapache2-mod-php7.0
           libapache2-mod-php
          E: Sub-process /usr/bin/dpkg returned an error code (1)
          

          Apache2 does not restart for me if I reboot my droplet. Does that work for everyone else? I thought that would have been a default thing…

          Thank you very much for this article. Your article is easily understandable and the commands correct.

          You have saved me a lot of time. Thanks once more.

          This is great! sudo apt-get install php5 was killing me, glad they went back to php for installs. I added webmin for managing everything so life is sweet.

          I configure the ServerName as you said. But I have troubles to see the apache welcome page through chrome.

          I have a TP Link router, Do I have to do something else in order to see the apache welcome page with my public ip from the browser?

          is mysql-client automatically installed when you install mysql-server?

          Hello this article has a been a great tool for me as I build my first virtual Ubuntu apache server. However I have came to an halt in the “Set Global ServerName to Suppress Syntax Warnings” section. I’m not sure where to enter the directive ServerName server_name_or_ip_address in the sudo nano /etc/apache2/apache2.conf file. I have entered the data directly at the bottom of the file and save. Yet, when I run the sudo apache2ctl configtest command I still receive the error message. Is there something I am missing? All suggestions are welcome!

          In this step:

          This will open a blank file. We want to put the following text, which is valid PHP code, inside the file:

          info.php <?php phpinfo();

          We need to close the info.php file with “?>” at the end:

          <?php phpinfo(); ?>

          How about a link to making apache and webserver work when it’s behind a router?

          Aaand as soon I forward port 80, the router GUI is inaccessible via web! yay. Now time to look at telnet commands…

          Can simply install the whole step on Ubuntu by one command

          sudo apt-get install lamp-server
          

          Thanks alot for this nice tutorial. Very complete, detailed and easy to follow. I’ve got 16.10 installed (no dual boot… full blown ) and currently setting up developpment environment… Your tutorial was of a big help. – Now heading up to install Symfony 3 :) Thanks again.

          I made a video of migrating my blog from a shared host to digital ocean, Ubuntu 16.04. I chronicled all the steps here https://www.youtube.com/watch?v=UrY1P041uUU

          Hi, I’ve been following along with this tutorial and everything went well except I couldn’t access my server on web browser via the Public IP got from curl http://icanhazip.com. What should I do?

          I’m using Ubuntu 16.04.1

          Thanks,

          I found this to be very helpful in my installation. thanks!

          Awesome…!!!

          Had an issue with accessing the info.php (500 error). changing ownership of the file from root to www-data seemed to work–Hope it helps someone :)

          sudo chown www-data:www-data /var/www/html/info.php
          

          How to know the “Server’s Public IP Address” on Wireless Interface?

          Getting these two error $ sudo systemctl restart apache2 sudo: systemctl: command not found $ sudo ufw app list sudo: ufw: command not found could anyone please tell what to do?

          Hi mohit26maheshwari,

          Could you please confirm that you are using Ubuntu 16.04?

          If not, probably you need to use something like:

          sudo service apache2 restart

          Thank You It worked Now

          Great! You are welcome!

          unable to open this address http://139.59.21.231/info.php

          Hi mohit26maheshwari,

          You are using Debian, and this tutorial is for Ubuntu 16.04.

          Anyway, you need to check the correctness of the content of the file you’ve created for the test (info.php). Also, check the permission of the file in /var/www/html/ directory.

          @Brennen Bearnes,

          In Step 4, you are referencing Ubuntu 14.04 instead of 16.04.

          I think that is due to the updates from the previous version. : )

          when i run info.php then i saw this

          <?php phpinfo();

          what i do please reply

          Hi akhand2505aps,

          You need to close the info.php file with “?>” at the end:

          <?php phpinfo(); ?>

          Try again with this code, please.

          Setting the Global ServerName to Suppress Syntax Warnings section seems irrelevant now.

          sudo apache2ctl configtest
          

          Running the command above only returns just a Syntax OK output

          I followed everything, but php wasnt working.

          I tried askubuntu and found this command and things worked fine for me then.

          sudo apt-get install apache2 php5 libapache2-mod-php5

          http://askubuntu.com/questions/451708/php-script-not-executing-on-apache-server

          Hope it help others too…

          Hi thinkncode,

          I’d like to remember that this guide is for an Ubuntu 16.04 Droplet (An Ubuntu 16.04 image prepared by DigitalOcean).

          Some problems might arise if you are using this guide for a generic Ubuntu 16.04 Server.

          Best regards

          Awesome tutorial, but it’s not really finished – now I have a nice sparkly new LAMP server, but how do I upload my web files? There needs to be either/or:

          1. An FTP how-to (or SFTP, or ???)
          2. A link (or two, or three) to Tutorials that DO tell how to do this.

          I’ve found plenty of tutorials, but they ALL tell how to set it up for a new user. I need to know how to set up FTP to upload files to /var/www/html/???. How do I chroot that?!? (or do I need to?) How do I set up the login in that directory? Is the trick to use the www-data user? How do I set up a password on that user? Or an SSH key pair? Will any of that interfere with Apache? Yup…I have questions!

          FTP is not safe instead use

          Use winscp Download it at www.winscp.net Use File protocol: SCP Enter Hostname or IP address Username or root Password

          This post might help you.

          Thank you, but my point is that this tutorial is not complete until a method for uploading files to the server is included. My comment was directed at the author of this tutorial.

          The code: <?php phpinfo(); doesn’t seem to work for 16.04. Only shows a blank page, any suggestions?

          Hi buddejeffrie1,

          You need to close the info.php file with “?>” at the end:

          <?php phpinfo(); ?>

          Try again with this code, please.

          The closing PHP Tag (‘?>’) is optional. I doubt that is the problem. Does the name of the file that contains this code, have a ‘.php’ extension? Assuming the webserver is Apache, has the httpd.conf file been modified? If the “<IfModule mime_module>” section doesn’t contain a line that associates “.php” with the PHP plugin, then *.php files will not be interpreted as PHP code [though, I would expect to see the code displayed on the page, if this were the cause]. The following links to an excellent article about this: http://www.thegeekstuff.com/2014/03/php-custom-file-extension/

          Also, have a look in the PHP error_log file (if one exists). You might also get clues by viewing the “Page Source” [Firefox, Chrome, not sure what it’s called in the Micro$oft browser, and I refuse to look], and both Firefox and Chrome have a debugging tool. In Firefox it’s called “Inspect Element” – right-click on the “page” and select “Inspect Element” from the pop-up menu. Sometimes it can provide clues as to what is going wrong.

          Also, it’s possible that something went wrong with the PHP install. Or, perhaps you neglected to restart Apache after installing PHP.

          Thank for sharing great and valuable information with us. You just helped me setting up a new Ubuntu vps with Apache PHP and MySQL at my newly registered domain jaisi.org. Now I am looking for wild card subdomain on the same domain. Can any one help me here in setting wild card subdomain.

          Hi websitemaker001,

          I think this can help you (See step three):

          https://www.digitalocean.com/community/tutorials/how-to-set-up-a-host-name-with-digitalocean

          Best,

          Fernando Pimenta

          Excellent guide! Got everything setup and its working flawlessly!

          Thanks,

          If you want to use PHP 7 you can just replace “php” with “php7.0” on all install names, as each library listed has a separate PHP 7 version, here is what I use:

          apt install php7.0 libapache2-mod-php7.0 php7.0-mcrypt php7.0-mysql
          

          Great tutorial. One question, can I rename the info file to something rare instead of removing it? I just would like to keep it.

          Hi @fourwadsmart,

          For security reasons, remove this file from your site.

          If you need to keep it, remove the .php extension:

          mv info.php info

          Best,

          Fernando Pimenta

          Thanks, I will remove ;)

          Perfect Tutorial… Everything works like a charm…

          Brennen Bearnes you are the best!!! Thank you!!!

          Hi, I recently figured out a nice emerging package which eases this entire tutorial in a single command.

          Check: https://github.com/santoshbaggam/stacker

          I feel this could be a helpful tool!

          Which ip we need to add, private or public in case aws ec2

          What about python?

          Thank you for creating this guide. It has helped me a lot setup.

          If you’re using multiple domain names Please set open_basedir when you’re defining your virtual hosts in Apache. This way you prevent a potential ransomeware attack to the folder for that virtual host and not the whole /var/www directory, not knowing which site was the source of evil. (As happened to me). E.g.:

          <Directory "/var/www/engeen.nl">
              allow from all
              Options -Indexes
              Require all granted
              php_admin_value open_basedir "/var/www/engeen.nl"
          </Directory>
          

          There is one problem I see, and that is that the link to install worpdress is for Ubuntu 14.04, when it should link to this tutorial: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-with-lamp-on-ubuntu-16-04. Other than that, I have used this tutorial every time, and have not had any problems whatsoever!

          Hello Brennen and thanks for this nice tutorial. What if the server reboot for any reason are the different services restarting or do i have to do configure it somewhere ?

          Thank you!

          What if I don’t want to secure the mysql that I’d created but I want to change my password? What code should I input?

          Hi @curteneyarellano,

          To setup root password for first time, use mysqladmin command at shell prompt as follows:

          $ mysqladmin -u root password NEWPASSWORD

          Best,

          Fernando Pimenta

          Great tutorial. Thanks a ton. But how to start developing using a editor like Brackets since the directory /var/www/html/ has permission issue and using terminal every time to create save and edit is not good choice. Also using chmod to change permissions of the directory doesn’t seems right. So what should one do ? Change the documents root directory of the apache server from /etc/apache2/sites-available/ ??

          Great tutorial. Thanks a ton. But how to start developing using a editor like Brackets since the directory /var/www/html/ has permission issue and using terminal every time to create save and edit is not good choice. Also using chmod to change permissions of the directory doesn’t seems right. So what should one do ? Change the documents root directory of the apache server from /etc/apache2/sites-available/ ??

          Good tutorial and steps! Thx

          php-mycrypt is deprecated since php 7.1 and removed since php 7.2, as seen here: http://php.net/manual/en/intro.mcrypt.php

          Thanks, well explained and easy to follow. Just what I needed.

          Note that php-mcrypt has been deprecated as of PHP 7.1, so may not be needed.

          Fantastic. Coming back to Linux after a few years, this worked flawlessly. I just installed this on a fresh install of Mint 18.3. I did install the suggested php packages: php-pear, libmcrypt-dev, and mycrypt.

          Thanks!

          One of the best tutorials to install LAMP, thank you.

          thanks very much, it worked best but how can i access my local webserver from any computer on the internet?

          Very very thank you that I’ve installed LAMP like you said and installed correctly. But when i try to run .php file (localhost/first.php) , output looks like this :

          <?php echo “This is php”; ?>

          What is the problem behind this. Can you help me to solve this.

          Error during my apache2ctl configtest. i ve added ServerName IP to the apache2.conf file but same error occurs . Is there any solution to this error??

          This (and the rest of the Digital Ocean tutorials) have been wonderful.

          One note, for those not using digital ocean, I had trouble losing access to the mysql root account when using dynamic ip’s with aws/ec2 instances. The solution for me was to answer “no” to the “Disallow root login remotely?” question when running mysql_secure_installation.

          Thanks!

          -C

          When installing php-mcrypt :

          Package php-mcrypt is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source

          E: Package ‘php-mcrypt’ has no installation candidate


          So I know php-mcrypt has been abandoned / not updated in years, but I just want to make sure that this new notification (I make a new droplet about once every other week) isn’t anything to cause concern, or if there are any functions that I will be missing.

          Hi @nickpimnj,

          I’ve tested the entire tutorial just now, and and everything worked fine. For php-mcrypt, see the message while installing in my droplet:

          Get:12 http://mirrors.digitalocean.com/ubuntu xenial-updates/universe amd64 php7.0-mcrypt amd64 7.0.30-0ubuntu0.16.04.1 [14.5 kB]

          Are you using Ubuntu version 16.04 (the version that this tutorial is made for)?

          If not, let me know if you have the same problem testing on Ubuntu 16.04.

          Cheers!

          Absolument excellent. J’ai suivi le tutoriel à a Z sans soucis. Tous fonctionnait jusqu’à ce que je teste letsencrypt. Mais pour toute cette partie sur cette page aucun problème ça fonctionne nickel sur orangepi zéro (armbian Ubuntu 16.04 Xenical) du premier coups sans prise de tête. Vraiment excellent. Clairement expliqué pas à pas. Un tuto de grande qualité. Merci

          This tutorial used to work 100% and it was a great reference guide until a recent change to MySQL defaults. As of 5.7, now root is set to auth_sock authentication by default, so this will let you login from SSH/Terminal but not through any app/script/website following the tutorial.

          Look at the tutorial for installing Ubuntu on 18.04 for instructions on how to make the changes to MySQL to allow root to login inside your PhpMyAdmin/Adminer/Scripts/etc: https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-ubuntu-18-04

          Thank you <3

          Great explanation!

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

          the php-mcrypt is not working, I make works change for this one apt-get install php7.0

          This comment has been deleted

            this is very great. keep it up

            This comment has been deleted

              This comment has been deleted

                This comment has been deleted

                  Error: Access denied for user ‘root’@‘localhost’

                  Following section 2 to install MySQL it fails. The install command is successful but it doesn’t ask me to provide a password. I can’t find a default password for MySQL (I tried no password, root, and a couple others but no luck). Any suggestions for how to provide a password now that it’s already installed?

                  I’ve tried the suggestions on forums such as: https://stackoverflow.com/questions/11657829/error-2002-hy000-cant-connect-to-local-mysql-server-through-socket-var-run https://support.rackspace.com/how-to/mysql-resetting-a-lost-mysql-root-password/ https://stackoverflow.com/questions/41645309/mysql-error-access-denied-for-user-rootlocalhost

                  Are you using the droplet Ubuntu 16.04 (this tutorial is for this version)?

                  I’ve just created such droplet and ran the command:

                  apt-get install mysql-server

                  After this, the password message appears, as you can see here:

                  https://www.screencast.com/t/G3J8zaAjs

                  I’m following this tutorial in 11/2020 and thought I’d share some updates:

                  1. MySQL Instead of myql_secure_installation, I ran sudo mysql_secure_installation. I then proceeded to configure the password that is now know as VALIDATE PASSWORD COMPONENT. This is when you use add your pw.

                  2. PHP To install PHP, use this sudo apt-get install php libapache2-mod-php php-mysql. The php-mcrypt has been deprecated since PHP7.2

                  Everything is working, but your article in my opinion is to long. All article maybe can be faster and light, but everything is working

                  I use this to set root@localhost password :

                  $sudo mysql
                  mysql>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';
                  mysql>exit
                  

                  mysql_secure_installation gets stuck for me… https://share.getcloudapp.com/L1uXw1RJ … always this error: … Failed! Error: SET PASSWORD has no significance for user ‘root’@‘localhost’ as the authentication method used doesn’t store authentication data in the MySQL server. Please consider using ALTER USER instead if you want to change authentication parameters.

                  Guess I gotta leave and restart

                  KFSys
                  Site Moderator
                  Site Moderator badge
                  November 19, 2023

                  The error message you’re encountering during mysql_secure_installation is due to changes in how MySQL handles authentication for the root user, especially in MySQL 5.7 and later versions. By default, the root user in these versions uses the auth_socket or unix_socket plugin for authentication, which doesn’t require a password.

                  Here’s how you can resolve this issue:

                  1. Log in to MySQL:

                    First, access the MySQL shell. Since you’re using the auth_socket plugin, you can log in to MySQL as the root user without a password:

                  sudo mysql
                  
                  1. Change Authentication Method (Optional):

                  If you want to use a password for the root user, you can switch the authentication method from auth_socket to mysql_native_password. This step is optional but recommended for consistency with traditional authentication methods.

                  Run the following command in the MySQL shell:

                  ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'your_new_password';
                  FLUSH PRIVILEGES;
                  

                  Replace your_new_password with the password you wish to set for the MySQL root user.

                  1. Exit MySQL:

                    After making the changes, exit the MySQL shell:

                  EXIT;
                  
                  1. Run mysql_secure_installation Again:

                  Now that you’ve set a password for the root user (if you chose to change the authentication method), you can run the mysql_secure_installation script again. This time, it should proceed without the error:

                  mysql_secure_installation
                  

                  Above all thing cover by this script just one command

                  https://gist.github.com/Rushabhsorathia/e9646482e7185ee1313093a406129240

                  • 🛠️ Git Installation: Installs the Git version control system for managing your code repositories.

                  • 🌐 Apache Installation: Sets up the Apache HTTP Server and configures the necessary firewall rules for web server functionality.

                  • 🗃️ MySQL Installation: Installs MySQL Server and provides options to secure your installation, ensuring a robust database setup.

                  • 🧩 PHP Installation: Adds the PHP repository and installs multiple PHP versions (7.4, 8.0, 8.1, 8.2, 8.3) along with common modules for diverse development needs.

                  • 📊 phpMyAdmin Installation: Installs phpMyAdmin for easy database management with default credentials (Username: root, Password: password).

                  • 🔄 Custom PHP Switch: Clones and executes a custom PHP version switcher script, allowing you to switch PHP versions effortlessly.

                  Try DigitalOcean for free

                  Click below to sign up and get $200 of credit to try our products over 60 days!

                  Sign up

                  Join the Tech Talk
                  Success! Thank you! Please check your email for further details.

                  Please complete your information!

                  Become a contributor for community

                  Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                  DigitalOcean Documentation

                  Full documentation for every DigitalOcean product.

                  Resources for startups and SMBs

                  The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                  Get our newsletter

                  Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                  New accounts only. By submitting your email you agree to our Privacy Policy

                  The developer cloud

                  Scale up as you grow — whether you're running one virtual machine or ten thousand.

                  Get started for free

                  Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                  *This promotional offer applies to new accounts only.