Install Magento 2, NGINX, PHP 7.2 and SSL on Ubuntu

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

Magento is an e-commerce platform built with PHP and it’s an open source technology which provides online merchants with a flexible shopping cart, content and functionality of their online store.

This tutorial demonstrates step by step how to manually install Magento 2, NGINX, PHP 7.2 and SSL on Ubuntu.

Prerequisites

Before starting with this guide, you’ll need to generate Magento authentication keys. If you don’t have a Magento Marketplace account, you can create one here. Once you create the account, please check these instructions on how to generate a new set of authentication keys.

For this tutorial, we will use lab.axfon.com as testing domain and the Ubuntu version is 18.10


Step 1: Install NGINX Web Server

Now we are going to install NGINX stable version by default repository Ubuntu, to do this type the command below:

sudo apt update && sudo apt install nginx

Once NGINX already installed, to check and verify Nginx service status type the command below

sudo service nginx status

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

 nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2019-02-04 00:19:58 UTC; 12s ago
     Docs: man:nginx(8)
  Process: 3095 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, stat
  Process: 3080 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exi
 Main PID: 3099 (nginx)
    Tasks: 2 (limit: 4399)
   Memory: 4.5M
   CGroup: /system.slice/nginx.service
           ├─3099 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─3100 nginx: worker process

To exit Nginx service status just press q on the keyboard


Step 2: 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 Nginx

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 'Nginx HTTP'

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
Nginx HTTP                 ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

Step 3: Testing NGINX on the Browser

NGINX 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 Nginx 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.nginx-debian.html

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

sudo service nginx reload

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


Step 3: Install PHP 7.2 FPM and Related Modules

When this tutorial made the PHP 7.2 is not yet available in Ubuntu default repositories, for installing it we have to add manually ondrej/php PPA by running the following command

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php

After adding the PPA we need to update Ubuntu, run the following command

sudo apt-get update

Once the PPA repository has been added and updated, now we are going to install PHP 7.2

sudo apt install php7.2-common php7.2-cli php7.2-fpm php7.2-opcache php7.2-gd php7.2-mysql php7.2-curl php7.2-intl php7.2-xsl php7.2-mbstring php7.2-zip php7.2-bcmath php7.2-soap

PHP-FPM service will automatically start after the installation process is complete, you can verify it by printing the service status

sudo systemctl status php7.2-fpm

You will be presented on the terminal screen as below

 php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2019-02-02 22:19:41 UTC; 1h 32min ago
     Docs: man:php-fpm7.2(8)
 Main PID: 10696 (php-fpm7.2)
   Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
    Tasks: 3 (limit: 4399)
   Memory: 15.1M
   CGroup: /system.slice/php7.2-fpm.service
           ├─10696 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf)
           ├─10715 php-fpm: pool www
           └─10717 php-fpm: pool www
Feb 02 22:19:41 axfon systemd[1]: Starting The PHP 7.2 FastCGI Process Manager...
Feb 02 22:19:41 axfon systemd[1]: Started The PHP 7.2 FastCGI Process Manager.

Step 4: Configure PHP file (Optional)

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, Follow the below steps to modify the PHP configuration file php.ini using the command line on Ubuntu.

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

To edit the configuration file your may 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

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


Step 5: 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 (Option 1)

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 database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2019-02-02 10:37:38 UTC; 11s ago
 Main PID: 31143 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 27 (limit: 665)
   Memory: 70.4M
   CGroup: /system.slice/mariadb.service
           └─31143 /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


Installing MySQL (Option 2)

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 Sat 2019-02-02 10:37:38 UTC; 11s 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 6: 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 9.1 Distrib 10.1.29-MariaDB, for debian-linux-gnu on x86_64
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Server version          10.1.29-MariaDB-6ubuntu2
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/run/mysqld/mysqld.sock
Uptime:                 24 min 27 sec
Threads: 1  Questions: 489  Slow queries: 0  Opens: 173  Flush tables: 1  Open tables: 30  Qu
eries per second avg: 0.333

Configured MySQL server on Ubuntu now is successful


Step 7: Create Database for Magento

At this step, Magento required Database to store data collection, to create a database run the commands below to login to the database server. When prompted for a password, type the root password you created above.

sudo mysql -u root -p

Then create a database name ex: “magento” for user “MAGENTOUSER” and for password “NEWPASSWORD”. Please attention you may change with anything else that you want. Let’s create a database called magento

CREATE DATABASE magento;

Creating a database user called MAGENTOUSER with NEWPASSWORD

CREATE USER 'MAGENTOUSER'@'localhost' IDENTIFIED BY 'NEWPASSWORD';

Then grant the user full access to the database.

GRANT ALL ON magento.* TO 'MAGENTOUSER'@'localhost' IDENTIFIED BY 'NEWPASSWORD' WITH GRANT OPTION;

Finally, save your changes and exit.

FLUSH PRIVILEGES; 
EXIT;

Step 8: Install Composer

Composer is a dependency manager for PHP and we will be using it to download the Magento core and install all necessary Magento components. To install composer globally, download the Composer installer with curl and move the file to the /usr/local/bin directory

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

