- Step by Step Guide to Install Magento 2.4.1 with Apache on Ubuntu 20.04, Ubuntu 18.04, Ubuntu 22.10 and Ubuntu 22.04 using Composer 2 and Command line ( CLI )
Install & Configure Apache
First of all, update your Ubuntu 20.04 system packages and install apache 2 using following commands in CLI.
sudo apt update
sudo apt install apache2
Once the installation is finished, you’ll need to adjust your firewall settings to allow HTTP and HTTPS traffic.
To list all currently available UFW application profiles, you can run:
sudo ufw app list
sudo ufw allow in "Apache Full"
sudo ufw delete allow 'Apache'

- Apache Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic).
You can verify the change with:
sudo ufw status

Now open your domain in browser and you will see the default Ubuntu 20.04 Nginx web page. It should look something like this:
For localhost: http://localhost

If you see this page, then your web server is now correctly installed and accessible through your firewall.
Verify that the apache2 service is active/running and is enabled to automatically start at system startup using the following systemctl commands
sudo systemctl is-active apache2
sudo systemctl is-enabled apache2
sudo systemctl status apache2

Install MySQL
Install MySQL 8 using apt command
sudo apt install mysql-server

When prompted, confirm installation by typing Y
, and then ENTER
When the installation is finished, it’s recommended that you run a security script that comes pre-installed with MySQL. This script will remove some insecure default settings and lock down access to your database system.
sudo mysql_secure_installation
Answer Y
for yes

Select a level of password validation
If you enabled password validation, you’ll be shown the password strength for the root password you just entered and your server will ask if you want to continue with that password. If you are happy with your current password, enter Y
for “yes” at the prompt:
For the rest of the questions, press Y
and hit the ENTER
key at each prompt.
When you’re finished, test if you’re able to log in to the MySQL console by typing:
sudo mysql
This will connect to the MySQL server as the administrative database user root, which is inferred by the use of sudo when running this command. You should see output like this:

To exit the MySQL console, type:
exit
Your MySQL server is now installed and secured. Next, we’ll install PHP.
Install PHP
Install PHP 7.4 and other Packages with below command.
sudo apt install php7.4 libapache2-mod-php php-mysql

Verify installed PHP version
php -v

Edit the /etc/apache2/mods-enabled/dir.conf
file and modify the order in which the index.php
file is listed within the DirectoryIndex
directive:
sudo nano /etc/apache2/mods-enabled/dir.conf
<IfModule mod_dir.c>
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

Enable the mbstring
PHP extension
sudo apt install php7.4-mbstring
sudo phpenmod mbstring
Reload Apache so the changes take effect:
sudo systemctl reload apache2
Install phpMyAdmin (Optional)
Login to mysql
sudo mysql
Or, if you enabled password authentication for the root MySQL user,
mysql -u root -p
Disable the Validate Password component.
UNINSTALL COMPONENT "file://component_validate_password";
exit

Note: that this won’t actually uninstall it, but just stop the component from being loaded on your MySQL server:
Install phpmyadmin
sudo apt install phpmyadmin php-zip php-gd php-json php-curl
- For the server selection, choose
apache2
(hit space and select first and then hit enter otherwise it will just look highlighted with red color but it will not be selected.
)

- Select
Yes
when asked whether to usedbconfig-common
to set up the database

- You will then be asked to choose and confirm a MySQL application password for phpMyAdmin

Select TCP/IP Connection Method

Once phpMyAdmin is installed, re-enable the Validate Password component:
sudo mysql
Or, if you enabled password authentication for the root MySQL user,
mysql -u root -p
INSTALL COMPONENT "file://component_validate_password";
exit

Reload Apache so the changes take effect:
sudo systemctl restart apache2
Configure Password Access for the MySQL Root Account
sudo mysql
Or, if you enabled password authentication for the root MySQL user,
mysql -u root -p
SELECT user,authentication_string,plugin,host FROM mysql.user;

Make sure to replace your_secure_password
with your password.
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
SELECT user,authentication_string,plugin,host FROM mysql.user;
exit

Create new MySQL User for magento 2 & Configure Password Access
Here you can choose more secure name for your user. But for this tutorial I will create magento
user.
sudo mysql
Or, if you enabled password authentication for the root MySQL user,
mysql -u root -p
SELECT user,authentication_string,plugin,host FROM mysql.user;
Make sure to replace your_secure_password
with your password.
CREATE USER 'magento2'@'localhost' IDENTIFIED BY 'your_secure_password';
ALTER USER 'magento2'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_secure_password';
GRANT ALL PRIVILEGES ON *.* TO 'magento2'@'localhost' WITH GRANT OPTION;

