How do I deploy Next.js with Nginx on DigitalOcean?
In this guide, we will set up a Next.js application with Nginx on a DigitalOcean Droplet using Pulumi. We will create a DigitalOcean Droplet, configure Nginx to serve the Next.js application, and deploy the application.
Steps to Deploy Next.js with Nginx on DigitalOcean:
- Create a DigitalOcean Droplet: This is the virtual machine where we will host our Next.js application.
- Install and Configure Nginx: Nginx will act as a reverse proxy to serve our Next.js application.
- Deploy the Next.js Application: We will deploy our Next.js application on the Droplet.
import * as pulumi from "@pulumi/pulumi";
import * as digitalocean from "@pulumi/digitalocean";
// Create a new DigitalOcean Droplet
const droplet = new digitalocean.Droplet("nextjs-droplet", {
region: digitalocean.Region.NYC3,
size: "s-1vcpu-1gb",
image: "ubuntu-20-04-x64",
sshKeys: [/* Add your SSH key fingerprint here */],
userData: `#!/bin/bash
apt-get update
apt-get install -y nginx git nodejs npm
git clone https://github.com/your-github-repo/nextjs-app.git /var/www/nextjs-app
cd /var/www/nextjs-app
npm install
npm run build
npm install -g pm2
pm2 start npm --name "nextjs-app" -- start
rm /etc/nginx/sites-enabled/default
cat << 'EOF' > /etc/nginx/sites-available/nextjs-app
server {
listen 80;
server_name _;
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;
}
}
EOF
ln -s /etc/nginx/sites-available/nextjs-app /etc/nginx/sites-enabled/
systemctl restart nginx
`,
tags: ["nextjs", "nginx"],
});
// Export the Droplet's IP address
export const dropletIp = droplet.ipv4Address;
Key Points:
- DigitalOcean Droplet: We create a Droplet with Ubuntu 20.04 as the base image.
- Nginx Configuration: Nginx is installed and configured to act as a reverse proxy for the Next.js application.
- Next.js Deployment: The Next.js application is cloned from a GitHub repository, built, and started using PM2.
Summary:
We successfully set up a DigitalOcean Droplet, installed and configured Nginx, and deployed a Next.js application. The Nginx server serves as a reverse proxy to the Next.js application running on the Droplet. This setup ensures that your Next.js application is accessible via the Droplet’s public IP address.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.