Hosting multiple Next.js applications on a single AWS Lightsail instance or Ubuntu VPS is an efficient way to manage your projects. This guide walks you through the step-by-step process of setting up and configuring multiple Next.js apps using Nginx as a reverse proxy and PM2 for process management.
Configuring and hosting your first next js project can be found here
Set Up Your Second Next.js App
Navigate to the /var/www directory, which is commonly used for web applications:
cd /var/www
Create or Copy Your Next.js App
npx create-next-app@latest intertoonssecondnextappReplaceintertoonssecondnextappwith the desired name for your project.
Build Your Application
Navigate into your project folder and build your Next.js app:
cd intertoonssecondnextapp
npm run build
Configure Nginx as a Reverse Proxy
cd /etc/nginx/sites-available
Create a new configuration file for your second app:
sudo nano intertoonssecondnextapp
Add the Configuration
Paste the following code into the file, replacing placeholders with your app details:
server {
listen 80;
server_name intertoonssecondnextapp.intertoons.com; # Replace with your domain or IP
location /_next/static/ {
alias /var/www/intertoonssecondnextapp/.next/static/; # Update with your app path
expires 365d;
access_log off;
}
location / {
proxy_pass http://127.0.0.1:3001; # Ensure this app runs on port 3001
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;
}
}
Make sure new app will run on different port say 3001
Test Nginx Configuration
Check for syntax errors:
sudo nginx -t
If there are no errors, restart Nginx to apply the changes:
sudo systemctl restart nginx
Run the Next.js Application with PM2
Change to your app directory:
cd /var/www/intertoonssecondnextapp
Start your application using PM2:
pm2 start npm --name "intertoonssecondnextapp" -- start
Save the PM2 process list so that the app restarts automatically after a reboot:
pm2 save
pm2 startup
Verify Your Application
Visit your domain in the browser to verify that your Next.js app is running:
http://intertoonssecondnextapp.intertoons.com
Hosting Additional Next.js Apps
To host more Next.js applications:
- Repeat the steps above for each new app.
- Assign a unique port (e.g., 3002, 3003, etc.) for each application in the
proxy_passdirective. - Use a different domain or subdomain for each app in the
server_namedirective.
Conclusion
By following these steps, you can successfully host multiple Next.js applications on a single AWS Lightsail instance or Ubuntu VPS. This setup leverages Nginx for efficient reverse proxying and PM2 for robust process management, ensuring your apps are always up and running.
Let us know in the comments if you encounter any issues or have additional tips for hosting Next.js apps!