Thursday, October 10, 2024
HomeHow toHow to Install Magento eCommerce Suite on Rocky Linux 9 with Elasticsearch

How to Install Magento eCommerce Suite on Rocky Linux 9 with Elasticsearch

Magento is an open-source e-commerce platform written in PHP. It was acquired by Adobe in 2018. It is also offered as a commercial and cloud-based product. You can use Magento to create high-capacity professional shopping websites. It offers both – a single-store and a multiple-store mode. It comes with lots of modules to extend its functionality.

In this tutorial, we will install the Magento open-source community edition. It offers all the functionality you need to set up a professional online store. We will also install Elasticsearch to search through the product catalog, Redis for the session, and file cache, and serve it using the Nginx server.

Prerequisites

  • A server running Rocky Linux 9 with a minimum of 2GB RAM. You may need more RAM, depending on your requirements.

  • A non-root user with sudo privileges.

  • A fully qualified domain name (FQDN) for the server, magento.example.com

  • Make sure everything is updated.

    $ sudo dnf update
    
  • Few packages that your system needs.

    $ sudo dnf install wget curl nano unzip yum-utils policycoreutils-python-utils -y
    

    Some of these packages may already be installed on your system.

Step 1 – Configure Firewall

The first step is to configure the firewall. Rocky Linux uses Firewalld Firewall. Check the firewall’s status.

$ sudo firewall-cmd --state
running

The firewall works with different zones, and the public zone is the default one that we will use. List all the services and ports active on the firewall.

$ sudo firewall-cmd --permanent --list-services

It should show the following output.

cockpit dhcpv6-client ssh

Allow HTTP and HTTPS ports.

$ sudo firewall-cmd --permanent --add-service=http
$ sudo firewall-cmd --permanent --add-service=https

Recheck the status of the firewall.

$ sudo firewall-cmd --permanent --list-services

You should see a similar output.

cockpit dhcpv6-client http https ssh

Reload the firewall to enable the changes.

$ sudo firewall-cmd --reload

Step 2 – Install PHP and its extensions

Rocky Linux 9 ships with PHP 8.1 by default. To always stay on the latest version of PHP or if you want to install multiple versions of PHP, we need to use the REMI repository.

The first step is to grab the Epel repository.

$ sudo dnf install epel-release -y

Next, install the Remi repository.

$ sudo dnf install https://rpms.remirepo.net/enterprise/remi-release-9.rpm

Check for available PHP streams.

$ dnf module list php -y
Name    Stream              Profiles                                      Summary
php     8.1                 common [d], devel, minimal                    PHP scripting language

Remi's Modular repository for Enterprise Linux 9 - x86_64
Name    Stream              Profiles                                      Summary
php     remi-7.4            common [d], devel, minimal                    PHP scripting language
php     remi-8.0            common [d], devel, minimal                    PHP scripting language
php     remi-8.1            common [d], devel, minimal                    PHP scripting language
php     remi-8.2            common [d], devel, minimal                    PHP scripting language
php     remi-8.3            common [d], devel, minimal                    PHP scripting language

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled

The default version is 8.1. At the time of writing this tutorial, Magento is compatible with PHP 8.2. Therefore, enable Remi’s PHP 8.2 repository.

$ sudo dnf module reset php -y
$ sudo dnf module enable php:remi-8.2

You can install it and the extensions required by Magento by running the following command.

$ sudo dnf install php-fpm php-cli php-mysql php-mbstring php-xml php-gd php-bcmath php-zip php-curl php-tidy php-intl php-soap php-opcache php-xsl php-sodium

Verify the installation.

$ php --version
PHP 8.2.15 (cli) (built: Jan 16 2024 12:19:32) (NTS gcc x86_64)
Copyright (c) The PHP Group
Zend Engine v4.2.15, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.15, Copyright (c), by Zend Technologies

Step 3 – Install Composer

Composer is a dependency management tool for PHP and is required for Magento installation.

Run the following commands to download the Composer binary. Magento requires Composer 2.2 LTS so we have modified the command accordingly.

$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
$ php composer-setup.php --2.2
$ php -r "unlink('composer-setup.php');"

