Magento Installation · 11 min read · Sep 26, 2025
Como Instalar Magento com Apache e Let's Encrypt SSL no Ubuntu 22.04

Magento é uma plataforma de eCommerce de código aberto e uma das mais populares que ajuda programadores a criar sites de eCommerce. É escrito em PHP, permitindo que você crie um sistema de carrinho de compras flexível. É totalmente personalizável e permite que você desenvolva e lance uma loja online totalmente funcional em minutos. O Magento oferece uma versão comunitária gratuita e uma versão comercial, a versão comunitária é gratuita e é projetada para pequenas empresas, enquanto a versão comercial é projetada para empresas de médio a grande porte.
Este tutorial mostrará como instalar o Magento no Ubuntu 22.04.
Pré-requisitos
- Um servidor rodando Ubuntu 22.04.
- Um nome de domínio válido apontado para o IP do seu servidor.
- Uma senha de root configurada no servidor.
Instalar Apache, MySQL e PHP
Primeiro, instale o servidor web Apache e o servidor de banco de dados MySQL usando o seguinte comando:
apt install apache2 mysql-server -yO Magento suporta apenas as versões PHP 7.3 a 7.4. No entanto, a versão PHP 7.4 não está incluída no repositório padrão do Ubuntu 22.04, pois fornece o PHP 8.1 como a versão padrão. Portanto, você precisará instalar o PHP 7.4 do repositório PHP Ondrej.
Primeiro, instale as dependências necessárias usando o seguinte comando:
apt install software-properties-common -yEm seguida, adicione o repositório PHP Ondrej usando o seguinte comando:
add-apt-repository ppa:ondrej/phpUma vez que o repositório é adicionado, atualize o repositório e instale o PHP com outras dependências necessárias usando o seguinte comando:
apt update -y
apt install php7.4 libapache2-mod-php7.4 php7.4-common php7.4-gmp php7.4-curl php7.4-soap php7.4-bcmath php7.4-intl php7.4-mbstring php7.4-xmlrpc php7.4-mysql php7.4-gd php7.4-xml php7.4-cli php7.4-zip -yEm seguida, edite o arquivo de configuração do PHP e altere as configurações padrão:
nano /etc/php/7.4/apache2/php.iniAltere os seguintes valores:
file_uploads = On
allow_url_fopen = On
short_open_tag = On
memory_limit = 512M
upload_max_filesize = 128M
max_execution_time = 3600
Salve e feche o arquivo e reinicie o serviço Apache para aplicar as alterações de configuração:
systemctl restart apache2Uma vez que você tenha terminado, pode prosseguir para a próxima etapa.
Criar um Banco de Dados para Magento
O Magento usa o MySQL como um backend de banco de dados, então você precisará criar um banco de dados e um usuário para o Magento.
Primeiro, faça login no shell do MySQL com o seguinte comando:
mysqlUma vez conectado ao MySQL, crie um usuário e um banco de dados para o Magento usando o seguinte comando:
mysql> CREATE DATABASE magento2;
mysql> CREATE USER 'magento2'@'localhost' IDENTIFIED BY 'password';Em seguida, conceda todas as permissões ao banco de dados Magento2:
mysql> GRANT ALL PRIVILEGES ON magento2.* TO 'magento2'@'localhost';Em seguida, limpe as permissões e saia do MySQL com o seguinte comando:
mysql> FLUSH PRIVILEGES;
mysql> EXIT;Instalar o Composer
O Composer é um gerenciador de dependências para PHP usado para instalar as dependências PHP necessárias para o seu projeto PHP.
Primeiro, instale a ferramenta de linha de comando Curl usando o seguinte comando:
apt-get install curl -yEm seguida, instale o Composer usando o seguinte comando:
curl -sS https://getcomposer.org/installer -o composer-setup.php
php composer-setup.php --install-dir=/usr/local/bin --filename=composerUma vez que o Composer está instalado, você receberá a seguinte saída:
All settings correct for using Composer
Downloading...
Composer (version 2.3.5) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer
Você pode verificar a versão do Composer usando o seguinte comando:
composer --versionVocê receberá a seguinte saída:
Composer version 2.3.5 2022-04-13 16:43:00
Baixar e Instalar o Magento no Ubuntu 22.04
Nesta seção, iremos baixar a versão 2.4.3 do Magento usando o Composer. Para isso, você precisará criar uma chave de acesso após fazer login no site do Magento. https://marketplace.magento.com/customer/accessKeys/. Uma vez que a chave de acesso é criada, execute o seguinte comando para baixar o Magento no seu servidor:
cd /var/www/html
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition=2.4.3 magento2Você será solicitado a fornecer sua chave de acesso, conforme mostrado abaixo, para baixar o Magento:
Creating a "magento/project-community-edition=2.4.3" project at "./magento2"
Warning from repo.magento.com: You haven't provided your Magento authentication keys. For instructions, visit https://devdocs.magento.com/guides/v2.3/install-gde/prereq/connect-auth.html
Authentication required (repo.magento.com):
Username: a6b333ad41629bac913eaabb9b8e053c
Password:
Do you want to store credentials for repo.magento.com in /root/.config/composer/auth.json ? [Yn] Y
Installing magento/project-community-edition (2.4.3)
- Downloading magento/project-community-edition (2.4.3)
- Installing magento/project-community-edition (2.4.3): Extracting archive
Created project in /var/www/html/magento2
Loading composer repositories with package information
Info from https://repo.packagist.org: #StandWithUkraine
Uma vez que o Magento é baixado, defina a propriedade e permissão adequadas para o diretório do Magento:
chown -R www-data:www-data /var/www/html/magento2/
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 {} +
chown -R :www-data .
chmod u+x bin/magentoEm seguida, execute o seguinte comando para instalar o Magento no seu servidor:
bin/magento setup:install --base-url=http://magento.example.com --db-host=localhost --db-name=magento2 --db-user=magento2 --db-password=password --admin-firstname=Hitesh --admin-lastname=Jethva [email protected] --admin-user=admin --admin-password=Magento@Secure1Password --language=en_US --currency=USD --timezone=America/Chicago --use-rewrites=1Você receberá o seguinte erro:
Could not validate a connection to Elasticsearch. No alive nodes found in your cluster Você pode resolver esse erro usando o seguinte comando:
php bin/magento module:disable {Magento_Elasticsearch,Magento_InventoryElasticsearch,Magento_Elasticsearch6,Magento_Elasticsearch7}Você deve ver a seguinte saída:
The following modules have been disabled:
- Magento_Elasticsearch
- Magento_Elasticsearch6
- Magento_InventoryElasticsearch
- Magento_Elasticsearch7
Cache cleared successfully.
Generated classes cleared successfully. Please run the 'setup:di:compile' command to generate classes.
Info: Some modules might require static view files to be cleared. To do this, run 'module:disable' with the --clear-static-content option to clear them.
Você também precisará executar o seguinte comando para desativar a autenticação de dois fatores:
sudo -u www-data bin/magento module:disable Magento_TwoFactorAuthVocê receberá a seguinte saída:
The following modules have been disabled:
- Magento_TwoFactorAuth
Cache cleared successfully.
Generated classes cleared successfully. Please run the 'setup:di:compile' command to generate classes.
Info: Some modules might require static view files to be cleared. To do this, run 'module:disable' with the --clear-static-content option to clear them.
Agora, execute o comando de instalação do Magento novamente para iniciar a instalação:
bin/magento setup:install --base-url=http://magento.example.com --db-host=localhost --db-name=magento2 --db-user=magento2 --db-password=password --admin-firstname=Hitesh --admin-lastname=Jethva [email protected] --admin-user=admin --admin-password=Magento@Secure1Password --language=en_US --currency=USD --timezone=America/Chicago --use-rewrites=1Uma vez que a instalação esteja completa, você receberá a seguinte saída:
[Progress: 1359 / 1366]
Module 'Yotpo_Yotpo':
[Progress: 1360 / 1366]
Enabling caches:
Current status:
layout: 1
block_html: 1
full_page: 1
[Progress: 1361 / 1366]
Installing admin user...
[Progress: 1362 / 1366]
Caches clearing:
Cache cleared successfully
[Progress: 1363 / 1366]
Disabling Maintenance Mode:
[Progress: 1364 / 1366]
Post installation file permissions check...
For security, remove write permissions from these directories: '/var/www/html/magento2/app/etc'
[Progress: 1365 / 1366]
Write installation date...
[Progress: 1366 / 1366]
[SUCCESS]: Magento installation complete.
[SUCCESS]: Magento Admin URI: /admin_1u9o0y
Nothing to import.
Agora, limpe todo o cache e crie um trabalho cron do Magento usando os seguintes comandos:
sudo -u www-data bin/magento cache:flush
sudo -u www-data bin/magento cron:installUma vez que você tenha terminado, pode prosseguir para a próxima etapa.
Configurar o Apache para Magento
Em seguida, você precisará criar um arquivo de configuração de host virtual do Apache para servir o Magento na web.
nano /etc/apache2/sites-available/magento2.confAdicione as seguintes linhas:
ServerAdmin [email protected]
DocumentRoot /var/www/html/magento2/
ServerName magento.example.com
Options FollowSymlinks
AllowOverride All
Require all granted
ErrorLog ${APACHE_LOG_DIR}/magento2_error.log
CustomLog ${APACHE_LOG_DIR}/magento2_access.log combined
Salve e feche o arquivo, em seguida, ative o host virtual do Magento e o módulo de reescrita do Apache usando o seguinte comando:
a2ensite magento2.conf
a2enmod rewriteEm seguida, reinicie o serviço Apache para aplicar as alterações:
systemctl restart apache2Você também pode verificar o status do Apache com o seguinte comando:
systemctl status apache2Você deve ver a seguinte saída:
? apache2.service - The Apache HTTP Server
Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
Active: active (running) since Fri 2022-04-29 09:03:19 UTC; 2s ago
Docs: https://httpd.apache.org/docs/2.4/
Process: 39790 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
Main PID: 39794 (apache2)
Tasks: 6 (limit: 4630)
Memory: 14.1M
CPU: 132ms
CGroup: /system.slice/apache2.service
??39794 /usr/sbin/apache2 -k start
??39795 /usr/sbin/apache2 -k start
??39796 /usr/sbin/apache2 -k start
??39797 /usr/sbin/apache2 -k start
??39798 /usr/sbin/apache2 -k start
??39799 /usr/sbin/apache2 -k start
Apr 29 09:03:19 ubuntu systemd[1]: Starting The Apache HTTP Server...
Acessar a Interface Web do Magento
Agora, abra seu navegador e acesse o painel do Magento usando a URL http://magento.example.com/admin_1u9o0y. Você será redirecionado para a página de login do Magento:

