The LEMP stack (Linux, Nginx, MySQL, PHP) is an alternative to the LAMP stack (Linux, Apache, MySQL, PHP), with the primary difference being that LEMP uses Nginx for its web server, while LAMP uses Apache. Compared to Apache, Nginx is faster and more secure. This guide explains how to install the LEMP stack on an Ubuntu cloud server.
First, create a cloud server with Ubuntu 20.04 operating system, install Nginx, MariaDB, and PHP, and update the operating system to the latest version.
$ sudo apt install -y nginx mariadb-server php-fpm php-mysql
$ sudo apt update && sudo apt upgrade
Start by running the MariaDB/MySQL installation wizard. Set the root password through the wizard, leaving the other options at their default settings.
$ sudo mysql_secure_installation
Connect to MariaDB, create a test database named 'example_db', and set up a database username 'username' and password 'password'.
$ sudo mariadb
CREATE DATABASE example_db;
GRANT ALL ON example_db.* TO 'username'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit
Test the connection using the username and password, then create a table 'table1' and insert a record.
$ sudo mariadb -u username -p
SHOW DATABASES;
USE example_db;
CREATE TABLE table1(column1 varchar(255));
INSERT INTO table1 VALUES("Database connection established successfully");
exit
Create a directory for the website and assign appropriate ownership permissions. Replace 'example.com' with the actual domain name.
$ sudo mkdir -p /var/www/example.com
$ sudo chown -R $USER:$USER /var/www/example.com
Edit the site configuration file, replacing 'example.com' with the actual domain name.
$ sudo nano /etc/nginx/sites-available/example.com
Add the following code to the configuration file, also replacing 'example.com' with the actual domain name.
server {
listen 80;
listen [::]:80;
server_name www.example.com;
server_name example.com;
root /var/www/example.com;
location / {
index index.html;
}
}
Restart Nginx to apply the changes.
$ sudo systemctl restart nginx.service
Create a PHP test file in the website's root directory.
$ nano /var/www/example.com/testdb.php
Add the following code, substituting 'username' and 'password' with the previously configured MariaDB username and password.
<?php
$mysqli = new mysqli("localhost", "username", "password", "example_db");
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column1 FROM table1";
if($result = $mysqli->query($query)) {
while($row = $result->fetch_row()){
printf("%s\n", $row[0]);
}
$result->close();
}
$mysqli->close();
Finally, access 'http://example.com/testdb.php' in a browser. If there are no error messages, the LEMP platform on the Ubuntu cloud server is successfully configured.
23-02-2024 02:02:07
22-02-2024 03:19:32
22-02-2024 03:16:03
22-02-2024 03:14:03
22-02-2024 03:11:58