For the next we need to Unzip for extracting the package, to install the unzip utility

sudo apt install unzip

Step 9: Install Magento 2

Start the installation by downloading Magento files to the default directory /var/www/html and create a new folder lab-axfon (Change it with your own name), just follow the command below for the easy way

sudo composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition /var/www/html/lab-axfon

You’ll be prompted to enter the access keys, copy the keys from your Magento marketplace account and store them in the auth.json file, so later when updating your installation you don’t have to add the same keys again.

Authentication required (repo.magento.com):
      Username: cf5e0a09388557182414e2d2ad663ee5
      Password: 0f57c43cba4276dbf37c245b48ccb3a3

After filling the Username and Password then Enter, it may take a few minutes to process and if it is successful at the end of the output should look like the following:

Writing lock file
Generating autoload files

Now go to the folder lab-axfon to Install Magento

cd /var/www/html/lab-axfon/

In this guide, we are going to install Magento using the command line. On the base URL use https for SSL certificate installation on the next step and change other value with your own

sudo bin/magento setup:install --base-url=https://lab.axfon.com/ \
        --base-url-secure=https://lab.axfon.com/ \
        --admin-firstname=YOUR_FIRST_NAME \
        --admin-lastname=YOUR_LAST_NAME \
        --admin-email=YOUR_EMAIL \
        --admin-user=USERNAME \
        --admin-password=YOUR_PASSWORD \
        --db-name=magento \
        --db-host=localhost \
        --db-user=MAGENTOUSER \
        --currency=USD \
        --timezone=America/Chicago \
        --use-rewrites=1 \
        --db-password=NEWPASSWORD

The process may take few minutes and once completed you will be presented with a message that contains the URI to the Magento admin dashboard.

[SUCCESS]: Magento installation complete.
[SUCCESS]: Magento Admin URI: /admin_3vpbmb
Nothing to import.

After running the commands above, a new project directory will be created. Run the commands below to set the correct permissions for that directory

sudo chown -R www-data:www-data /var/www/html/lab-axfon/
sudo chmod -R 755 /var/www/html/lab-axfon/

Step 10: NGINX Configuration

Finally, configure Nginx site configuration file for Magento 2. This file will control how users access Magento content. Run the commands below to create a new configuration

sudo nano /etc/nginx/sites-available/default

Then copy and paste the content below into the file and save it. Replace the highlighted line with your own domain name and directory root location.

server {
    listen 80;
    listen [::]:80;
    root /var/www/html/axfon-lab;
    index index.php index.html index.htm;
    server_name  example.com www.example.com;

    location / {
        try_files $uri $uri/ /index.php?$args;        
    }

    location ~ \.php$ {
         include snippets/fastcgi-php.conf;
         fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         include fastcgi_params;
    }

}

Cmd/Ctr X and Y to exit and save


Step 7: Install Let’s Encrypt Nginx Client

Let’s Encrypt is a free automated and open certificate authority for SSL(Secure Sockets Layer) just as secure as currently paid certificates. On this step we will configure an SSL certificate for Nginx on Ubuntu.

sudo apt-get install python-certbot-nginx

Then run the command below

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install python-certbot-nginx

Now generate certbot. Replace example.com with your own domain. If you want to use www prefix for your domain, you need to obtain a cert for that as well. Even if you’re only redirecting www.example.com to example.com, you will still need a separate cert for the www subdomain. Use -d to add even more domain or subdomain.

sudo certbot --nginx --agree-tos --email admin@example.com --redirect --hsts -d example.com -d www.example.com

The SSL client should installed and configure your website to redirect all traffic to HTTPS.

Congratulations! You have successfully enabled https://example.com and
https://www.example.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=example.com
https://www.ssllabs.com/ssltest/analyze.html?d=www.example.com
-------------------------------------------------------------------------------

IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/example.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/example.com/privkey.pem
   Your cert will expire on 2018-02-24. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Then you will see on file/etc/nginx/site-available/default site is ready to be used HTTPS with the Port 443.

server {
    listen 80;
    listen [::]:80;
    root /var/www/html/example.com;
    index  index.php index.html index.htm;
    server_name  example.com www.example.com;

     client_max_body_size 100M;

    location / {
        try_files $uri $uri/ /index.php?$args;        
    }

    location ~ \.php$ {
         include snippets/fastcgi-php.conf;
         fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
         include fastcgi_params;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    # Redirect non-https traffic to https
    # if ($scheme != "https") {
    #     return 301 https://$host$request_uri;
    # } # managed by Certbot
}

As Let’s Encrypt certs expire after 90 days, they need to be checked for renewal periodically. Certbot will automatically run twice a day and renew any certificate that is within thirty days of expiration.

sudo certbot renew --dry-run
sudo crontab -e

Then add the line below and save.

0 1 * * * /usr/bin/certbot renew & > /dev/null

Cmd/Ctr X and Y to exit and save


Step 13: Testing Magento 2 on the Browser

You can now view this page in your web browser by visiting your server’s domain name or public IP address http://your_domain_or_IP/


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