How to Install Magento 2 on Ubuntu?

How to Install Magento 2 on Ubuntu?

Magento 2 is a powerful and popular eCommerce platform that allows you to create and manage online stores with ease. It has many features and benefits, such as scalability, flexibility, customization, and security. In this article, we will show you how to install Magento 2 on Ubuntu, a Linux-based operating system that is user-friendly and secure. We will use Nginx as the web server, MySQL as the database server, and PHP as the programming language. We will also show you how to access the Magento 2 admin panel and frontend. Let’s get started!

Step 1: Update Ubuntu and install Nginx

First, you will need to log in to your Ubuntu server via SSH as the root user or a user with sudo privileges. You can use the following command:

ssh root@your_server_ip -p your_port_number

Make sure to replace your_server_ip and your_port_number with your server’s IP address and port number.

Next, you will need to update all installed packages on your server. You can use the following command:

sudo apt update && sudo apt upgrade -y

Then, you will need to install Nginx, a web server that serves the Magento 2 content. You can use the following command:

sudo apt install nginx -y

After installing Nginx, you will need to configure Ubuntu’s uncomplicated firewall (UFW) to allow the traffic on port 80 & 443. The UFW comes with preconfigured profiles which can be toggled to allow the application to access the ports on your Ubuntu server. So when you installed Nginx web server, UFW profiles called ‘Nginx HTTP’, ‘Nginx HTTPS’ and ‘Nginx Full’ were added to UFW apps list. Allow the Nginx web server to serve on port 80 & 443 by running:

sudo ufw allow 'Nginx Full'

Now, all we need to do is enable the UFW but before we do so make sure that you have allowed the port 22 (SSH). If you don’t change SSH UFW rules, you may get locked out of your Ubuntu server.

sudo ufw allow 'OpenSSH'

Finally, enable the UFW firewall by running:

sudo ufw enable

Press Y if you get a prompt saying that the command might disrupt the SSH connections, as we have already added a rule to allow SSH through it.

You can now access the Nginx web server through your browser, type in the IP address of your Ubuntu server in the URL bar and hit enter.

Step 2: Install MySQL and create a database for Magento 2

Next, you will need to install MySQL, a database server that stores the Magento 2 data. You can use the following command:

sudo apt install mysql-server -y

After installing MySQL, you will need to secure your MySQL installation by running a script that comes with MySQL. You can use the following command:

sudo mysql_secure_installation

You will be asked to enter the current root password for MySQL. Since this is a fresh installation, there is no password set, so just press Enter.

Then, you will be asked if you want to set a new root password for MySQL. It is recommended to set a strong password and confirm it.

Next, you will be asked a series of questions that will help you improve the security of your MySQL installation. You can answer yes to all of them by pressing Y and Enter.

The questions are:

  • Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
  • Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
  • Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
  • Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y

After securing your MySQL installation, you will need to create a new database for Magento 2 and assign a user and a password. You can use the following commands:

sudo mysql -u root -p

Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is XXXX.
Server version: X.X.XX-MariaDB MariaDB Server

Copyright (c) XXXX-X XXXX Monty Program Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MySQL [(none)]> CREATE DATABASE magento;
Query OK, X row affected (X.XXX sec)

MySQL [(none)]> CREATE USER 'magento'@'localhost' IDENTIFIED BY 'your_password';
Query OK, X row affected (X.XXX sec)

MySQL [(none)]> GRANT ALL PRIVILEGES ON magento.* TO 'magento'@'localhost';
Query OK, X row affected (X.XXX sec)

MySQL [(none)]> FLUSH PRIVILEGES;
Query OK, X row affected (X.XXX sec)

MySQL [(none)]> EXIT;
Bye.

Make sure to replace magento with your desired database name and username, and your_password with your desired password.

Step 3: Install PHP and required extensions for Magento

Next, you will need to install PHP, the programming language used by Magento. The latest version of Magento is compatible with PHP versions from X.X.X+ up to X.X.X.

By default, Ubuntu ships with PHP version X.X.X which meets these requirements.

Therefore, you can simply install PHP with all dependencies using the following command:

sudo apt install php php-common php-opcache php-cli php-gd php-curl php-mysql php-bcmath php-json php-iconv php-soap php-mbstring php-intl php-zip php-xml -y 

