Deploying a Next.js application on an EC2 instance with PM2 and Nginx

suvankar Satpati
2 min readMar 10, 2024

--

Deploying a Next.js application on an EC2 instance with PM2 and Nginx involves setting up PM2 to manage your Next.js application process and configuring Nginx as a reverse proxy to route incoming requests to your Next.js application. Here’s a step-by-step guide:

Step 1: Launch an EC2 Instance

Launch an EC2 instance using the AWS Management Console. Choose an instance type that meets your requirements, and ensure that it has the necessary security group settings to allow inbound HTTP (port 80) and HTTPS (port 443) traffic.

Step 2: SSH into the Instance

SSH into your EC2 instance using your terminal:

ssh -i your-key.pem ec2-user@your-ec2-public-ip

Step 3: Install Node.js, npm, PM2, and Nginx

Update the package manager and install Node.js, npm, PM2, and Nginx:

sudo yum update -y
sudo yum install -y nodejs npm
sudo npm install -g pm2
sudo yum install -y nginx

Step 4: Clone Your Next.js Application

Clone your Next.js application repository or copy your application files to the EC2 instance.

Step 5: Install Dependencies and Build Your Next.js Application

Navigate to your Next.js application directory and install dependencies:

cd your-nextjs-app
npm install

Build your Next.js application:

npm run build

Step 6: Configure PM2 to Manage Your Next.js Application

Start your Next.js application with PM2:

pm2 start npm - name "your-nextjs-app" - start

Ensure PM2 starts your application automatically on server restart:

pm2 save
pm2 startup

Step 7: Configure Nginx as a Reverse Proxy

Create a new Nginx server block configuration:

sudo nano /etc/nginx/conf.d/your-nextjs-app.conf

Add the following configuration:

server {
listen 80;
server_name 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;
}
}

Replace `your-domain.com` with your actual domain name or IP address.

Step 8: Test Nginx Configuration and Restart Nginx

Test the Nginx configuration:

sudo nginx -t

If the test is successful, restart Nginx:

sudo systemctl restart nginx

Step 9: Access Your Next.js Application

You should now be able to access your Next.js application by visiting your domain name or IP address in a web browser.

That’s it! Your Next.js application is now deployed on an EC2 instance, managed by PM2, and served via Nginx.

Helpful Links: https://medium.com/@mudasirhaji/deploying-a-next-js-app-manually-on-aws-ec2-a-step-by-step-guide-58b266ff1c52

--

--

suvankar Satpati
suvankar Satpati

Written by suvankar Satpati

Traveler, cyclist, story teller

Responses (1)