Magento 2 Cookbook

3.8 (4 reviews total)
By Ray Bogman , Vladimir Kerkhoff
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Installing Magento 2 on Apache and NGINX

About this book

Magento 2 is an open source e-commerce platform that has all the functionality to function from small to large online stores. It is preferred by developers and merchants due to its new architecture, which makes it possible to extend the functionalities with plugins, a lot of which are now created by the community.

This merchant and developer guide is packed with recipes that cover all aspects of Magento 2. The recipes start with simple how-to’s then delve into more advanced topics as the book progresses.

We start with the basics of setting up a Magento 2 project on Apache or Nginx. Next, you will learn about basics including system tools and caching to get your Magento 2 system ready for the real work. We move on to simple tasks such as managing your store and catalog configuration. When you are familiar with this, we cover more complex features such as module and extension development. Then we will jump to the final part: advanced Magento 2 extensions.

By the end of this book, you’ll be competent with all the development phases of Magento 2 and its most common elements.

Publication date:
March 2016
Publisher
Packt
Pages
342
ISBN
9781785887062

 

Chapter 1. Installing Magento 2 on Apache and NGINX

In this chapter, we will cover the basic tasks related to installing Magento 2 on Apache and NGINX. You will learn the following recipes:

  • Installing Apache

  • Installing NGINX

  • Installing PHP-FPM

  • Installing HHVM

  • Installing MySQL

  • Installing Magento 2

  • Installing Magento 2 on Hypernode

  • Managing Magento 2 on Docker

 

Introduction


This chapter explains how to install Magento 2 on a hosting environment. When installing a new Magento 2 instance, we can use either a Linux, Apache, MySQL, PHP (LAMP) or Linux, NGINX, MySQL, PHP (LEMP) setup. Currently, options such as MariaDB or HHVM are equivalent to MySQL or PHP. Only HHVM will be converted in this chapter.

We will install a clean Magento 2 setup on a hosted virtual private server (VPS) for more advanced users and an easy-to-use installation on Hypernode.

The recipes in this chapter will primarily focus on a basic setup of how to install Magento 2. However, in some situations, we will dive in deeper related to the subject.

While Magento requirements differ from Magento 1, we will be using the latest and finest version from PHP, HHVM, NGINX, Apache, Redis, MySQL, and Ubuntu.

Tip

Creating a new Magento 2 stack could bring up minor issues. Always update to the latest available version, if possible.

 

Installing Apache


Throughout the following recipes, we will install the latest Apache 2.4.x version on a Software as a Service (SaaS) platform hosted by DigitalOcean. The current Apache version supports HTTP/2. This recipe will show you how to do this.

Tip

HTTP/2 is an optimized version of the Hypertext Transfer Protocol (HTTP), also known as HTTP version 2 (HTTP/2). Some of the new features of HTTP/2 are a more efficient usage of network resources and network latency. HTTP/2 allows multiple concurrent connections over a single Transmission Control Protocol (TCP) connection at once, which optimizes TCP load. Merging CSS and JS is not necessary anymore. HTTP/2 service also provides the possibility to use server push, which allows a proactive push of resources to the client.

Getting ready

For this recipe, you will need to create an account at DigitalOcean https://www.digitalocean.com/. No other prerequisites are required.

How to do it...

