ReactJS · 11 min read · Dec 21, 2025
Como Instalar ReactJS com Nginx no Ubuntu 22.04

React.js é um framework JavaScript gratuito e de código aberto desenvolvido pelo Facebook em 2011. É usado para construir componentes de UI reutilizáveis e ajuda os usuários a criar aplicativos web ricos e envolventes de forma rápida e eficiente com codificação mínima. Com o React, você pode construir uma interface web interativa e compor UIs complexas a partir de pequenos e isolados pedaços. Ele usa o Virtual DOM, o que torna o aplicativo rápido. Ele fornece muitos recursos, como Virtual DOM, Vinculação de Dados Unidirecional, Componentes, JSX, Declarações Condicionais e muitos mais.
Neste tutorial, mostraremos como instalar o React.js no Ubuntu 22.04.
Pré-requisitos
- Um servidor rodando Ubuntu 22.04.
- Nome de domínio válido apontado para o IP do seu servidor.
- Uma senha de root configurada no servidor.
Começando
Primeiro, você precisará atualizar os pacotes do seu sistema para a versão mais recente. Você pode atualizá-los usando o seguinte comando:
apt-get update -y
apt-get upgrade -yUma vez que todos os pacotes estejam atualizados, execute o seguinte comando para instalar outras dependências necessárias:
apt-get install curl gnupg2 -yUma vez que todas as dependências estejam instaladas, você pode prosseguir para o próximo passo.
Instalar Node.js
Em seguida, você precisará instalar o Node.js no seu servidor. Por padrão, a versão mais recente do Node.js não está disponível no repositório padrão do Ubuntu 22.04. Portanto, você precisará instalar o Node.js a partir do repositório oficial do Node.js.
Primeiro, adicione o repositório do Node.js com o seguinte comando:
curl -sL https://deb.nodesource.com/setup_18.x | bash -Em seguida, execute o seguinte comando para instalar o Node.js no seu sistema:
apt-get install nodejs -yApós instalar o Node.js, atualize o NPM para a versão mais recente usando o seguinte comando:
npm install npm@latest -gVocê deve obter a seguinte saída:
removed 14 packages, changed 73 packages, and audited 223 packages in 3s
14 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Em seguida, verifique a versão instalada do Node.js com o seguinte comando:
node -vVocê deve obter a seguinte saída:
v18.12.1
Uma vez que você tenha terminado, pode prosseguir para o próximo passo.
Instalar a Ferramenta Create React App
Create React App é uma ferramenta CLI que ajuda os usuários a economizar tempo na configuração e configuração. Você só precisa executar um único comando e o Create React App configurará todas as ferramentas necessárias para iniciar seu projeto.
Você pode instalar a ferramenta Create React App usando o seguinte comando:
npm install -g create-react-appUma vez que você tenha terminado, pode prosseguir para o próximo passo.
Criar um Aplicativo React de Exemplo
Nesta seção, criaremos um aplicativo React de exemplo com a ferramenta Create React App.
Primeiro, mude o diretório para /opt e crie seu primeiro projeto com o seguinte comando:
cd /opt
create-react-app reactappVocê deve ver a seguinte saída:
Success! Created reactapp at /opt/reactapp
Inside that directory, you can run several commands:
npm start
Starts the development server.
npm run build
Bundles the app into static files for production.
npm test
Starts the test runner.
npm run eject
Removes this tool and copies build dependencies, configuration files
and scripts into the app directory. If you do this, you can’t go back!
We suggest that you begin by typing:
cd reactapp
npm start
Happy hacking!
Em seguida, mude o diretório para o diretório do seu projeto e inicie seu aplicativo com o seguinte comando:
cd /opt/reactapp
npm startVocê deve obter a seguinte saída:
Compiled successfully!
You can now view reactapp in the browser.
http://localhost:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
webpack compiled successfully
Pressione CTRL+C para parar o aplicativo. Criaremos um arquivo de serviço systemd para gerenciar o aplicativo React.
Criar um Serviço Systemd para o Aplicativo React
Em seguida, você precisará criar um serviço systemd para seu aplicativo React. Você pode criá-lo com o seguinte comando:
nano /lib/systemd/system/react.serviceAdicione as seguintes linhas:
[Service]
Type=simple
User=root
Restart=on-failure
WorkingDirectory=/opt/reactapp
ExecStart=npm start -- --port=3000
Salve e feche o arquivo, em seguida, recarregue o daemon do systemd com o seguinte comando:
systemctl daemon-reloadEm seguida, inicie o serviço React e habilite-o para iniciar na reinicialização do sistema executando o seguinte comando:
systemctl start react
systemctl enable reactVocê pode verificar o status do serviço React com o seguinte comando:
systemctl status reactVocê deve obter a seguinte saída:
? react.service
Loaded: loaded (/lib/systemd/system/react.service; static)
Active: active (running) since Sun 2022-11-20 11:18:50 UTC; 6s ago
Main PID: 76129 (npm start --por)
Tasks: 30 (limit: 2242)
Memory: 250.9M
CPU: 4.663s
CGroup: /system.slice/react.service
??76129 "npm start --port=3000" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
??76140 sh -c "react-scripts start --port=3000"
??76141 node /opt/reactapp/node_modules/.bin/react-scripts start --port=3000
??76148 /usr/bin/node /opt/reactapp/node_modules/react-scripts/scripts/start.js --port=3000
Nov 20 11:18:54 ubuntu2204 npm[76148]: (node:76148) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddl>
Nov 20 11:18:54 ubuntu2204 npm[76148]: (Use `node --trace-deprecation ...` to show where the warning was created)
Nov 20 11:18:54 ubuntu2204 npm[76148]: (node:76148) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMid>
Nov 20 11:18:54 ubuntu2204 npm[76148]: Starting the development server...
Nov 20 11:18:55 ubuntu2204 npm[76148]: Compiled successfully!
Nov 20 11:18:55 ubuntu2204 npm[76148]: You can now view reactapp in the browser.
Nov 20 11:18:55 ubuntu2204 npm[76148]: http://localhost:3000
Nov 20 11:18:55 ubuntu2204 npm[76148]: Note that the development build is not optimized.
Nov 20 11:18:55 ubuntu2204 npm[76148]: To create a production build, use npm run build.
Nov 20 11:18:55 ubuntu2204 npm[76148]: webpack compiled successfully
Uma vez que você tenha terminado, pode prosseguir para o próximo passo.
Configurar o Nginx como um Proxy Reverso
É uma boa ideia instalar e configurar o Nginx como um proxy reverso para o Aplicativo React. Assim, você pode acessar seu aplicativo através da porta 80.
Primeiro, instale o pacote Nginx usando o seguinte comando:
apt-get install nginx -yUma vez que o Nginx esteja instalado, crie um novo arquivo de configuração de host virtual do Nginx:
nano /etc/nginx/sites-available/reactjs.confAdicione as seguintes linhas:
upstream backend {
server localhost:3000;
}
server {
listen 80;
server_name reactjs.example.com;
location / {
proxy_pass http://backend/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forward-Proto http;
proxy_set_header X-Nginx-Proxy true;
proxy_redirect off;
}
}
Salve e feche o arquivo, em seguida, habilite o host virtual do Nginx com o seguinte comando:
ln -s /etc/nginx/sites-available/reactjs.conf /etc/nginx/sites-enabled/Em seguida, verifique o Nginx para qualquer erro de sintaxe executando o seguinte comando:
ginx -tVocê deve obter a seguinte saída:
ginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Finalmente, reinicie o serviço Nginx para aplicar as alterações:
systemctl restart nginxVocê também pode verificar o status do serviço Nginx com o seguinte comando:
systemctl status nginxVocê deve ver a seguinte saída:
? nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2022-11-20 11:20:17 UTC; 6s ago
Docs: man:nginx(8)
Process: 76760 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Process: 76762 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
Main PID: 76763 (nginx)
Tasks: 2 (limit: 2242)
Memory: 2.6M
CPU: 32ms
CGroup: /system.slice/nginx.service
??76763 "nginx: master process /usr/sbin/nginx -g daemon on; master_process on;"
??76764 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" "" ""
Nov 20 11:20:17 ubuntu2204 systemd[1]: Starting A high performance web server and a reverse proxy server...
Nov 20 11:20:17 ubuntu2204 systemd[1]: Started A high performance web server and a reverse proxy server.
Neste ponto, o Nginx está instalado e configurado para servir o Aplicativo React. Você pode agora prosseguir para o próximo passo.
Proteger o React.js com Let’s Encrypt
Em seguida, você precisará instalar o pacote cliente Certbot para instalar e gerenciar o SSL Let’s Encrypt.
Primeiro, instale o Certbot com o seguinte comando:
apt-get install python3-certbot-nginx -yUma vez que a instalação esteja concluída, execute o seguinte comando para instalar o SSL Let’s Encrypt no seu site:
certbot --nginx -d reactjs.example.comVocê será solicitado a fornecer um endereço de e-mail válido e aceitar os termos de serviço, conforme mostrado abaixo:
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
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
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for reactjs.example.com
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/fuel.conf
Em seguida, escolha se deseja ou não redirecionar o tráfego HTTP para HTTPS, conforme mostrado abaixo:
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
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 finalizar a instalação. Você deve ver a seguinte saída:
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/fuel.conf
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://reactjs.example.com
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=reactjs.example.com
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/reactjs.example.com/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/reactjs.example.com/privkey.pem
Your cert will expire on 2023-02-20. 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"
- Your account credentials have been saved in your Certbot
configuration directory at /etc/letsencrypt. You should make a
secure backup of this folder now. This configuration directory will
also contain certificates and private keys obtained by Certbot so
making regular backups of this folder is ideal.
- 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
- We were unable to subscribe you the EFF mailing list because your
e-mail address appears to be invalid. You can try again later by
visiting https://act.eff.org.
Agora, sua aplicação web React.js está segura com o SSL Let’s Encrypt.
Acessar a Interface Web do Aplicativo React
Agora, abra seu navegador web e digite a URL https://reactjs.example.com. Você será redirecionado para a interface web do React.Js na seguinte tela:

Conclusão
Parabéns! você instalou e configurou com sucesso o React.Js no servidor Ubuntu 22.04. Agora você pode começar a construir seu próprio aplicativo baseado em React e hospedá-lo no ambiente de produção. 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.