How To Deploy Next JS App to AWS EC2

How To Deploy Next JS App to AWS EC2

How To Deploy Next JS App to AWS EC2

Deploying a Next.js application to AWS EC2 can seem challenging at first, but with the right guidance, it becomes a straightforward process. This comprehensive guide will walk you through every step, from setting up your EC2 instance to running your production-ready Next.js app live on the web. Whether you are a beginner or a professional developer, this tutorial will help you master AWS EC2 deployment for your Next.js project.

What Is AWS EC2?

Amazon EC2 (Elastic Compute Cloud) is a cloud-based service that provides resizable computing capacity. It allows developers to deploy web applications on virtual servers without worrying about physical hardware. You can choose the operating system, network configuration, and even security settings according to your project needs.

For Next.js developers, EC2 is an ideal choice due to its scalability, performance, and control over the environment.

Prerequisites

Before you start, make sure you have the following:

  • A working Next.js project
  • An AWS account
  • Basic knowledge of terminal commands
  • Git installed on your local machine
  • An SSH key for secure server access

If you don't have an AWS account yet, visit AWS and create one. You'll also need to configure your billing method.

Step 1: Create and Configure an EC2 Instance

  1. Login to AWS Management Console
    Go to your AWS Management Console and search for EC2 under the "Services" section.

  2. Launch a New Instance

    • Click Launch Instance
    • Choose Ubuntu Server 22.04 LTS (Free Tier Eligible)
    • Select an instance type, such as t2.micro for free-tier usage
    • Configure instance details (default settings are fine for now)
    • Add storage (default 8 GB is sufficient for small apps)
    • Configure security group (allow ports 22, 80, and 443)
    • Review and launch the instance
    • Download your .pem key file --- this is required for SSH access
  3. Connect to Your Instance
    Use the command below to connect to your instance (replace placeholders accordingly):

    ssh -i "your-key.pem" ubuntu@your-ec2-public-ip
    

    Once connected, you'll have access to your remote Ubuntu server.

Step 2: Install Node.js and NPM on EC2

Next.js requires Node.js and NPM to run.

sudo apt update
sudo apt install nodejs npm -y

Check versions to confirm installation:

node -v
npm -v

If you need a specific Node version, use nvm (Node Version Manager):

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
source ~/.bashrc
nvm install 18

This ensures compatibility with your Next.js version.

Step 3: Clone Your Next.js Project

If your project is hosted on GitHub or GitLab, clone it using:

git clone https://github.com/yourusername/your-nextjs-project.git
cd your-nextjs-project

Alternatively, you can upload your files manually using an SFTP tool like FileZilla.

Step 4: Install Dependencies

Inside your project folder, run:

npm install

This will install all required dependencies defined in package.json.

Step 5: Build the Next.js App

Before deployment, build your application for production:

npm run build

This command optimizes your Next.js app for the best performance.

Step 6: Run the App Locally

You can test your build locally before making it live:

npm start

Now visit your server's IP address on port 3000:
http://your-ec2-public-ip:3000

If you see your app running, you're good to proceed.

Step 7: Set Up a Process Manager (PM2)

You don't want your app to stop running if you close the terminal. Use PM2, a production process manager:

sudo npm install -g pm2
pm2 start npm --name "nextjs-app" -- start
pm2 startup
pm2 save

Now your app will automatically restart if the server reboots.

Step 8: Configure Reverse Proxy with Nginx

Nginx is used to serve your app over HTTP/HTTPS.

  1. Install Nginx

    sudo apt install nginx -y
    
  2. Edit Nginx Configuration

    sudo nano /etc/nginx/sites-available/default
    

    Replace the file content with:

    server {
        listen 80;
        server_name your-domain.com www.your-domain.com;
    
        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;
        }
    }
    
  3. Restart Nginx

    sudo systemctl restart nginx
    

Now your app will be accessible through your domain.

Step 9: Set Up a Domain and SSL (Optional but Recommended)

To make your website secure, you can set up SSL using Certbot:

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

Follow the prompts to automatically install and configure SSL certificates.

Step 10: Automate Deployment (Optional)

For continuous deployment, you can integrate GitHub Actions or AWS CodeDeploy. This allows automatic updates every time you push to your main branch.

Example GitHub Actions workflow:

name: Deploy Next.js to EC2

on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2

      - name: SSH to EC2 and Deploy
        uses: appleboy/ssh-action@v0.1.6
        with:
          host: ${{ secrets.EC2_HOST }}
          username: ubuntu
          key: ${{ secrets.EC2_SSH_KEY }}
          script: |
            cd /home/ubuntu/your-nextjs-project
            git pull origin main
            npm install
            npm run build
            pm2 restart all

Step 11: Troubleshooting Common Issues

  • Port already in use: Kill the existing process using sudo lsof -i :3000 and kill -9 PID.
  • Permission denied: Ensure your .pem key file permissions are set with chmod 400 your-key.pem.
  • App not loading on domain: Check Nginx logs with sudo tail -f /var/log/nginx/error.log.

Why Choose AWS EC2 for Next.js Deployment?

  • Scalability: Easily upgrade instance types as traffic grows.\
  • Performance: Low latency and high availability with AWS infrastructure.\
  • Flexibility: Full control over your environment.\
  • Security: Strong firewall and access control features.

Conclusion

Deploying your Next.js app on AWS EC2 is a powerful way to achieve performance, scalability, and full control over your application environment. Following the steps above ensures a smooth and efficient setup process, from server configuration to live deployment.

If you're looking for professional help with MERN Stack Development or need expert guidance in Next.js and AWS deployment, consider hiring AAMAX. AAMAX is a full-service digital marketing and web development company offering expertise in Web Development, Digital Marketing, and SEO Services. Their team of professionals can help you build, scale, and deploy your projects seamlessly using modern technologies.

Related Blogs

How To Deploy Next JS App on Cpanel

How To Deploy Next JS App on Cpanel

Deploying a Next.js app on cPanel isn’t as straightforward as on specialized platforms, but it’s completely doable with the right configuration. The k...

How To Deploy Next JS App on Vercel

How To Deploy Next JS App on Vercel

Next.js application on Vercel is an incredibly straightforward process that streamlines development and hosting into a single platform. From automated...

How To Deploy Next JS App on Netlify

How To Deploy Next JS App on Netlify

Deploying a Next.js app on Netlify is quick, efficient, and scalable. With features like automatic builds, serverless support, and global CDN hosting...

How To Deploy Next JS App to AWS

How To Deploy Next JS App to AWS

AWS has earned its reputation as a market-leading cloud service provider because of its unmatched global infrastructure, enterprise-grade tools, and d...

How To Deploy Next JS App to AWS S3

How To Deploy Next JS App to AWS S3

This approach is ideal for blogs, portfolios, marketing sites, and documentation platforms that rely on static content. Plus, with the addition of CI/...

How To Deploy Next JS App to AWS EC2

How To Deploy Next JS App to AWS EC2

Deploying your Next.js app on AWS EC2 is a powerful way to achieve performance, scalability, and full control over your application environment. Follo...

Need Help? Chat with Our AI Support Bot