How to Install a LAMP Stack on Ubuntu 18.04
Traducciones al EspañolEstamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
What is a LAMP Stack?
A LAMP (Linux, Apache, MySQL, PHP) stack is a common, free, and open-source web stack used for hosting web content in a Linux environment. Many consider it the platform of choice on which to develop and deploy high-performance web apps.
This guide shows how to install and test a LAMP stack on Ubuntu 18.04 (LTS).
This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, visit our
Users and Groups guide.
All configuration files should be edited with elevated privileges. Remember to include sudo before running your text editor.
Replace each instance of example.com in this guide with your site’s domain name or IP.
Before You Begin
If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
Follow our Setting Up and Securing a Compute Instance guide to update your system and configure your hostname. You may also wish to set the timezone, create a limited user account, and harden SSH access.
example.com with the IP address of the Linode server in the following instructions.Installation
Install Using Tasksel
Instead of installing Apache, MySQL, and PHP separately, Tasksel offers a convenient way to get a LAMP stack running quickly.
Install Tasksel if not already installed by default:
sudo apt install taskselUse Tasksel to install the LAMP stack:
sudo tasksel install lamp-server
Install Packages Separately
If you prefer not to install the bundled packages via Tasksel, you can instead install them separately:
Install Apache 2.4 from the Ubuntu repository:
sudo apt install apache2Install the
mysql-serverpackage:sudo apt install mysql-serverInstall PHP, the PHP Extension and Application Repository, Apache support, and MySQL support:
sudo apt install php7.2 libapache2-mod-php7.2 php-mysqlOptionally, install additional cURL, JSON, and CGI support:
sudo apt install php-curl php-json php-cgi
Configuration
Apache
The
KeepAlivesetting allows Apache to better utilize server-side memory, reducing latency for users on the hosted site.KeepAlivemakes a website faster if the host has enough memory to support it. This is done by allowing Apache to reuse connections, instead of opening a new connection for every request.Open the
apache2.confApache config file and adjust theKeepAlivesetting:- File: /etc/apache2/apache2.conf
1 2 3KeepAlive On MaxKeepAliveRequests 50 KeepAliveTimeout 5
Note TheMaxKeepAliveRequestssetting controls the maximum number of requests during a persistent connection. 50 is a conservative amount; you may need to set this number higher depending on your use-case. TheKeepAliveTimeoutsetting controls how long the server waits (measured in seconds) for new requests from already connected clients. Setting this to 5 will avoid wasting RAM.The default multi-processing module (MPM) is the prefork module.
mpm_preforkis the module that is compatible with most systems. Open thempm_prefork.conffile located in/etc/apache2/mods-availableand edit the configuration. Below are the suggested values for a 2GB Linode:- File: /etc/apache2/mods-available/mpm_prefork.conf
1 2 3 4 5 6 7<IfModule mpm_prefork_module> StartServers 4 MinSpareServers 3 MaxSpareServers 40 MaxRequestWorkers 200 MaxConnectionsPerChild 10000 </IfModule>
Enable the firewall to allow web traffic. This guide lists the commands to enable web traffic if you configured UFW on your server.
a. Check the ports that are enabled for
Apache FullProfile:sudo ufw app info "Apache Full"Ports
80and443should be listed as enabled forApache Fullprofile.b. To allow incoming HTTP and HTTPS traffic for
Apache Fullprofile:sudo ufw allow in "Apache Full"Disable the event module and enable prefork:
sudo a2dismod mpm_event sudo a2enmod mpm_preforkRestart Apache:
sudo systemctl restart apache2
Virtual Hosts
You can set up virtual hosts several ways, and the following steps outline the recommended method. For each of these steps, replace example.com with your domain name.
Create a copy of the default Apache configuration file for your site:
sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/example.com.confOpen the new
example.comconfiguration file in your text editor. Uncomment theServerNameoption and update it with your domain. Enter the document root path and log directories as shown below, and add aDirectoryblock before<VirtualHost>:- File: /etc/apache2/sites-available/example.com.conf
1 2 3 4 5 6 7 8 9 10 11 12 13<Directory /var/www/html/example.com/public_html> Require all granted </Directory> <VirtualHost *:80> ServerName example.com ServerAlias www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/example.com/public_html ErrorLog /var/www/html/example.com/logs/error.log CustomLog /var/www/html/example.com/logs/access.log combined </VirtualHost>
Note The file example above has all comment sections removed for brevity. Keep or remove the commented areas as you see fit.The
ServerAliasdirective allows you to include multiple domain names or subdomains for a single host. The example above allows visitors to useexample.comorwww.example.comto navigate to this virtual host.Create the directories referenced above:
sudo mkdir -p /var/www/html/example.com/{public_html,logs}Note Make sure that you do not put a space after the comma betweenpublic_htmlandlogsbecause it will create a folder named{public_html,and will cause an error when you will reload Apache.Assign ownership of
public_htmldirectory to the userwww-data:sudo chown -R www-data:www-data /var/www/html/example.com/public_htmlSet the permissions for the
public_htmldirectory:sudo chmod -R 755 /var/www/html/example.com/public_htmlLink your virtual host file from the
sites-availabledirectory to thesites-enableddirectory:sudo a2ensite example.comNote To disable your website, runa2dissite example.com.Disable the default virtual host to minimize security risks:
sudo a2dissite 000-default.confReload Apache:
sudo systemctl reload apache2
Virtual hosting should now be enabled. To allow the virtual host to use your domain name, be sure that you have configured DNS services for your domain to point to your Linode’s IP address.
If there are additional websites you wish to host on your Linode, repeat the above steps to add a folder and configuration file for each.
MySQL
Log in to MySQL’s SQL shell:
sudo mysql -u rootBy default, MySQL is configured to use the
auth_socketauthorization plugin. This authorization scheme allows you to log in to the database’s root user as long as you are connecting from the Linux root user on localhost, or as a user with sudo privileges (i.e. withsudo mysql -u root). In this scheme, no password is assigned to MySQL’s root user:1 2 3 4 5 6 7mysql> SELECT user,host,authentication_string,plugin FROM mysql.user WHERE user='root'; +------+-----------+-----------------------+-------------+ | user | host | authentication_string | plugin | +------+-----------+-----------------------+-------------+ | root | localhost | | auth_socket | +------+-----------+-----------------------+-------------+ 1 row in set (0.02 sec)You can keep using the
auth_socketplugin, and this is considered a secure option for production systems. If you’d rather switch to password authentication and assign a password, enter the following commands. Replacepasswordwith a new root password:1 2mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH 'mysql_native_password' BY 'password'; mysql> FLUSH PRIVILEGES;After making this change, you should pass the
-poption when invoking the MySQL shell:mysql -u root -pCreate a database and a user with permissions for it. In this example, the database is called
webdata, the userwebuser, and passwordpassword. Be sure to enter your own password. This should be different from the root password for MySQL:1 2CREATE DATABASE webdata; GRANT ALL ON webdata.* TO 'webuser' IDENTIFIED BY 'password';Exit the SQL shell:
1quitUse the mysql_secure_installation tool to configure additional security options. You will be given the choice to change the MariaDB root password, remove anonymous user accounts, disable root logins outside of localhost, and remove test databases. It is recommended that you answer
yesto these options. You can read more about the script in the MariaDB Knowledge Base.sudo mysql_secure_installation
PHP
Edit the configuration file located in
/etc/php/7.2/apache2/php.inito enable more descriptive errors, logging, and better performance. The following modifications provide a good starting point:- File: /etc/php/7.2/apache2/php.ini
1 2 3error_reporting = E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_ERROR | E_CORE_ERROR max_input_time = 30 error_log = /var/log/php/error.log
Note The beginning of thephp.inifile contains examples commented out with a semicolon (;), which disables these directives. Ensure that the lines you modify in this step follow the examples section and are uncommented.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/phpRestart Apache:
sudo systemctl restart apache2Note If you plan on using your LAMP stack to host a WordPress server, install additional PHP modules:sudo apt install php-curl php-gd php-mbstring php-xml php-xmlrpc
Optional: Test and Troubleshoot the LAMP Stack
In this section, you’ll create a test page that shows whether Apache can render PHP and connect to the MySQL database. This can be helpful in locating the source of an error if one of the elements of your LAMP stack is not communicating with the others.
Paste the following code into a new file,
phptest.php, in thepublic_htmldirectory. Modifywebuserandpasswordto match the information entered in the Create a MySQL Database section above:- File: /var/www/html/example.com/public_html/phptest.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23<html> <head> <title>PHP Test</title> </head> <body> <?php echo '<p>Hello World</p>'; // In the variables section below, replace user and password with your own MySQL credentials as created on your server $servername = "localhost"; $username = "webuser"; $password = "password"; // Create MySQL connection $conn = mysqli_connect($servername, $username, $password); // Check connection - if it fails, output will include the error message if (!$conn) { die('<p>Connection failed: </p>' . mysqli_connect_error()); } echo '<p>Connected successfully</p>'; ?> </body> </html>
Navigate to
example.com/phptest.phpfrom your local machine. If the components of your LAMP stack are working correctly, the browser will display a “Connected successfully” message. If not, the output will be an error message.Remove the test file:
sudo rm /var/www/html/example.com/public_html/phptest.php
Troubleshooting
If the site does not load at all, check if Apache is running, and restart it if required:
sudo systemctl status apache2 sudo systemctl restart apache2If the site loads, but the page returned is the default “Congratulations” page, return to the Configure Virtual Hosts section above and check that the
DocumentRootmatches yourexample.com/public_htmlfolder.If the page returned says “Index of /” or has a similar folder tree structure, create a test
index.htmlfile or a test file as shown above.
Congratulations! You have now set up and configured a LAMP stack on Ubuntu 18.04 (LTS).
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on