In this tutorial, you’ll deploy a React / Next.js application on Ubuntu EC2 instance running Apache2. You’ll deploy an application using GitHub repository, use an Apache2 config file to determine where to deploy files, and securely run with apache2 proxy server. By the end of this tutorial, you’ll be able to build and deploy a React application.
Prerequisites
- You need a ubuntu ec2 instance in AWS server
- First Install nvm and start to Install Node with nvm
~ sudo apt-get update
~ sudo curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
- Activate the nvm
~ . ~/.nvm/nvm.sh
- Install Node.js with nvm and check the version.
~ nvm install node
~ node -v
- Install PM2 to manage proxy server
~ npm i -g pm2
Now you need to create a project directory and change the ownership to ubuntu and give permission to initialize a git repository.
- Make a directory and change the ownership to ubuntu
~ sudo mkdir project_name
~ sudo chown -R ubuntu:ubuntu directory_name
~ sudo chmod 777 DIR_NAME cd DIR_NAME # change permission
- Add your Github Repository in your project. If you want to generate SSH key for GitHub check the link.
~ cd project_directory #go to your project directory
~ git init
~ git remote add origin repository_path #add your repo path
~ git pull origin main
Finally, you are ready to build the project and run it with proxy server.
- For development mode with next.js application
~ pm2 start npm --name "project_name" -- run dev
- For production mode [React / Next.js] - Start or Run node server with pm2
~ npm run build
~ pm2 start npm --name "project_name" -- start
~ pm2 start npm --name "project_name" -- start -- --port=3001 #Start project with specific port if needed
- See logs at
~ nano /.pm2/logs/XXX-err.log
- For watching file changes, add below flag with start command
--watch Synchronous
- Save the proxy server
~ pm2 save ***
~ pm2 startup
At the end, to deploy the application, you need to configure the Apache server.
Apache Server Configuration
- First enable the Proxy Server
~ sudo a2enmod proxy
~ sudo a2enmod proxy_http
- Restart the Apache server
~ sudo service apache2 restart
- Error log command
~ tail -10 /var/log/apache2/error.log
- Make .conf file and configure with your domain on /etc/apache2/sites-available/
~ sudo nano example.conf
- Paste the following configurations and update with your own way.
<VirtualHost *:80>
ServerName domain.com
ServerAlias www.domain.com
ProxyRequests Off
ProxyPreserveHost On
ProxyVia Full
<Proxy *>
Require all granted
</Proxy>
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
</VirtualHost>
- Enable the newly created .conf file and disable the default one.
~ sudo a2ensite example.conf
~ Sudo a2dissite default.conf
- Restart the server
~ sudo service apache2 restart
Done! Now you can browse your application with the domain name.
Top comments (0)