For the purpose of this recipe, let's assume that we need to create an Apache hosting environment. The following steps will guide you through this:

  1. The first step is creating an account at https://cloud.digitalocean.com/registrations. All the steps to create an account are straightforward. Confirm your mail and update your billing profile.

  2. Start creating your first Droplet. Choose your hostname, and select your size (2GB CPU's or 40GB SSD Disk). Next, pick your region (DigitalOcean has many regions available worldwide). Select your image (we will use the latest Ubuntu). Select extra available settings such as Private Networking to run multiple servers including an Internet network or backup and IPv6 options. If you already have an SSH key, you can upload this:

  3. The Droplet takes approximately 60 seconds to get created. You will get an e-mail right after including all the additional login details such as the hostname, IP address, username, and password.

  4. Configure your domain name, yourdomain.com, to the addressed IP address from the Droplet:

    yourdomain.com    A    123.123.123.123
         www        CNAME   yourdomain.com
  5. Connect your Droplet with SSH using your favorite SSH client (putty or terminal) and change your password:

    sudo ssh yourdomain.com
    
  6. First, we will update your server to the latest updates available:

    apt-get update && apt-get -y upgrade
    
  7. Next, we will install Apache 2 using a third-party package. Currently, Ubuntu doesn't include the latest Apache 2.4.x with HTTP/2 support. The third-party vendor that we will use is https://launchpad.net/~ondrej/+archive/ubuntu/apache2. Run the following command:

    echo "deb http://ppa.launchpad.net/ondrej/apache2/ubuntu wily main" | sudo tee -a /etc/apt/sources.list.d/apache2.list
    echo "deb-src http://ppa.launchpad.net/ondrej/apache2/ubuntu wily main" | sudo tee -a /etc/apt/sources.list.d/apache2.list
    
  8. Before we can install Apache 2, we need to authorize the package by installing a signed key:

    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 0x4F4EA0AAE5267A6C
    
  9. Now, we will update our Ubuntu system using the latest Apache2 packages:

    apt-get update && apt-get -y install apache2
    
  10. Once every Apache 2 package is installed, we can check whether everything is in order by running the following command on the shell:

    apache2 -v
    

    The output of this command is as follows:

    [email protected]:~# apache2 -v
    Server version: Apache/2.4.17 (Ubuntu)
    

If you have followed steps 1 to 9, you will be able to see if the web server is running. Go to your favorite browser and search using your yourdomain.com.

Tip

In the DigitalOcean control panel, you can create multiple snapshots at all times during the recipes. This will help you in restoring an old version or just going back in time.

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 3, we create a clean hosting server setup using DigitalOcean. Next, we connect the Droplet IP to your domain name in DNS. After login via SSH, we are able to update the server and continue to the process of installing Apache 2 via a third-party repository. Depending on the Ubuntu setup, we need to change the version name, such as precise, trusty, wily, vivid, or xenial, to install the software.

In step 8, we submit a key that will validate the repository before we can start installing the Apache 2 software. In step 9, we use a simple command to update the repository and start installing.

There's more…

If you want to check whether Apache is running fine, use one of the following commands:

service apache2 status
netstat –anp | grep apache2
 

Installing NGINX


Throughout the following recipes, we will install the latest NGINX 1.9.x version on a SaaS platform hosted by DigitalOcean. The current NGINX version supports HTTP/2. This recipe will show you how to do it.

Getting ready

For this recipe, you will need to create an account at DigitalOcean https://www.digitalocean.com/. No other prerequisites are required.

Tip

For this cookbook, we will use a commercial SaaS hosting provider to get a production-ready environment. You can use any other solution out there to build on your preferred stack.

How to do it...

For the purpose of this recipe, let's assume that we need to create an NGINX hosting environment. The following steps will guide you through this:

  1. Follow steps 1 until 6 in the previous recipe on how to install Apache.

  2. Then, we will update our server to the latest updates available:

    apt-get update && apt-get -y upgrade
    
  3. Next, we will install NGINX using the latest mainline version 1.9.x. Currently, Ubuntu doesn't include the latest NGINX 1.9.x mainline version. The latest change log can be viewed at http://nginx.org/en/CHANGES. Run the following command:

    echo "deb http://nginx.org/packages/mainline/ubuntu/ wily nginx" | sudo tee -a /etc/apt/sources.list.d/nginx.list
    echo "deb-src http://nginx.org/packages/mainline/ubuntu/ wily nginx" | sudo tee -a /etc/apt/sources.list.d/nginx.list
    
  4. Before we can install NGINX, we need to authorize the package by installing a signed key:

    wget http://nginx.org/keys/nginx_signing.key | apt-key add nginx_signing.key
    
  5. Now, we will update our Ubuntu system using the latest NGINX packages:

    apt-get update && apt-get -y install nginx
    
  6. Once every NGINX package is installed, we can check whether everything is in order by running the following command on the shell:

    nginx -v
    

    The output of this command is as follows:

    [email protected]:~# nginx -v
    nginx version: nginx/1.9.6
    

If you have followed steps 1 to 6, you will be able to see if the web server is running. Go to your favorite browser and search using your yourdomain.com.

Tip

In the DigitalOcean control panel, you can create multiple snapshots at all times during the recipes. This will help you in restoring an old version or just going back in time, such as switching from Apache to NGINX or back.

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 5, we used the same Droplet to install NGINX. All steps are alike, but instead of installing Apache, we use NGINX instead. The only big difference is that it is an official NGINX repository.

There's more…

The current market share of NGINX is around 15% worldwide compared to 50% of Apache on active sites. Over the last couple of years, NGINX has grown and is commonly used as a stable web server for Magento hosting:

http://news.netcraft.com/archives/2015/03/19/march-2015-web-server-survey.html

If you want to check whether NGINX is running fine, use one of the following commands:

service nginx status
netstat -anp | grep nginx
 

Installing PHP-FPM


Throughout the following recipes, we will install the latest PHP 7.x version on Apache and NGINX. The current PHP-FastCGI Process Manager (PHP-FPM) will be installed through a third-party package. This recipe will show you how to do it.

Tip

PHP 7 is the latest version of the PHP stack. It's also known as PHP Next Generation (PHP NG) and PHP's answer to HHVM. Currently, it's two to three times faster than PHP 5.x.

The whole code base is rewritten and uses less memory. Lots of PHP functions are backward-compatible with the PHP 5.x code base, so upgrading to PHP 7 should be easy.

Getting ready

For this recipe, you will need a preinstalled Apache or NGINX setup. No other prerequisites are required.

How to do it...

For the purpose of this recipe, let's assume that we need to create an PHP-FPM hosting environment. The following steps will guide you through this:

  1. First, we will start installing PHP-FPM on Apache; later, we will do the same with NGINX.

  2. Next, we will install PHP 7 on Apache 2 using a third-party package. Currently, Ubuntu doesn't include the latest PHP 7 yet. The third-party vendor that we will use is https://launchpad.net/~ondrej/+archive/ubuntu/php.

    Run the following command:

    echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu wily main" | sudo tee -a /etc/apt/sources.list.d/php.list
    echo "deb-src http://ppa.launchpad.net/ondrej/php/ubuntu wily main" | sudo tee -a /etc/apt/sources.list.d/php.list
    
  3. As we have already used the authorized Apache package from the same vendor, we are okay on the signed key. There is no need to install the key anymore.

  4. Now, we will update our Ubuntu system using the latest PHP 7 packages:

    apt-get update && apt-get -y install php7.0 php7.0-fpm php7.0-dev php7.0-mhash php7.0-mcrypt php7.0-curl php7.0-cli php7.0-mysql php7.0-gd php7.0-intl php7.0-xsl
    
  5. Once every PHP 7 package is installed, we can check whether everything is in order by running the following command on the shell:

    php -v
    

    The output of this command is as follows:

    [email protected]:/etc/php# php -v
    PHP 7.0.0 (cli) ( NTS )
    Copyright (c) 1997-2015 The PHP Group
    Zend Engine v3.0.0-dev, Copyright (c) 1998-2015 Zend Technologies
    
  6. Now, we will configure PHP-PFM with Apache. Out of the box, Apache 2 comes with a module named mod_proxy, which we will use to connect Apache to PHP-FPM. We will be using PHP-FPM in TCP mode instead of the Unix socket. The main reason is that it's easy to configure and we can use it later with HHVM. The default port 9000 will be our connector. To enable mod_proxy, run the following command on the shell:

    a2enmod proxy_fcgi
    
  7. Before we can connect Apache to PHP-FPM, we need to give PHP-FPM instructions to listen to the correct internal port. Run the following command from the shell:

    sed -i "s/listen =.*/listen = 127.0.0.1:9000/" /etc/php/7.0/fpm/pool.d/www.conf
    

    You can do this manually as well; edit the www.conf file with your favorite editor in your PHP-FPM pool directory. Search for listen = /var/run/php/php7.0-fpm.sock and change this to listen = 127.0.0.1:9000.

  8. Restart your PHP-FPM process to use the altered changes. Run the following command from the shell:

    service php7.0-fpm restart
    
  9. Next, we need to configure Apache using the currently set-up internal proxy_fcgi module. The default Apache Virtual Host configuration file is located at /etc/apache2/sites-enabled/000-default.conf. Edit this file and add the following code just before the closing </VirtualHost> tag on one line without any breaks:

    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1

    The following code is for the new 000-default.conf:

    <VirtualHost *:80>
    ServerAdmin [email protected]
    DocumentRoot /var/www/html
    <Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    allow from all
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    
    ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1
    </VirtualHost>

    You can change DocumentRoot /var/www/html to any given preferred directory. However, for the rest of the recipes, we will stay with the default.

  10. After saving the Apache configuration, we need to restart the web server. Run the following command from the shell:

    service apache2 restart
    
  11. Now, we need to check whether Apache and PHP-FPM are working fine. Go to the cd /var/www/html directory and create the following file including content:

    echo "<?php phpinfo(); ?>" > phpinfo.php
    
  12. If you have followed steps 1 to 11, you will be able to see if PHP-FPM works with your web server. Go to your favorite browser and search using your yourdomain.com/phpinfo.php.

    You should now see a phpinfo page like the following screenshot. Check on the second line for the Server API; this should be FPM/FastCGI.

    If everything is working fine, we have completed the Apache PHP-FPM setup. Now let's do the same for the NGINX and PHP-FPM setup.

    As we have already installed the PHP-FPM packages in steps 1 to 5, we now need to combine them with NGINX.

    Before we continue, it is important to use either a clean DigitalOcean Droplet with NGINX running or you can disable the Apache server using the following command form the shell:

    service apache2 stop && service nginx start
    
  13. Next, we need to configure NGINX. The default NGINX configuration file is located at /etc/nginx/conf.d/default.conf. Remove the old configuration in this file and add the following code:

    server {
      listen       80;
      server_name  yourdomain.com;
    
      root   /var/www/html;
      index  index.php index.html;
    
      access_log /var/log/nginx/access.log;
      error_log /var/log/nginx/error.log;
    
      location ~ \.php$ {
    
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
      }
    
      location ~ /\.ht {
        deny  all;
      }
    }
  14. Save the new configuration using your favorite editor and restart your NGINX and PHP-PFM server using the following command on the shell:

    service nginx restart && service php7.0-fpm restart
    

    A nice trick to test if your configuration is correct is as follows:

    nginx –t
    

If you have followed steps 13 to 14, you will be able to see if PHP-FPM works with your web server. Go to your favorite browser and search using your yourdomain.com/phpinfo.php.

You should now see a phpinfo page similar to the one on the previous page during the Apache PHP-FPM setup. Check on the second line for the Server API; this should be FPM/FastCGI.

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 4, we first install PHP-FPM from a third-party repository. The main reason that we use this repository is that it is easy to use and well-supported. Current Ubuntu versions don't have the latest PHP 7 available yet. If you are comfortable installing PHP from source, you can do so.

All PHP modules listed in step 4 are mandatory for Magento 2 to work properly. In step 6, we explain why we use PHP-FPM running on port 9000. Setting up a TCP port is much easier when using multiple PHP backends, switching from Apache to NGINX, or PHP-FPM versus HHVM.

In step 7, we add an Apache module that acts as a proxy, so we are able to connect PHP-FPM to Apache.

In step 8, we changed the PHP-FPM pool to switch from Unix sockets to TCP. If you prefer sockets, you can do so.

In step 10, we add the ProxyPassMatch rule to our Apache configuration file, which will serve all incoming PHP requests to the PHP-FPM server. After saving and restarting the Apache server, we are able to test if everything works.

In step 13, we configure NGINX to work with PHP-PFM. Creating fastcgi_pass does the trick to connect to port 9000.

There's more…

If you want to check whether PHP-FPM is running fine, use one of the following commands:

service php7.0-fpm status
netstat -anp | grep php-fpm

To check which server is running, check the headers by running the following command:

curl -I http://mage2cookbook.com/phpinfo.php

The output of this command will be as follows:

[email protected]:~# curl -I http://mage2cookbook.com/phpinfo.php
HTTP/1.1 200 OK
Server: nginx/1.9.6

Once we switch back to Apache we will see the following:

service nginx stop && service apache2 start
[email protected]:~# curl -I http://mage2cookbook.com/phpinfo.php
HTTP/1.1 200 OK
Server: Apache/2.4.17 (Ubuntu)

Tip

Use phpinfo.php wisely on a production environment. Sharing this information on a production website is not advised and could expose your security risks.

 

Installing HHVM


Throughout the following recipes, we will install the latest HHVM 3.9.x version on Apache and NGINX. HHVM has gained large popularity over the last couple of year and is well-known for its high performance on Magento. While Magento 1 was not supported by default, Magento 2 is. This recipe will show you how to do it.

Tip

HHVM (also known as the HipHop Virtual Machine) is a virtual machine for PHP developed by Facebook, with an associated just-in-time (JIT) compiler.

Deploying HHVM on a Magento 2 website should lead to performance improvements across your web shop.

Getting ready

For this recipe, you will need a preinstalled Apache or NGINX setup. No other prerequisites are required.

How to do it...

For the purpose of this recipe, let's assume that we need to create an HHVM hosting environment. The following steps will guide you through this:

  1. First, we will start installing HHVM on Apache; later, we will do the same with NGINX.

  2. Next, we will install HHVM on Apache2 using the official prebuilt package by Facebook. Run the following command on the shell:

    echo "deb http://dl.hhvm.com/ubuntu wily main" | sudo tee -a /etc/apt/sources.list.d/hhvm.list
    
  3. Before we can install HHVM, we need to authorize the package by installing a signed key:

    apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 0x5a16e7281be7a449
    
  4. Now we will update our Ubuntu system using the latest HHVM packages:

    apt-get update && apt-get -y install hhvm
    
  5. Once every HHVM package is installed, we can check whether everything is in order by running the following command on the shell:

    hhvm --version
    

    The output of this command is as follows:

    [email protected]:~# hhvm --version
    HipHop VM 3.10.1 (rel)
    
  6. Since the setup of PHP-FPM, we have started using the internal port 9000 to handle all traffic on PHP. Now we will use the same port for HHVM. Stop PHP-FPM as it is still running and start HHVM using the following command from the shell:

    service php7.0-fpm stop && service hhvm start
    
  7. If you need to run dedicated HipHop code such as Hack (the default HipHop programming language) in the future, you may want to change your Apache configuration. Restart your Apache and HHVM server:

    ProxyPassMatch ^/(.+\.(hh|php)(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1
    
  8. Now, let's check whether HHVM and Apache are working. Create a PHP file called hhvm.php in the /var/www/html directory:

    <?php
    if (defined('HHVM_VERSION')) {
      echo "HHVM";
    } else {
      echo "PHP";
    }

    If you have followed steps 1 to 8, you will be able to see if HHVM works with your web server. Go to your favorite browser and search using your yourdomain.com/hhvm.php. You should now see a HHVM notice on your screen.

    In newer versions of HHVM, the default phpinfo(); tag works just fine on your screen. Go to your favorite browser and search using your yourdomain.com/phpinfo.php:

  9. If everything is working fine, we have completed the Apache HHVM setup. Now let's do the same for the NGINX and HHVM setup.

    As we have already installed the HHVM packages in steps 1 to 5, we now need to combine them with NGINX.

  10. Before we continue, it is important to use either a clean DigitalOcean Droplet with NGINX running or you can disable the Apache server using the following command from the shell:

    service apache2 stop && service nginx start
    

    The following is the content of NGINX configuration file:

    server {
      listen       80;
      server_name  yourdomain.com;
    
      root   /var/www/html;
      index  index.php index.html;
    
      access_log /var/log/nginx/access.log;
      error_log /var/log/nginx/error.log;
    
      location ~ \.(hh|php)$ {
    
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
      }
    
      location ~ /\.ht {
        deny  all;
      }
    }

    In the preceding example, we altered the location for PHP and Hack support:

    location ~ \.(hh|php)$ {
  11. You can now restart your NGINX and HHVM server to connect them using the follow command from the shell:

    service nginx restart && service hhvm restart
    
  12. Now let's check whether HHVM and NGINX are working. Create a PHP file called hhvm.php or use the one in the previous Apache HHVM setup in the /var/www/html directory:

    <?php
    if (defined('HHVM_VERSION')) {
      echo "HHVM";
    } else {
      echo "PHP";
    }

If you have followed steps 9 to 11, you will be able to see if HHVM works with your web server. Go to your favorite browser and search using your yourdomain.com/hhvm.php.

You should now see a HHVM notice on your screen, but you can also use yourdomain.com/phpinfo.php.

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 4, we use the official HHVM repository and install the software. The installation process is similar to the PHP-FPM setup. The important difference between HHVM and PHP-FPM is that HHVM does not have additional modules to install.

In step 7, we change ProxyPassMatch a little bit, and add the .hh extension parameter only. By default, the .hh extension is used only when creating HipHop (Hack)-dedicated code.

In step 10, we do the same procedure for NGINX. The only thing that we change is the .hh extension in the location. As HHVM runs by default on port 9000, we do not change anything here.

There's more…

If you want to check whether HHVM is running fine, use one of the following commands:

service hhvm status
netstat -anp | grep hhvm

To check which server is running, check the headers by running the following command:

curl -I http://mage2cookbook.com/hhvm.php

The output of this command is as follows:

[email protected]:~# curl -I http://mage2cookbook.com/hhvm.php
HTTP/1.1 200 OK
Server: nginx/1.9.6
X-Powered-By: HHVM/3.10.1

Once we switch back to Apache, we will see the following:

service nginx stop && service apache2 start
[email protected]:~# curl -I http://mage2cookbook.com/hhvm.php
HTTP/1.1 200 OK
Server: Apache/2.4.17 (Ubuntu)
X-Powered-By: HHVM/3.10.1
 

Installing MySQL


Throughout the following recipes, we will install the latest MySQL 5.7.x version on Apache and NGINX. The current MySQL version is a milestone in the open source world. Its new performance and scalability features will be a great benefit for every Magento website. This recipe will show you how to do it.

Tip

MySQL 5.7 is an extremely exciting new version of the world's most popular open source database, which is two times faster than MySQL 5.6 while also improving usability, manageability, and security.

Getting ready

For this recipe, you will need a preinstalled Apache or NGINX and PHP-FPM or HHVM setup. No other prerequisites are required.

How to do it...

Before we can install the latest MySQL version, we need to download the software in our local system. The official MySQL APT repository provides you with a simple and convenient way to install and update MySQL products. Always use the latest software package using apt-get.

  1. We will now install MySQL using the official vendor package. Run the following command from your root or home directory:

    wget http://dev.mysql.com/get/mysql-apt-config_0.5.3-1_all.deb
    
  2. To download the rest of the latest MySQL package, we first install the mysql-apt-config package. Run the following command:

    dpkg -i mysql-apt-config_0.5.3-1_all.deb
    

    During installation, it will ask which MySQL product you wish to configure. Select Server:

    Next, it will ask which Server version you wish to receive. Select mysql-5.7:

    In the next screen, click on Apply:

  3. Now, we will update our Ubuntu system using the latest MySQL packages:

    apt-get update && apt-get -y install mysql-server
    
  4. During installation, it will ask you several questions. The first one will be to choose a new password for the MySQL root user. Always make sure to create a new dedicated user only for a database; using root is just an example and not advised on production.

  5. Once every MySQL package is installed, we can check whether everything is in order by running the following command on the shell:

    mysql --version
    

    The output of this command is as follows:

    [email protected]:~# mysql --version
    mysql  Ver 14.14 Distrib 5.7.9, for Linux (x86_64)
    

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 3, we download the official MySQL package and use a graphical interface to install the latest version. The whole process is pretty straightforward. Remember to use a dedicated user that has all the privileges instead of the root user.

There's more…

If you want to check whether MySQL is running fine, use one of the following commands:

service mysql status
netstat -anp | grep mysql

After the MySQL server installation is finished, you can log in on the shell using the following command:

mysql -u root -p
 

Installing Magento 2


Throughout the following recipes, we will install Magento 2 on a preconfigured SaaS platform hosted by DigitalOcean. Installing Magento 2 differs a lot from the current Magento 1 version. An important change is the use of Composer. We will use Composer to install all the third-party modules and manage the core of Magento 2. This recipe will show you how to do it.

Tip

Composer is a dependency management tool for PHP. It allows you to declare the software libraries for your project. It will help you install or update them.

Getting ready

For this recipe, you will need a preinstalled Apache or NGINX, PHP or HHVM and MySQL setup. No other prerequisites are required.

How to do it...

For the purpose of this recipe, let's assume that we need to create a Magento 2 hosting environment. The following steps will guide you through this:

  1. First, we will start installing Magento 2 on Apache; later, we will do the same with NGINX. Throughout this recipe, you can use PHP-FPM or HHVM. For now, we will focus only on PHP-FPM.

  2. Installing Composer is pretty straightforward. For the rest of the recipes, we will be installing Composer in the /usr/local/bin directory. This way, we can use it system-wide. Run the following command on the shell in the /usr/local/bin directory:

    curl -sS https://getcomposer.org/installer | php
    

    If you have not installed curl yet, you may need to run the following command on the shell:

    apt-get -y install curl
    

    To check whether Composer is working fine, run the following command:

    mv composer.phar composer
    ./composer
    

    You will get the following output:

    While we will be using a search-friendly URL in Magento, we need to enable the Apache mod_rewrite module before we can continue. Run the following code on the shell:

    a2enmod rewrite
    

    Restart your Apache server to complete the new configuration. Run the following code on the shell:

    service apache2 restart
    

    If you see the following output on your screen, everything is correct:

    [email protected]:/var/www/html# a2enmod rewrite
    Enabling module rewrite.
    To activate the new configuration, you need to run:
    service apache2 restart
    

    Note

    Installing Magento 2 can be done in several ways. First, we will be showing you how to install it using the latest version from the GitHub release branch. Download the complete package and unzip or untar the files in your /var/www/html directory.

    The URL for the latest releases is https://github.com/magento/magento2/releases.

    Make sure that your /var/www/html has no files in it anymore. (Use the rm * command to clean up.)

    Execute either of the following commands:

    wget https://github.com/magento/magento2/archive/2.0.0.zip
    wget https://github.com/magento/magento2/archive/2.0.0.tar.gz
    

    While extracting your files, make sure to move or copy them in to the /var/www/html directory.

  3. Now let's set the ownership and permissions:

    chown -R www-data:www-data /var/www/html
    find . -type d -exec chmod 770 {} \; && find . -type f -exec chmod 660 {} \; && chmod u+x bin/magento
    
  4. Now we use Composer to resolve all of our dependencies. Run the following command on the shell:

    cd /var/www/html/ && composer install
    

    Tip

    If your installation is set up correctly, the installation will continue, using the correct PHP modules. However, if, in some way, your PHP installing is not correct, you may get the following error messages. Update your system and try again:

    Your requirements could not be resolved to an installable set of packages.

    Problem 1

        - The requested PHP extension ext-gd * is missing from your system.
    

    Problem 2

        - The requested PHP extension ext-curl * is missing from your system.
    

    Problem 3

        - The requested PHP extension ext-intl * is missing from your system.
    
  5. During the installation process, you will get a notice to create a GitHub OAuth token. The download rate limit is pretty small. Copy the URL from your shell window in your browser, log in at GitHub, or create an account and token:

    Copy the generated token in the command prompt of your current shell window and the token will be saved for future reference in /root/.composer/auth.json. You can continue the rest of the installation.

  6. Next, we will be using the setup wizard to continue the rest of the installation. In Chapter 2, Magento 2 System Tools, we will be using the shell installation method. Go to your favorite browser and run the following URL:

    http://mage2cookbook.com/setup

    As a result, we will get the following screen:

  7. Now click on Agree and Setup Magento.

  8. Let's start analyzing the readiness of your setup. Click on the Next button:

  9. Magento 2 now will check your hosting setup for the correct PHP version, PHP modules, PHP settings, and file permissions, as shown in the following screenshot:

  10. Continue the installation flow and commit your database credentials in the following screen:

  11. In Step 3, we will set up our store address and administrator address. In Advanced Options, we are able to pick HTTPS, Apache rewrites, encryption key, and where to store the session key:

    Step 4 gives you the opportunity to choose your time zone, currency, and language. In Magento 2, there is a brand new option to pick which modules need to be installed. You can easily select them by just clicking the checkbox, as shown in the following screenshot:

  12. In Step 5, you can choose your username and password:

  13. Now we are almost there; the final Step 6 will start installing our Magento 2 environment:

    The installation step is really fast in Magento 2 and is done within a minute depending on your server. If you get an error in the console screen, such as a missing database, create one via the shell with the following command:

    mysql –u root –p
    create database magento;
    

    Installation of Magento 2 can be seen in the following screenshot:

  14. Congratulations, you have successfully installed Magento 2. You will be given administrative information on your login and store address.

    For security reasons, you may want to alter the write permissions of your /app/etc directory to only read permissions with the following command:

    chmod -R 440 /var/www/html/app/etc
    

    Now we will focus on the configuration of Magento 2 on NGINX. We don't need to reinstall Magento 2; we just need to alter the current NGINX setup with the appropriate setting.

  15. Now, let's go to the NGINX configuration directory and update default.conf in /etc/nginx/conf.d. Open the default.conf file and change it with the following settings:

    upstream fastcgi_backend {
      server  127.0.0.1:9000;
    }
    server {
      listen       80;
      server_name  yourdomain.com;
    
      set $MAGE_ROOT /var/www/html;
      set $MAGE_MODE developer;
    
      include /var/www/html/nginx.conf.sample;
    
      access_log /var/log/nginx/access.log;
      error_log /var/log/nginx/error.log;
    
      location ~ /\.ht {
        deny  all;
      }
    }

    As you can see, we are now using an upstream and set $MAGE setting and have removed the fastcgi_pass.

    However, the most important element is the Magento 2 nginx.conf.sample file, which is in the root directory of your Magento 2 instance. For now, it is easy to include this directory but not advised on a production level. It's best that you copy this file to your NGINX configuration directory and store it there. Don't forget to change the following setting:

    include /var/www/html/nginx.conf.sample;
  16. Save your configuration and run the following command to check whether your settings are correct. If not, change your configuration:

    nginx -t
    
  17. If your syntax is okay and the test is successful, then restart your NGINX server. Don't forget to stop your Apache server. Run the following command on the shell:

    service apache2 stop && service nginx start
    

    To check whether you are running NGINX, use the following command:

    curl -I http://mage2cookbook.com/
    [email protected]:~# curl -I http://mage2cookbook.com/HTTP/1.1 200 OKServer: nginx/1.9.6
    
  18. Congratulations, you just finished the installation of Magento 2 on NGINX.

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 and 2, we install Composer. Composer is our most important element before we can start installing Magento 2. As we are using Apache, we need to enable the mod_rewrite module, which is mandatory in Magento 2. Next, we download the latest Magento 2 version from GitHub and unzip the code in our directory.

In step 4, we check whether our setup is resolving all dependencies. Depending on the outcome, we need to install or enable the additional PHP modules.

In step 5, we create a GitHub token and store it in the auth.json file. We need this because the download rate limit is small when downloading additional software dependencies.

In step 6, we use the Magento 2 setup directory to install via the graphical user interface. All the remaining steps till 12 are self-explanatory.

In step 14, we switch from Apache to NGINX. The configuration file contains the following important elements: nginx.conf.sample, upstream fastcgi_backend, and $MAGE to finish our setup. The upstream parameter makes sure that all PHP requests are connected to PHP-FPM, the $MAGE variable connects the web directory, and include refers to the master configuration file.

There's more…

If you want to check which Apache modules are enabled, use the following command:

apachectl -M

The equivalent for NGINX to check your modules is nginx -V.

 

Installing Magento 2 on Hypernode


Throughout the following recipes, we will install Magento 2 on a fully managed platform hosted by Hypernode. Hypernode is an advanced platform for successful Magento shops.

Hypernode is a radically different approach to Magento hosting that actively improves your shop's performance. Its unique Magento platform is developed by Byte Internet, a Dutch hoster with eight years of experience in hosting Magento.

Hypernode has been developed in close consultation with Magento developers, with the objective of having Magento web shops perform to the best advantage and make its development several times easier. This recipe will show you how to do it.

Tip

With Hypernode, you will get your own fully managed isolated cloud server. This server has been fully configured for Magento 2. The best and latest software such as NGINX, HHVM, PHP-FPM, Redis, and MySQL are installed as a standard. In addition, they offer all the tools that you, as a Magento developer, would need in order to work comfortably: New Relic, Git, Vagrant, and Magento-specific tools such as ModMan, N98 Magerun, Sphinx Search, and much more.

The following image illustrates working of Hypernode which can be found at https://www.hypernode.com/:

Getting ready

For this recipe, you will need to create an account at Hypernode https://www.hypernode.com/. No other prerequisites are required.

How to do it...

For the purpose of this recipe, let's assume that we need to create a Magento 2 hosting environment on the Hypernode platform. The following steps will guide you through this:

  1. First, we start by creating a user account for Hypernode.

    There are two options to create a Hypernode.

    The first option is a default clean Magento 2 setup using the link, https://auth.byte.nl/account/register/magento2, and committing your name, e-mail, company name, and so on. For the following steps, make sure to submit the correct cell number. You will get a text message to confirm that this account is valid and not spam. Now perform steps 2 through 9 to set up Magento 2 the easy way.

    If you want to start using Magento 1 before switching to Magento 2, then follow all of the steps until step 11. To do so, use the link, https://auth.byte.nl/account/register/hypernode/, and commit your name, e-mail, company name, and so on. For the following steps, make sure to submit the correct cell number. You will get a text message to confirm that this account is valid and not spam.

  2. Now, open up your mail account, and confirm the e-mail that you received from Byte Internet. Next, you will be prompted with a text message on your cell phone; commit the code to continue. Make sure to pick a password for the Hypernode control panel, which we will use later.

  3. Next, commit your domain name, or any other name that will relate to this setup. The name will be used to create a subdomain on the Hypernode. The name could be called yourdomain.hypernode.io.

  4. After submitting your domain name, creating the Hypernode will take between 20-30 minutes, or less. All current Hypernodes are created on the same hosting platform that we used before at DigitalOcean. The difference between this setup for Magento 2 is that it is a managed setup. So we don't need to configure PHP, MySQL, NGINX, and so on.

  5. Now go to the Hypernode control panel to check the current status on the creation of the Hypernode. Go to https://service.byte.nl.

  6. Click on your domain name and then click on Hypernode settings in the control panel. Here, you will find the current status and health of your setup:

  7. Next, we need to set up an SSH key to log in via SSH. By default, this is the only way to log in. Go to https://service.byte.nl/sshkeymanager/ and submit your personal key or create a new pair. It will take less than 10 minutes to auto-submit this to your Hypernode.

  8. Now you can log in to the Hypernode via the shell. The hostname is the same as your domain name, which we had set up in the beginning. The username is always app. The example should look as follows:

  9. If everything worked out fine, you should now have access to the Hypernode on http://yourdomain.hypernode.io.

  10. By default, the current Hypernode setup has a Magento 1 preinstalled setup. We will now switch to Magento 2 using the following commands via the shell:

    n98-magerun --root-dir=/data/web/public uninstall --installationFolder=/data/web/public –force
    
    touch ~/nginx/magento2.flag
    mkdir ~/magento2
    cd ~/magento2
    
    wget -qO- https://magento.mirror.hypernode.com/releases/magento2-latest.tar.gz | tar xfz –
    
    echo "create database magento2" | mysql
    chmod 755 bin/magento
    cat ~/.my.cnf
    
    bin/magento setup:install --db-host=[HOSTNAME]   --dbname=[DATABASE] --db-user=app   --db-password=[DATABASE_PASSWORD]   --admin-firstname=[YOURFIRSTNAME]   --admin-lastname=[YOURSURNAME] --admin-user=[ADMINNAME]   --admin-password=[ADMINPASSWORD]   --adminemail=[[email protected]]   --base-url=[YOUR.HYPERNODE.IO] --language=[en_US]   --timezone=[Europe/Berlin] --currency=[EUR]   --use-rewrites=1
    
    rm -rf ~/public
    mkdir ~/public
    cd ~/magento2
    ln -fs ../magento2/pub/* ../public
    

    The detailed instructions can also be found on the Hypernode knowledge base, https://support.hypernode.com/knowledgebase/installing-magento-2-on-hypernode/. This also includes a small tutorial regarding a sample data setup.

  11. Now open your browser and go to your domain name to check whether everything is working correctly.

  12. Congratulations, you just finished configuring Magento 2 on Hypernode.

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 4, we create a new Hypernode account at https://www.byte.nl/. These steps will create a new Byte customer that stores a reference to the Hypernode. The Hypernode is auto-created in the background on DigitalOcean. During the whole process, you will get multiple mails for validation and additional account information regarding the Hypernode logins.

In steps 5 through 11, we need to switch from the default Magento 1 preinstalled setup to Magento 2. All setups are self-explanatory and result in a clean Magento 2 setup located on a managed hosting platform and ready for production.

There's more…

Hypernode provides you with a large set of tools useful for your Magento setup. Check your service panel for the latest tools and links available. Here is a small section of some useful links:

https://yourdomain.hypernode.io/phpmyadmin/

https://support.hypernode.com/knowledgebase_category/getting-started/

https://support.hypernode.com/knowledgebase/configure-redis/

https://support.hypernode.com/knowledgebase/varnish-on-hypernode/

 

Managing Magento 2 on Docker


Docker is a new way of packaging your application and building containers for every single process. It is very lightweight and easy to set up. Creating building blocks for Apache, NGINX, MySQL, PHP, HHVM, and Magento individually and running them together can save lots of time during development, testing, and production.

In this recipe, we will not cover the Docker fundamentals but learn how to run a Magento 2 Docker setup on your DigitalOcean Droplet using existing containers.

Getting ready

Before we can start using Magento 2 on Docker, we need to create a clean Droplet. Back up your current Droplet by creating a snapshot. Here are some easy steps to create a snapshot and start a new Droplet with Docker preinstalled:

  1. Power off your current Droplet in the DigitalOcean control panel.

  2. Select Take Snapshot and choose a name. (This may take some time depending on how big your current environment is.)

  3. Select Rebuild Droplet, which is in the Destroy menu, choose Ubuntu docker (1.9.1 on 14.04), and press Rebuild from Image.

How to do it…

For the purpose of this recipe, let's assume that we need to create a Magento 2 Docker setup. The following steps will guide you through this:

  1. Log in to your Docker Droplet. You can check your current Docker version with the following command:

    docker -version
    
  2. Before we start pulling the Magento 2 Docker container, we first need to pull a MySQL container. Run the following command in your shell:

    docker run -d --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=admin mysql:5.6
    

    The Docker run command will automatically download a MySQL 5.6 container, which will run in the background once it's done.

  3. Now we can check whether the MySQL container works. Run the dockers images command, and then check which images are available. If you want to log in to the container, run the following command:

    docker exec -it mysql bash
    

    You can run any other command here, and then check whether MySQL is running. For example, run the ps --aux command and you will see the process of MySQL.

  4. Now we start pulling the Magento 2 Docker container to our local machine. We are using a prebuilt Docker container hosted at the Docker hub (https://hub.docker.com/u/raybogman/).

    Run the following command to install a clean Magento 2 setup:

    docker run --rm --name magento2 -it -p 80:80 --link mysql:mysql -e MYSQL_USER=root -e MYSQL_PASSWORD=admin -e PUBLIC_HOST=
    yourdomain.com raybogman/mage2cookbook-docker $*
    

    Run the following command to install a Magento 2 setup including sample data:

    docker run --rm --name magento2 -it -p 80:80 --link mysql:mysql -e MYSQL_USER=root -e MYSQL_PASSWORD=admin -e PUBLIC_HOST=yourdomain.com raybogman/mage2cookbook-sample-docker $*
    

    Change the PUBLIC_HOST setting with your own IP or domain name. The SampleData version has all of its assets to create a preinstalled Magento 2 setup.

  5. Be patient now; this may take some time. The latest Magento 2 container is downloaded and executed on the fly. The final phase is the execution of Apache that will run in the foreground.

  6. Now open your browser and, depending on your public IP or domain name, execute this.

  7. Now we can check whether the Magento 2 container works. Run the dockers images command, and then check which images are available. If you want to log in to the container, run the following command:

    docker exec -it magento2 bash
    

    You can run any other command here, and then check whether Apache 2 is running. For example, run the ps --aux command and you will see the process of Apache 2. All Magento 2 files are located at /var/www/magento2.

  8. Congratulations, you have Magento 2 running using a Docker container. The login credentials are the Magento username (admin), password (password123), and backend URL (http://yourdomain.com/admin).

How it works…

Let's recap and find out what we did throughout this recipe. In steps 1 through 8, we create a Docker setup for Magento 2.

In steps 2 and 3, we set up a MySQL container that will be downloaded automatically and run in the background.

In step 4, we download the prebuilt Magento 2 Docker container and connect it to the MySQL container. The installation process can take some time; Magento needs to deploy the whole setup.

In step 7, you learn how to get shell access to the Magento container and maintain it.

There's more…

To kill/shut down the current Magento 2 container, use the Ctrl + C command in the running shell.

This Magento 2 Docker container is designed only for demo purposes, and is there to run in the foreground and not as a daemon in the background.

Check out the source code of the Magento 2 Docker container on GitHub:

https://github.com/mage2cookbook.

Some basic commands to use Docker are as follows:

docker ps

Docker running containers

docker images

Docker local containers

docker exec -it bash

Access to running container shell

docker rm -f $(docker ps -a -q)

Remove all running containers

docker rmi -f $(docker images -q)

Remove all containers

About the Authors

  • Ray Bogman

    Ray Bergman is an IT professional and Magento evangelist from the Netherlands. He started working with computers in 1983, as a hobby at first. In the past, he has worked for KPN, a large Dutch Telecom company, as a senior security officer. He has been the CTO of Wild Hibiscus, Netherlands, since 2010, and co-founder and business creator of Yireo until 2011. Jira ICT since 2005, and CTO of SupportDesk B.V, which he co-founded in 2011. At SupportDesk B.V, he is a Magento, Joomla, OroCRM, Web / Server / Mobile Performance specialist, and Security evangelist. His focus during the day is business/product development and training webmasters and consultants about the power of Magento, from the basics up to an advanced level. He has trained over 1000 Magento and 750 Joomla experts worldwide since 2005. During Magento events like Magento Developers Paradise, Meet Magento and Magento Live he is regular speakers since 2009. He has participated in reviewing Mastering Magento (2012), Mastering Magento (2013) the video, Mastering Magento Theme Design (2014), Magento Administration Guide (2014) and Learning Magento Theme Development (2014). The writing of this book was a big thing for me. I spend every free minute with passion in writing this. I had many doubts and thoughts as a dyslexic person to overcome this big challenge. But I never thought that writing this would give me lots of self-esteem, peace and joy. This would not have happened without the loving support and patient of my wife Mette and daughter Belize. Joining forces with my co-writing Vladimir was a lot of fun. Sharing thoughts and inside about our Magento passion was great. Last, but not least, I would like to thank all the people who made this writing possible.

    Browse publications by this author
  • Vladimir Kerkhoff

    Vladimir Kerkhoff is an experienced IT professional, 4 times Magento Certified Developer from the Netherlands and working with Magento since late 2009. Currently Vladimir is the founder/owner of Genmato BV, a Magento extension development company. He is also available for cool freelance projects. Vladimir has a long carrier in the IT industry, he started his carrier in 1992 at an IT company managing customer corporate networks (Bionet, Novell Netware and Windows Server). In 1996 he was co-founder and CTO of Perfect InterNetworking Solutions (PINS) a large Dutch Managed Hosting provider. After leaving PINS in 2009 he co-founded eFulFillers offering webshop fulfilment services based on the Magento platform. The writing of this book was a nice new experience, forcing myself to dive into the new Magento 2 code and learning the new methods that are available. Joining forces with my co-writing Ray was a lots of fun. Sharing thoughts and inside about our Magento passion was great. Last, but not least, I would like to thank all the people who made this writing possible.

    Browse publications by this author

Latest Reviews

(4 reviews total)
The content was outdated - useless
Nice Book. I am newbie on magento 2 . With this book i can make extension easily and do something , some module in my project perfect . I can do any thing , everything can work.
Good content for a magento2 dev.

Recommended For You

Book Title
Unlock this full book FREE 10 day trial
Start Free Trial