Forneça seu nome de usuário e senha de administrador e clique no botão Login. Você deve ver o painel do Magento na tela seguinte:

Proteger o Magento com Let’s Encrypt SSL
É sempre uma boa ideia proteger seu site com Let’s Encrypt SSL. Você precisará instalar o cliente Certbot para instalar e gerenciar o SSL. Você pode instalá-lo com o seguinte comando:
apt-get install python3-certbot-apache -yUma vez que o Certbot está instalado, execute o seguinte comando para proteger seu site com Let’s Encrypt SSL:
certbot --apache -d magento.example.comVocê será solicitado a fornecer seu e-mail e aceitar os termos de serviço, conforme mostrado abaixo:
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator standalone, Installer None
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel): [email protected]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v02.api.letsencrypt.org/directory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(A)gree/(C)ancel: A
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about our work
encrypting the web, EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(Y)es/(N)o: Y
Plugins selected: Authenticator apache, Installer apache
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for magento.example.com
Enabled Apache rewrite module
Waiting for verification...
Cleaning up challenges
Created an SSL vhost at /etc/apache2/sites-available/magento-le-ssl.conf
Enabled Apache socache_shmcb module
Enabled Apache ssl module
Deploying Certificate to VirtualHost /etc/apache2/sites-available/magento-le-ssl.conf
Enabling available site: /etc/apache2/sites-available/magento-le-ssl.conf
Em seguida, selecione se deseja ou não redirecionar o tráfego HTTP para HTTPS, conforme mostrado abaixo:
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Digite 2 e pressione Enter para instalar o Let’s Encrypt SSL para seu site:
Enabled Apache rewrite module
Redirecting vhost in /etc/apache2/sites-enabled/magento.conf to ssl vhost in /etc/apache2/sites-available/magento-le-ssl.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://magento.example.com
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=magento.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/magento.example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/magento.example.com/privkey.pem
Your cert will expire on 2023-01-23. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all*
of your certificates, run "certbot renew"
- If you like Certbot, please consider supporting our work by:
Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le
Agora, você pode acessar seu site com segurança usando a URL https://magento.example.com.
Conclusão
Parabéns! você instalou com sucesso o Magento com Apache no Ubuntu 22.04. Espero que este post ajude você a iniciar seu próprio sistema de carrinho de compras online. Sinta-se à vontade para me perguntar se você tiver alguma dúvida.
Receba novas postagens na sua caixa de entrada
Sem spam. Cancele a assinatura a qualquer momento.