Install Composer by moving the binary to the /usr/local/bin directory.

$ sudo mv composer.phar /usr/local/bin/composer

Verify the installation by checking its version.

$ composer --version
Composer version 2.2.22 2023-09-29 10:53:45

Step 4 – Install MariaDB

Rocky Linux 9 ships with an older version of MariaDB. Therefore, we will use MariaDB’s repository for the installation. At the time of writing this tutorial, Magento supports MariaDB 10.6 which is what we will install.

Import MariaDB’s GPG key.

$ sudo rpm --import https://supplychain.mariadb.com/MariaDB-Server-GPG-KEY

Create and open the /etc/yum.repos.d/mariadb.repo file for editing.

$ sudo nano /etc/yum.repos.d/mariadb.repo

Paste the following code in it.

[mariadb]
name = MariaDB
baseurl = https://rpm.mariadb.org/10.6/rhel/$releasever/$basearch
gpgkey= https://rpm.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

Save the file by pressing Ctrl + X and entering Y when prompted.

$ sudo dnf install MariaDB-server

Check the version of MySQL.

$ mysql --version
mysql  Ver 15.1 Distrib 10.6.16-MariaDB, for Linux (x86_64) using  EditLine wrapper

Enable and start the MariaDB service.

$ sudo systemctl enable mariadb --now

Run the MariaDB secure install script.

$ sudo mariadb-secure-installation

You will be asked for the root password. Press Enter because we haven’t set any password for it.

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):

Next, you will be asked if you want to switch to the Unix socket authentication method. The unix_socket plugin allows you to use your operating system credentials to connect to the MariaDB server. Since you already have a protected root account, enter n to proceed.

OK, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n

Next, you will be asked if you want to change your root password. Type Y to proceed further and change your root password to something strong and secure.

 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] Y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!

Next, you will be asked certain questions to improve MariaDB security. Type Y to remove anonymous users, disallow remote root logins, remove the test database, and reload the privilege tables.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

You can enter the MariaDB shell by typing sudo mysql or sudo mariadb on the command line.

Step 5 – Configure MariaDB

Log in to the MariaDB shell.

$ sudo mariadb

Create a database for Magento.

MariaDB > CREATE DATABASE magento;

Create an SQL user account.

MariaDB > CREATE USER 'magentouser'@'localhost' IDENTIFIED BY 'Your_password2';

Grant all privileges on the database to the user.

MariaDB > GRANT ALL PRIVILEGES ON magento.* TO 'magentouser'@'localhost';

Flush user privileges.

MariaDB > FLUSH PRIVILEGES;

Exit the shell.

MariaDB > exit

Step 6 – Install Nginx

Rocky Linux 9 ships with an older version of Nginx. You need to use the official Nginx repository to install the latest version.

Create and open the file /etc/yum.repos.d/nginx.repo for editing.

$ sudo nano /etc/yum.repos.d/nginx.repo

Paste the following code in it.

[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true

Once you are finished, save the file by pressing Ctrl + X and entering Y when prompted.

We will be installing the Nginx mainline so enable the package for it.

$ sudo dnf config-manager --enable nginx-mainline

Install Nginx.

$ sudo dnf install nginx -y

Verify the installation.

$ nginx -v
nginx version: nginx/1.25.3

Enable and start the Nginx server service.

$ sudo systemctl enable nginx --now

Check the service status.

? nginx.service - nginx - high performance web server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: disabled)
    Drop-In: /etc/systemd/system/nginx.service.d
             ??php-fpm.conf
     Active: active (running) since Fri 2024-01-26 06:46:17 UTC; 1s ago
       Docs: http://nginx.org/en/docs/
    Process: 19765 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 19767 (nginx)
      Tasks: 3 (limit: 12225)
     Memory: 3.1M
        CPU: 16ms
     CGroup: /system.slice/nginx.service
             ??19767 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ??19768 "nginx: worker process"
             ??19769 "nginx: worker process"

Step 7 – Install SSL