SELECT user,authentication_string,plugin,host FROM mysql.user;
exit
Now you can verify phpmyadmin whether it is accessible or not.
https://your-domain/phpmyadmin
For localhost : http://localhost/phpmyadmin

Now here if you are not able to see phpmyadmin page and if you are getting 404 Page not found error
on the PHPMyAdmin link, you can fix it with the below commands.

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf
sudo a2enconf phpmyadmin
sudo systemctl restart apache2
Secure Your phpMyAdmin with .htpasswd
It is not advisable to keep phpmyadmin page open for public. You can create username and password for that page to add and extra layer of security.
sudo nano /etc/apache2/conf-available/phpmyadmin.conf
Add an AllowOverride All
directive within the <Directory /usr/share/phpmyadmin>
section of the configuration file

AllowOverride All
directiveRelstart Apache so the changes take effect:
sudo systemctl restart apache2
Create .htaccess
file and add below code in that file
sudo nano /usr/share/phpmyadmin/.htaccess
/usr/share/phpmyadmin/.htaccess
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/phpmyadmin/.htpasswd
Require valid-user

Create username and password to access phpmyadmin
page.
sudo htpasswd -c /etc/phpmyadmin/.htpasswd secure_username

If you want to enter an additional user,
sudo htpasswd /etc/phpmyadmin/.htpasswd another_secure_username
Verify the PHPMyAdmin page, it must ask username and password. Once you enter the correct username and password it will redirect and allow you to access the PHPMyAdmin page.
https://your-domain/phpmyadmin
For Localhost: http://localhost/phpmyadmin

Set Up Let’s Encrypt SSL Certificate with Auto-Renewal Cron (Optional)
Install Certbot
sudo apt install certbot python3-certbot-apache
sudo apache2ctl configtest
sudo systemctl reload apache2
Obtain SSL Certificates
sudo certbot --apache
Select your domain in next step and after that complete other steps in process.
Verify Certbot Auto-Renewal
sudo systemctl status certbot.timer

To test the renewal process, you can do a dry run with certbot
:
sudo certbot renew --dry-run
Open /etc/apache2/sites-available/your-domain-le-ssl.conf
or your virtual host file for SSL ( 443 port ) if you haven’t configure SSL with Let’s Encrypt.
Set AllowEncodedSlashes
in the server config (globally) or in the virtual host configurations to avoid decoding the encoded slashes that may cause issues for URLs. For instance, when retrieving products with a slash in the SKU via the API, you will not want that converted.
<VirtualHost *:443>
...
# Allow encoded slashes
AllowEncodedSlashes NoDecode
...
</VirtualHost>
Install & configure Apache modules for Magento 2
Enable the Apache rewrite module
sudo a2enmod rewrite
sudo apt install php7.4-bcmath php7.4-intl php7.4-soap
Install Elastic Search
Install OpenJDK 11
sudo apt install openjdk-11-jdk

Once the installation is complete, verify java version with below command.
java -version

Install Elasticsearch
curl -fsSL https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
After that, add the Elastic source list to the sources.list.d
director
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee -a /etc/apt/sources.list.d/elastic-7.x.list
sudo apt update

sudo apt install elasticsearch

Configure Elasticsearch on Ubuntu 20.04
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart
Create new virtual host file for Elasticsearch proxy
sudo nano /etc/apache2/ports.conf
Add Listen 8080

open /etc/apache2/sites-available/your-domain-elasticsearch.conf
sudo nano /etc/apache2/sites-available/your-domain-elasticsearch.conf
<VirtualHost *:8080>
ProxyPass "/" "http://localhost:9200/"
ProxyPassReverse "/" "http://localhost:9200/"
</VirtualHost>
sudo a2ensite your-domain-elasticsearch
sudo service apache2 restart
Start the Elasticsearch service with systemctl
& enable Elasticsearch to start up every time your server boots.
sudo systemctl start elasticsearch
sudo systemctl enable elasticsearch

Verify Elasticsearch proxy is working or not ?
curl -i http://localhost:8080/_cluster/health

If should return the output as above.
Install Redis (Optional)
sudo apt install redis-server
Open up the Redis configuration file
sudo nano /etc/redis/redis.conf
Inside the file, find the supervised
directive which allows you to declare an init system and change its value from no
to systemd
:

why ? because you are running Ubuntu, which uses the systemd init system.
Configure Redis Password
sudo nano /etc/redis/redis.conf
Scroll to the SECURITY
section and look for a commented directive requirepass
Remove #
, and change foobared
to a secure password: ( Line No: 507 )

After setting the password, save and close the file, then restart Redis
sudo systemctl restart redis.service
Check Redis is working or not with below command ?
sudo systemctl status redis