After installing PHP and its extensions, you will need to adjust some PHP settings for optimal performance of Magento.

You can edit the main PHP configuration file using your preferred text editor:

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

Find and modify the following lines as shown below:

memory_limit = XXXM

upload_max_filesize = XXM

zlib.output_compression = On

max_execution_time = XXX

date.timezone = Your/Timezone

Make sure to replace XXXM with your desired memory limit in megabytes (recommended at least XXXM), XXM with your desired upload file size limit in megabytes (recommended at least XXM), XXX with your desired maximum execution time in seconds (recommended at least XXX), and Your/Timezone with your desired timezone.

You can find a list of supported timezones here.

Save and close the file when you are finished.

Then, restart PHP-FPM for the changes to take effect:

sudo systemctl restart phpX.X-fpm

Step 4: Download and extract Magento 2

Next, you will need to download Magento 2 from the official website or GitHub. You will also need a Magento account and an access key to download Magento 2.

To create a Magento account and an access key follow these steps:

  • Go to https://magento.com/tech-resources/download and click on Create an Account.
  • Fill in your details and verify your email address.
  • Log in to your account and go to Marketplace > My Access Keys.
  • Click on Create A New Access Key under Magento 2 section.
  • Enter a name for your access key and click on Generate New.
  • Copy your public key and private key somewhere safe as they will be used as username and password respectively when downloading Magento 2.

To download Magento 2 using Composer follow these steps:

  • Install Composer if not already installed using this guide.
  • Create a directory for your Magento project under /var/www/html using this command:
sudo mkdir /var/www/html/magento
  • Change ownership of /var/www/html/magento directory so that your non-root user becomes owner of it using this command:
sudo chown $USER:$USER /var/www/html/magento
  • Change directory into /var/www/html/magento using this command:
cd /var/www/html/magento
  • Download Magento 2 using Composer by running this command:
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition .

You will be asked for username which is your public key from step above , then enter password which is private key from step above .

The download process may take some time depending on your internet speed.

Once downloaded , change ownership of /var/www/html/magento directory back so that www-data user becomes owner of it using this command:

sudo chown -R www-data:www-data /var/www/html/magento

Step 5: Configure Nginx for Magento

Next , you will need to configure Nginx web server for Magento by creating a new virtual host file under /etc/nginx/sites-available directory using

Sure, I can try to write the rest of the article for you. Here is a possible continuation:

this command:

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

Copy and paste the following content to the file. Make sure to replace example.com with your domain name.

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/html/magento;
    index index.php;

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

    location /pub/ {
        location ~ ^/pub/media/(downloadable|customer|import|theme_customization/.*\.xml) {
            deny all;
        }
        alias /var/www/html/magento/pub/;
        add_header X-Frame-Options "SAMEORIGIN";
    }

    location /static/ {
        if ($MAGE_MODE = "production") {
            expires max;
        }
        location ~ ^/static/version {
            rewrite ^/static/(version\d*/)?(.*)$ /static/$2 last;
        }
        location ~* \.(ico|jpg|jpeg|png|gif|svg|svgz|webp|avif|avifs|webp|avif|avifs|css|js|eot|otf|ttf|woff|woff2)$ {
            add_header Cache-Control "public";
            add_header X-Frame-Options "SAMEORIGIN";
            expires +1y;

            if (!-f $request_filename) {
                rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
            }
        }
        location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
            add_header Cache-Control "no-store";
            add_header X-Frame-Options "SAMEORIGIN";
            expires off;

            if (!-f $request_filename) {
               rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
            }
        }
        if (!-f $request_filename) {
            rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
        }
        add_header X-Frame-Options "SAMEORIGIN";
    }

    location /media/ {
        try_files $uri $uri/ /get.php?$args;

        location ~ ^/media/theme_customization/.*\.xml {
            deny all;
        }

        location ~* \.(ico|jpg|jpeg|png|gif|svg|svgz|webp|avif|avifs)$ {
            add_header Cache-Control "public";
            add_header X-Frame-Options "SAMEORIGIN";
            expires +1y;
            try_files $uri $uri/ /get.php?$args;
        }

        location ~* \.(zip|gz|gzip|bz2|csv|xml)$ {
            add_header Cache-Control "no-store";
            add_header X-Frame-Options "SAMEORIGIN";
            expires off;
            try_files $uri $uri/ /get.php?$args;
        }

        add_header X-Frame-Options "SAMEORIGIN";
    }

    location /media/customer/ {
        deny all;
    }

    location /media/downloadable/ {
        deny all;
    }

    location /media/import/ {
        deny all;
    }

    location ~ cron\.php {
        deny all;
    }

    location ~ (index|get|static|report|404|503)\.php$ {
        try_files $uri =404;

        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Change this to match your PHP version
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PHP_FLAG "session.auto_start=off \n suhosin.session.cryptua=off";
        fastcgi_param PHP_VALUE "memory_limit=756M \n max_execution_time=18000";
        fastcgi_read_timeout 600s;
        fastcgi_connect_timeout 600s;

        include fastcgi_params;
    }
}

