1. Launch an EC2 Instance
2. Associate an Elastic IP ( Optional )
3. Instance Connection
4. Update the System and Install Dependencies
Run the following commands:
1. Refresh the package list to ensure the latest software versions are available.
sudo apt update
2. Upgrade all installed packages to their latest versions without prompting.
sudo apt upgrade -y
3. Install Node.js and npm to run and manage your Next.js application.
sudo apt install -y nodejs npm
5. Install Nginx to serve as a web server and reverse proxy for your app.
sudo apt install -y nginx
6. Navigate to the '/var/www/html' directory to put your project files.
cd /var/www/html
7. Create a new project directory ( optional ).
sudo mkdir myapp
8. Grant permissions to the project directory.
sudo chmod -R 777 /var/www/html/myapp
9. Globally install PM2 to keep your Next.js app running in the background.
sudo npm install -g pm2
10. Open the default Nginx configuration file for editing in the nano text editor.
sudo nano /etc/nginx/sites-available/default
11. Add the following configuration.
server {
server_name your-ip-or-domain;
root /var/www/html/myapp/.next;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
12. Test the Nginx configuration file for syntax errors before applying changes.
sudo nginx -t
13. Start the Nginx service to reload the updated configuration.
sudo systemctl start nginx
14. Go to your repository > Settings > Secrets and variables > Actions.
15. Create the GitHub Actions workflow for auto-deployment in
16. Add the following configuration in the deploy.yml file
name: Push-to-EC2
on:
push:
branches:
- master # Triggers on push to master branch
jobs:
deploy:
name: Deploy to EC2 on master branch push
runs-on: ubuntu-latest
steps:
- name: Checkout the files
uses: actions/checkout@v2
- name: Deploy to Server
uses: easingthemes/ssh-deploy@main
env:
SSH_PRIVATE_KEY: ${{ secrets.EC2_KEY }}
REMOTE_HOST: ${{ secrets.EC2_HOST }}
REMOTE_USER: ${{ secrets.EC2_USERNAME }}
TARGET: ${{ secrets.EC2_TARGETDIR }}
- name: Execute remote SSH commands
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USERNAME }}
key: ${{ secrets.EC2_KEY }}
script: |
cd /var/www/html/myapp
git pull origin master
npm install
npm run build
pm2 restart next-app || pm2 start npm --name "next-app" -- start
17. Commit and push your Next.js application to the master branch
git push
18. GitHub Actions will automatically deploy your application to your EC2 instance.
19. Open a browser and visit 'http://your-ip-address' to access your running Next.js application.