Install Composer 2
Downloading and Installing Composer 2
cd ~
curl -sS https://getcomposer.org/installer -o composer-setup.php
To install composer
globally, use the following command which will download and install Composer as a system-wide command named composer
, under /usr/local/bin
:
sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer --version=1.10.16
Check Composer 2 is installed or not in Ubuntu?
composer

Great! Finally we are ready to install Magento 2.4
Get your authentication keys
- Login to Magento Marketplace ( https://marketplace.magento.com )
- Go to My Profile > Access Keys Page ( https://marketplace.magento.com/customer/accessKeys/ )

- Click on Create A New Access Key Button
- Enter a key name and generate
Get the Magento 2.4.x metapackage
- Go to root folder and execute below command to change permission.
cd /var/www/html
sudo chown -R $USER:$USER /var/www/html
- Create a new Composer project using the Magento Open Source or Magento Commerce metapackage on magento2 directory. If you want you can change the directory name as per your requirement in the below command.
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition magento2

Set Up Virtual Hosts
Create Virtual Host Config file
sudo nano /etc/apache2/sites-available/your_domain.conf
Update /etc/apache2/sites-available/your_domain.conf file as below and make sure to change your-domain
with your actual domain name
<VirtualHost *:80>
ServerName your-domain
ServerAlias www.your-domain
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/magento2
<Directory /var/www/html/magento2/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Activate Your Virtual Host Configuration file and deactivate 000-default host conf file to avoid conflict.
sudo a2ensite your_domain
sudo a2dissite 000-default
Reload Apache so the changes take effect:
sudo systemctl reload apache2
Update Directory & File Permissions for Magento 2.4.x
Set read-write permissions so that command line can write files to the Magento 2 file system.
cd /var/www/html/magento2
find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
sudo chown -R :www-data .
sudo chmod u+x bin/magento
Install Magento 2.4.1
At the time of writing, current version of magento is 2.4.1. So we will install Magento 2.4.1 on Ubuntu 20.04 LTS.
This tutorial assumes that:
- Domain name is http://localhost
- Domain Root Directory is /var/www/html/magento2
- Database Host is on the same machine (
localhost
) - Database Name is magento2
- Database User is magento2
- Database Password is admin
So please make sure to update those values as per your requirement.
Go to Domain root Directory:
cd /var/www/html/magento2
Execute below command:
bin/magento setup:install \
--base-url=http://localhost \
--db-host=localhost \
--db-name=magento2 \
--db-user=magento2 \
--db-password=admin \
--admin-firstname=Admin \
--admin-lastname=Admin \
--admin-email=admin@admin.com \
--admin-user=admin \
--admin-password=admin123 \
--language=en_US \
--currency=USD \
--timezone=America/Chicago \
--use-rewrites=1
Once you will execute above command it should successfully install Magento 2.4.1

Setup Google Authenticator for Two Factor Authentication
Below are the steps to Setup 2FA or Fix Two Factor Authentication issue with initial installation of Magento 2.4.1
- Select Google Authenticator as the 2FA provider:
bin/magento config:set twofactorauth/general/force_providers google
- Increase the lifetime of the window to 60 seconds to prevent tokens from expiring.
bin/magento config:set twofactorauth/google/otp_window 60
- Generate a Base32-encoded string for the shared secret value
For example, encoding the string secretkey1
with the online [Base32 Encode][13] tool ( https://cryptii.com/pipes/base32 ) returns the value ONSWG4TFORVWK6JR
.
Please make sure to change ONSWG4TFORVWK6JR string as per your secret key in below commands
- Add the encoded shared secret to Google Authenticator.
bin/magento security:tfa:google:set-secret admin ONSWG4TFORVWK6JR

- Open Google Authenticator Application on your mobile and Add new Key ONSWG4TFORVWK6JR
- Once you will add Your key you will see Authenticator code in application. Copy that Authenticator code and use it to login in magento 2 admin panel.



Disable Magento_TwoFactorAuth Module in Magento 2.4

If you are installing magento2 on local system or want a quick access you can execute below command to disable Magento_TwoFactorAuth module in magento 2.4.1
sudo bin/magento module:disable Magento_TwoFactorAuth

If you want to enable Magento_TwoFactorAuth module you can use below command
sudo bin/magento module:enable Magento_TwoFactorAuth
I hope you are able to install Magento 2.4 with this guide. Please let me know in the comment below if you are facing any issue in installation with this guide.
Thanks for share this knowledge
Perfect!! Thank you so much for your content, great tutorial.
Great! Thanks for the tutorial. I tried with Windows + Virtualbox, Windows + Docker, Windows + Xampp and finally tried Ubuntu 20.x + LAMP and this is the first tutorial that actually worked.
Thank you so much, it was really very very helpful. You really made my life easy.