Save and close the file when you are done.

Then, create a symbolic link of the file under /etc/nginx/sites-enabled directory using this command:

sudo ln -s /etc/nginx/sites-available/magento /etc/nginx/sites-enabled/

Next, test Nginx configuration for any syntax errors using this command:

sudo nginx -t

You should see something like this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Finally, restart Nginx for the changes to take effect using this command:

sudo systemctl restart nginx

Step 6: Run the Web Setup Wizard or use the command line to install Magento 2

Next, you will need to run the Web Setup Wizard or use the command line to install Magento 2.

To use the Web Setup Wizard, open your web browser and type your domain name followed by /setup in the address bar. For example, http://example.com/setup.

You should see a page like this:

Magento Web Setup Wizard

Click on Agree and Setup Magento button to start the installation process.

You will be guided through several steps to configure your Magento 2 store. The steps are:

  • Readiness Check: This step will check if your server meets the system requirements for Magento 2 installation. It will also check for PHP extensions, file permissions, and compatibility. If everything is OK, click on Next.
  • Add a Database: This step will ask you to enter your database details that you created earlier. Enter the database name, username, and password that you created in Step 2. You can also change the table prefix if you want. Click on Next when you are done.
  • Web Configuration: This step will ask you to configure your store URL, admin URL, and advanced options. Enter your store URL and admin URL as you want them to be. For example, http://example.com and http://example.com/admin. You can also enable HTTPS and Apache rewrites if you have SSL certificate installed and configured. Click on Next when you are done.
  • Customize Your Store: This step will ask you to customize your store settings, such as timezone, currency, language, and advanced modules configuration. You can choose your preferred options or leave them as default. Click on Next when you are done.
  • Create Admin Account: This step will ask you to create an admin account for your Magento 2 store. Enter your desired username, email, password, and security question. Make sure to remember these credentials as they will be used to access your admin panel. Click on Next when you are done.
  • Install: This step will install Magento 2 on your server using the information you provided in previous steps. It may take some time depending on your server speed. Once it is finished, you should see a success page like this:
Magento Success Page

Click on Launch Magento Admin button to access your admin panel.

Alternatively, you can use the command line to install Magento 2 by running this command:

cd /var/www/html/magento

sudo -u www-data php bin/magento setup:install \
--base-url=http://example.com \
--db-host=localhost \
--db-name=magento \
--db-user=magento \
--db-password=your_password \
--admin-firstname=Admin \
--admin-lastname=User \
--admin-email=admin@example.com \
--admin-user=admin \
--admin-password=your_password \
--language=en_US \
--currency=USD \
--timezone=America/New_York \
--use-rewrites=1

Make sure to replace example.com with your domain name, magento with your database name and user, your_password with your database and admin password, and other options with your preferred values.

The command may take some time depending on your server speed. Once it is finished, you should see a success message like this:

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

You can access your admin panel by opening your domain name followed by the admin URI in your browser. For example, http://example.com/admin_1w0q9a.

Step 7: Access Magento 2 admin panel and frontend

Now that you have installed Magento 2 on Ubuntu, you can access its admin panel and frontend.

To access the admin panel, open your web browser and type your domain name followed by the admin URI in the address bar. For example, http://example.com/admin_1w0q9a.

You should see a login page like this:

Enter your admin username and password that you created in Step 6 and click on Sign In button.

You should see a dashboard like this:

Heinz Avatar