We need to install Certbot to generate the SSL certificate. We will use the Snapd package installer for that. Since Rocky Linux doesn’t ship with it, install the Snapd installer. It requires the EPEL (Extra Packages for Enterprise Linux) repository to work. But since we already installed it in step 3, we can directly move ahead.

Install Snapd package.

$ sudo dnf install -y snapd

Enable and Start the Snap service.

$ sudo systemctl enable snapd --now

Install the Snap core package, and ensure that your version of Snapd is up to date.

$ sudo snap install core && sudo snap refresh core

Create necessary links for Snapd to work.

$ sudo ln -s /var/lib/snapd/snap /snap
$ echo 'export PATH=$PATH:/var/lib/snapd/snap/bin' | sudo tee -a /etc/profile.d/snapd.sh

Install Certbot.

$ sudo snap install --classic certbot

Use the following command to ensure that the Certbot command can be run by creating a symbolic link to the /usr/bin directory.

$ sudo ln -s /snap/bin/certbot /usr/bin/certbot

Verify if Certbot is functioning properly.

$ certbot --version
certbot 2.8.0

Run the following command to generate an SSL Certificate.

$ sudo certbot certonly --nginx --agree-tos --no-eff-email --staple-ocsp --preferred-challenges http -m [email protected] -d magento.example.com

The above command will download a certificate to the /etc/letsencrypt/live/magento.example.com directory on your server.

Generate a Diffie-Hellman group certificate.

$ sudo openssl dhparam -dsaparam -out /etc/ssl/certs/dhparam.pem 4096

Check the Certbot renewal scheduler service.

$ sudo systemctl list-timers

You will find snap.certbot.renew.service as one of the services scheduled to run.

NEXT                        LEFT         LAST                        PASSED    UNIT                         ACTIVATES     
-------------------------------------------------------------------------------------------------------------------------------
Fri 2024-01-26 08:05:24 UTC 1h 1min left Fri 2024-01-26 06:35:00 UTC 29min ago dnf-makecache.timer          dnf-makecache.service
Fri 2024-01-26 14:20:42 UTC 7h left      Thu 2024-01-25 14:20:42 UTC 16h ago   systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
Fri 2024-01-26 22:37:00 UTC 15h left     -                           -         snap.certbot.renew.timer     snap.certbot.renew.service

Do a dry run of the process to check whether the SSL renewal is working fine.

$ sudo certbot renew --dry-run

If you see no errors, you are all set. Your certificate will renew automatically.

Step 8 – Install Elasticsearch

Elasticsearch is used by Magento for product searches. We will install Elasticsearch 7.x using its official repository since it is the version that is compatible with Magento 2.4.6 which is the latest version available. The requirements page mentions Elasticsearch 8.5 as well but it doesn’t work properly with Magento.

Import Elasticsearch’s GPG key.

$ sudo rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch

Create a file called elasticsearch.repo in the /etc/yum.repos.d/ directory and open it for editing.

$ sudo nano /etc/yum.repos.d/elasticsearch.repo

Paste the following code in it.

[elasticsearch]
name=Elasticsearch repository for 7.x packages
baseurl=https://artifacts.elastic.co/packages/7.x/yum
gpgcheck=1
gpgkey=https://artifacts.elastic.co/GPG-KEY-elasticsearch
enabled=0
autorefresh=1
type=rpm-md

Once you are finished, save the file by pressing Ctrl + X and entering Y when prompted.

Install Elasticsearch.

$ sudo dnf install --enablerepo=elasticsearch elasticsearch

Elasticsearch uses a lot of memory. You need to limit its usage depending on your server size. Create the file /etc/elasticsearch/jvm.options.d/memory.options file and open it for editing.

$ sudo nano /etc/elasticsearch/jvm.options.d/memory.options

Paste the following code in it. Modify the values according to your server size. The first value refers to the initial memory and the second one refers to the maximum available memory. For 1GB and more, use -Xms1g format.

-Xms512m
-Xmx784m

Save the file by pressing Ctrl + X and entering Y when prompted. This configures Elasticsearch to use 1GB of RAM. Modify it as per your requirements and server specifications.

Start and enable the service.

$ sudo systemctl enable elasticsearch --now

Check if Elasticsearch is working.

$ curl http://localhost:9200

You should see the following output.

{
  "name" : "magento.example.com",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "saBfw0F_Tam6ayGjXr6pEA",
  "version" : {
    "number" : "7.17.17",
    "build_flavor" : "default",
    "build_type" : "rpm",
    "build_hash" : "aba4da413a368e296dfc64fb20897334d0340aa1",
    "build_date" : "2024-01-18T10:05:03.821431920Z",
    "build_snapshot" : false,
    "lucene_version" : "8.11.1",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

Step 9 – Install Redis server

Magento uses Redis for session and cache storage. It is entirely optional and you can use the database for session storage. But Redis does a better job. The latest version of Magento works with Redis 7.0. Rocky Linux ships with Redis 6.0 so we will use the Remi repository repository for installation.

We already installed the Remi repository when we installed PHP in step 2. List all the available Redis modules.

$ dnf module list redis
Name                               Stream           Profiles                   Summary                                                                  
redis                              7                common [d]                 Redis persistent key-value database                                    
Remi's Modular repository for Enterprise Linux 9 - x86_64
Name                               Stream           Profiles                   Summary                             
redis                              remi-5.0         common [d]                 Redis persistent key-value database 
redis                              remi-6.0         common [d]                 Redis persistent key-value database 
redis                              remi-6.2         common [d]                 Redis persistent key-value database 
redis                              remi-7.0         common [d]                 Redis persistent key-value database 
redis                              remi-7.2         common [d]                 Redis persistent key-value database 

Hint: [d]efault, [e]nabled, [x]disabled, [i]nstalled

Enable Redis 7.0.

$ sudo dnf module enable -y redis:remi-7.0

Issue the following command to install the Redis server.

$ sudo dnf install redis

Confirm the Redis version.

$ redis-server -v
Redis server v=7.0.15 sha=00000000:0 malloc=jemalloc-5.2.1 bits=64 build=77c9855172eb54e9

Enable and start the Redis service.

$ sudo systemctl enable redis --now

Let us verify the service connection by using the following command.

$ redis-cli

You will be switched to the Redis shell.

The first step is to set the password for the Redis default user. Replace Your_Redis_Password with a strong password of your choice. Make sure you prefix the password with the > character.

127.0.0.1:6379> acl setuser default >Your_Redis_Password

Test the Redis Authentication.

127.0.0.1:6379> AUTH Your_Redis_Password
OK

Ping the service.

127.0.0.1:6379> ping
PONG

Exit the service by typing exit.

Step 10 – Download Magento

Create a web root directory for Magento.

$ sudo mkdir /var/www/html/magento -p

Give the rights to the Magento directory to the current user.

$ sudo chown $USER:$USER /var/www/html/magento/ -R

Before we move further, you need to authentication keys required by the Magento repository. Visit the website https://commercemarketplace.adobe.com/, click the Sign in link at the top right, and you will get the following page asking you to log in using your Adobe ID.

Click the Sign in with Adobe ID button to get to the following page.

If you have an Adobe ID, enter your credentials to continue or you can create an account here. Once you have created your account and logged in, open the URL https://commercemarketplace.adobe.com/customer/accessKeys/. You can also access this page by visiting your profile ( https://commercemarketplace.adobe.com/customer/account/) and clicking the Access Keys link.

Click the Create A New Access Key button to create your authentication key. Give a name to your key for identification.

Note down both the public and private keys for the next step.

Create the ~/.config/composer/auth.json file and open it for editing.

$ nano ~/.config/composer/auth.json

Paste the following code in it. Use the public key for the username and the private key for the password.

{
"http-basic": {
        "repo.magento.com": {
                   "username": "",
                   "password": ""
              }

}
}

Save the file by pressing Ctrl + X and entering Y when prompted.

Switch to the /var/www/html/magento directory.

$ cd /var/www/html/magento

Create the Magento project. Note the period at the end of the command. It refers to the current directory in which the command is being run.

$ composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition .

You should see a similar output.

Creating a "magento/project-community-edition" project at "./"
Installing magento/project-community-edition (2.4.6-p3)
  - Downloading magento/project-community-edition (2.4.6-p3)
  - Installing magento/project-community-edition (2.4.6-p3): Extracting archive
Created project in /var/www/html/magento/.
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Updating dependencies
Lock file operations: 566 installs, 0 updates, 0 removals
  - Locking 2tvenom/cborencode (1.0.2)
  - Locking adobe-commerce/adobe-ims-metapackage (2.2.0)
  - Locking allure-framework/allure-codeception (v2.3.0)
  - Locking allure-framework/allure-php-commons (v2.3.1)
  - Locking allure-framework/allure-phpunit (v2.1.0)
...............................................

Run the following commands to set the file permissions and make Magento binary executable. Also, set the owner of the Magento directory to the Nginx user so that it can access the website.

$ sudo find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
$ sudo find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
$ sudo chown -R :nginx .
$ sudo chmod u+x bin/magento

Step 11 – Install Magento

Make sure you are in the Magento directory.

$ cd /var/www/html/magento

Run the following command to install Magento.

$ bin/magento setup:install \
--base-url=http://magento.example.com \
--use-secure=1 \
--base-url-secure=https://magento.example.com \
--use-secure-admin=1 \
--db-host=127.0.0.1 \
--db-name=magento \
--db-user=magentouser \
--db-password=Your_password2 \
--admin-firstname=Navjot \
--admin-lastname=Singh \
[email protected] \
--admin-user=navjot \
--admin-password=admin_password \
--language=en_US \
--currency=USD \
--timezone=America/Chicago \
--use-rewrites=1 \
--elasticsearch-host=http://127.0.0.1 \
--elasticsearch-port=9200 \
--session-save=redis \
--session-save-redis-db=0 \
--session-save-redis-password=redis_password \
--cache-backend=redis \
--cache-backend-redis-db=2 \
--cache-backend-redis-password=redis_password \
--page-cache=redis \
--page-cache-redis-db=4 \
--page-cache-redis-password=redis_password

Once the process is complete, you will get a similar output.

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

Note down the Admin URI which you will need later to access the administration panel.

Create Magento cron jobs.

$ php bin/magento cron:install

Verify the cron job.

$ crontab -l

You should see the following output.

#~ MAGENTO START f37deed947b2ea951ad6f939b8ab752bc79587e3d77f40d06f20f0657c98e94d
* * * * * /usr/bin/php /var/www/html/magento/bin/magento cron:run 2>&1 | grep -v "Ran jobs by schedule" >> /var/www/html/magento/var/log/magento.cron.log
#~ MAGENTO END f37deed947b2ea951ad6f939b8ab752bc79587e3d77f40d06f20f0657c98e94d

Step 12 – Configure PHP-FPM

Open the file /etc/php-fpm.d/www.conf.

$ sudo nano /etc/php-fpm.d/www.conf

We need to set the Unix user/group of PHP processes to nginx. Find the user = apache and group = apache lines in the file and change them to nginx.

...
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
; RPM: apache user chosen to provide access to the same directories as httpd
user = nginx 
; RPM: Keep a group allowed to write in log dir.
group = nginx
...

Find the listen.owner = nobody, listen.group = nobody, listen.mode = 0660 lines in the file and change them as follows after uncommenting them.

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = nginx 
listen.group = nginx 
listen.mode = 0660

Save the file by pressing Ctrl + X and entering Y when prompted.

Increase the execution time to 180 seconds.

$ sudo sed -i 's/max_execution_time = 30/max_execution_time = 180/' /etc/php.ini

Increase the memory limit for PHP-FPM from 128MB to 512MB. You can raise the limit depending on your server size and requirements.

$ sudo sed -i 's/memory_limit = 128M/memory_limit = 512M/' /etc/php.ini

Magento by default sets the file size limit for the media library as 2MB. Run the following commands to increase the file size limit to 25MB.

$ sudo sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 25M/g' /etc/php.ini
$ sudo sed -i 's/post_max_size = 8M/post_max_size = 25M/g' /etc/php.ini

Turn on the Zlib Compression.

$ sudo sed -i 's/zlib.output_compression = Off/zlib.output_compression = On/g' /etc/php.ini

Increase the realpath_cache configuration as shown.

$ sudo sed -i 's/;realpath_cache_size = 4096k/realpath_cache_size = 10M/g' /etc/php.ini
$ sudo sed -i 's/;realpath_cache_ttl = 120/realpath_cache_ttl = 7200/g' /etc/php.ini

Open the file /etc/php.d/10-opcache.ini for editing.

$ sudo nano /etc/php.d/10-opcache.ini

Find the line ;opcache.save_comments=1 and uncomment it as shown.

opcache.save_comments=1

Save the file by pressing Ctrl + X and entering Y when prompted.

Restart the PHP-FPM service.

$ sudo systemctl restart php-fpm

Change the group of the PHP sessions directory to Nginx.

$ sudo chgrp -R nginx /var/lib/php/session

Step 13 – Configure SELinux

Run the following commands to change the security context for the Magento directory.

$ sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/magento/app/etc(/.*)?'
$ sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/magento/var(/.*)?'
$ sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/magento/pub/media(/.*)?'
$ sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/magento/pub/static(/.*)?'
$ sudo semanage fcontext -a -t httpd_sys_rw_content_t '/var/www/html/magento/generated(/.*)?'
$ sudo restorecon -Rv '/var/www/html/magento/'

Apply the policy to allow connections to be made to outside hosts.

$ sudo setsebool -P httpd_can_network_connect 1

Apply the policy to allow Nginx to give access to PostgreSQL.

$ sudo setsebool -P httpd_can_network_connect_db 1

Step 14 – Configure Nginx

Open the file /etc/nginx/nginx.conf for editing.

$ sudo nano /etc/nginx/nginx.conf

Add the following line before the line include /etc/nginx/conf.d/*.conf;.

server_names_hash_bucket_size 64;

Save the file by pressing Ctrl + X and entering Y when prompted.

Create and open the file /etc/nginx/conf.d/magento.conf for editing.

$ sudo nano /etc/nginx/conf.d/magento.conf

Paste the following code in it.

upstream fastcgi_backend {
  server  unix:/run/php-fpm/www.sock;
}

server {
  # Redirect any http requests to https
  listen 80;
  listen [::]:80;
  server_name magento.example.com;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name magento.example.com;

  set $MAGE_ROOT /var/www/html/magento;
  include /var/www/html/magento/nginx.conf.sample;
  client_max_body_size 25m;

  access_log /var/log/nginx/magento.access.log;
  error_log  /var/log/nginx/magento.error.log;

  # TLS configuration
  ssl_certificate /etc/letsencrypt/live/magento.example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/magento.example.com/privkey.pem;
  ssl_trusted_certificate /etc/letsencrypt/live/magento.example.com/chain.pem;
  ssl_protocols TLSv1.2 TLSv1.3;

  ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384';
  ssl_prefer_server_ciphers on;
  ssl_session_cache shared:SSL:50m;
  ssl_session_timeout 1d;

  # OCSP Stapling ---
  # fetch OCSP records from URL in ssl_certificate and cache them
  ssl_stapling on;
  ssl_stapling_verify on;
  ssl_dhparam /etc/ssl/certs/dhparam.pem;
}

Save the file by pressing Ctrl + X and entering Y when prompted once finished.

Magento comes with an Nginx configuration template at /var/www/magento/nginx.conf.sample which we have included in our configuration. The $MAGE_ROOT variable points to the Magento web root directory which we have set in our file and is used in the sample configuration file.

Verify the Nginx configuration file syntax.

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Restart the Nginx service.

$ sudo systemctl restart nginx

Open the Magento website via the URL https://magento.example.com. You should see the following page.

If the CSS and JS don’t load, run the following commands.

$ cd /var/www/html/magento
$ sudo php bin/magento setup:static-content:deploy -f
$ sudo php bin/magento indexer:reindex

Step 15 – Disable Two factor Authentication

Before accessing the administration panel, we need to disable the two-factor authentication enabled by default. Magento tries to send mail via sendmail for enabling two-factor authentication during installation but since we didn’t configure that, the only way to access the dashboard is to disable the feature first.

If you have sendmail Configured on your server to send emails, you can skip this step. We need to disable two of Magento’s modules using the following commands to disable two-factor authentication.

$ sudo php /var/www/html/magento/bin/magento module:disable Magento_AdminAdobeImsTwoFactorAuth
$ sudo php /var/www/html/magento/bin/magento module:disable Magento_TwoFactorAuth

Run the following command to create the classes.

$ sudo php /var/www/html/magento/bin/magento setup:di:compile

Clean the cache as well.

$ sudo php /var/www/html/magento/bin/magento c:c

Step 16 – Access the Administration Portal

You must open the administration portal using the URI the Magento install script gave you. If you somehow forgot to note it down or lost it, you can retrieve the URI again using the following command.

$ php /var/www/magento/bin/magento info:adminuri
Admin URI: /admin_l5pv1h

Open the URL https://magento.example.com/admin_l5pv1h in your browser and you will get the following screen.

Enter the administrator credentials you provided during the installation and click the Sign in button to proceed. You will be greeted with the following screen.

You will get a popup asking permission for Adobe to collect usage data. Click the Don’t Allow button to proceed.

The next step is to configure SMTP for emails so that we can re-enable two-factor authentication. Visit the Stores >> Configuration menu.

Expand the Advanced Menu from the left side and click the Systems option to open the Email settings page.

Uncheck the Use system value before the Transport, Host, and, Port options. Click the dropdown menu for Transport and select SMTP. For our tutorial, we are using Amazon SES as the mailer.

Enter your SMTP host, 587 as the port, username, and password, set Auth to LOGIN, and set SSL to TLS in the given fields. Click the Save Config button when you are done. Now that we have configured the email settings, the next step is to configure the store email IDs so that we can test them.

Scroll up, expand the General menu on the same page, and select the Store Email Addresses option.

Uncheck the default Sender Email fields and enter your store’s email IDs. Click the Save Config button when you are done. Similarly, open the Contacts screen, make the same changes, and click the Save Config button to finish it.

Changing administrator options can affect the cache and you will get a warning. Run the following command to clear the cache manually.

$ sudo php /var/www/html/magento/bin/magento c:c

To test the emails, visit the storefront page and open the Contact Us page. You can use the URL https://magento.example.com/contact/ directly to access it. Send a test message and click the Submit button. You should receive a similar mail.

Step 17 – Enable and Configure Two-factor Authentication

Now that we have enabled the SMTP mailer, it is time to re-enable two-factor authentication. Run the following commands to enable two-factor authentication.

$ sudo php /var/www/html/magento/bin/magento module:enable Magento_AdminAdobeImsTwoFactorAuth
$ sudo php /var/www/html/magento/bin/magento module:enable Magento_TwoFactorAuth

Upgrade the setup for the modules.

$ sudo php /var/www/html/magento/bin/magento setup:upgrade

Run the following command to create the classes.

$ sudo php /var/www/html/magento/bin/magento setup:di:compile

Clean the cache as well.

$ sudo php /var/www/html/magento/bin/magento c:c

If you are not able to access the admin area, run the following commands as well.

Force deploy the static content.

$ sudo php /var/www/html/magento/bin/magento setup:static-content:Deploy -f

Set the file permissions.

$ cd /var/www/html/magento
$ sudo find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
$ sudo find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
$ sudo chown -R :nginx .

Visit the Admin portal and you will get the following screen.

We will be using the Google Authenticator Method. You can use a hardware key if you have one. Google Authenticator method works with any TOTP app including Authy, 1Password, Bitwarden, Microsoft Authenticator, etc. Click the Apply button to proceed.

On the next page, you will get the QR code to scan with your 2FA app. Enter the details into your app and copy the generated code into the Authenticator code field. Click the Confirm button to proceed to the admin dashboard.

Conclusion

This concludes our tutorial on installing a Magento eCommerce Site on a Rocky Linux 9 server with an Nginx server and Elasticsearch. If you have any questions, post them in the comments below.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Most Popular