How to Deploy Next JS in VPS Ubuntu Server

Feature Image

So, you've built an awesome web application using Next.js, and now you're ready to share it with the world! While services like Vercel or Netlify offer fantastic deployment experiences, sometimes you need more control, customizability, or simply prefer to host your applications on your own infrastructure. That's where a Virtual Private Server (VPS) comes in. Learning how to deploy Next.js on a VPS might seem daunting at first, but it gives you immense power and flexibility over your environment. This comprehensive guide will walk you through every step, making the process clear and manageable, whether you're a seasoned developer or just starting your deployment journey.

Why Deploy Next.js on a VPS?

Before we dive into the nitty-gritty, let's understand why choosing a VPS for your Next.js application can be a game-changer:

  • Full Control: A VPS gives you root access, meaning you have complete control over the operating system, server configurations, and installed software. This is crucial for optimizing performance, installing specific libraries, or setting up complex server-side logic.
  • Cost-Effectiveness for Scale: While managed hosting might be convenient for small projects, a VPS can become more cost-effective as your application grows and demands more resources. You pay for what you use and can scale up resources as needed.
  • Customization: You can install any database, caching system, or other services directly on your server, tailoring the environment exactly to your application's needs.
  • Learning Opportunity: Setting up a server from scratch is an invaluable learning experience. It deepens your understanding of networking, server management, and application architecture.

Prerequisites for VPS Deployment

Before we touch the terminal, ensure you have the following:

  • A VPS Provider: Choose a reliable provider (e.g., DigitalOcean, Linode, AWS Lightsail, Vultr). For this tutorial, we'll assume a fresh Ubuntu 20.04 or 22.04 LTS instance.
  • SSH Client: A way to connect to your VPS (e.g., Terminal on macOS/Linux, PuTTY on Windows, or WSL).
  • Domain Name (Optional but Recommended): If you want your application accessible via a friendly URL (e.g., yournextapp.com). Make sure its DNS records (A record) point to your VPS's IP address.
  • Basic Linux Command Line Knowledge: Familiarity with commands like sudo, apt, cd, ls, etc.
  • Your Next.js Application: Make sure your Next.js app is ready for production.

Setting Up Your VPS Environment

Our first step is to get your VPS ready for action. Connect to your VPS via SSH:

ssh your_user@your_vps_ip_address

Disclaimer: all tutorials here use Ubuntu OS VPS.

1. Update Your System

Always start by updating your package lists and upgrading installed packages:

sudo apt update
sudo apt upgrade -y

2. Install Node.js and npm

Next.js requires Node.js. We recommend using a Node Version Manager (NVM) for easy management, but you can also install directly via apt if you prefer a simpler route for a single project.

Method A: Using NVM (Recommended)

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash
source ~/.bashrc # or ~/.zshrc if you use zsh
nvm install --lts # Installs the latest LTS version of Node.js
nvm list-remote  # ask NVM which versions of Node are available
nvm use --lts  # or nvm install v22.16.0  to select specific version
node -v # Verify installation
npm -v # Verify installation
sudo apt install npm  # for install npm

For detail installation NVM Read Here

Method B: Using Apt (Quicker, but less flexible)

sudo apt install nodejs
node -v
npm -v 
sudo apt install npm  # for install npm

3. Install Git

Git adalah salah satu sistem kontrol versi yang paling populer. In this case, git is used to clone the nextjs app from the github repository (if you use this method). Another way to transfer your project to a VPS is to use FTP.

sudo apt install git
git -v  # Verify installation

4. Install PM2 for Process Management

PM2 is a production process manager for Node.js applications. It keeps your application running forever, reloads it without downtime, and facilitates common system admin tasks.

npm install pm2 -g
pm2 -v  # Verify installation

To ensure PM2 starts automatically on server reboot, run:

pm2 startup systemd
# Follow the instructions output by the command above to copy-paste the generated command (optional).
# It will look something like: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u your_user --hp /home/your_user

5. Install Nginx as a Reverse Proxy

Nginx is a high-performance web server that will act as a reverse proxy, forwarding requests from the internet to your Next.js application running on a specific port.

sudo apt install nginx -y
sudo ufw allow 'Nginx Full' # Open firewall for Nginx (HTTP and HTTPS)
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx # Check if Nginx is running

This tutorial does not cover reverse proxies.

Transferring Your Next.js Application

Now, let's get your Next.js code onto your VPS. The easiest way is using Git.

1. Clone Your Repository

Navigate to a suitable directory (e.g., your home directory or /home/myapp or /var/www/) and clone your Next.js repository:

cd /home/myapp/ # Or your preferred directory
git clone https://github.com/your-username/your-next-app.git . # Clone into the current directory
cd your-next-app  # your git clone folder

If your repository is private, you'll need to set up SSH keys or use a personal access token.

Configuring Your Next.js Application

1. Install Dependencies and Build

Once your code is on the VPS, navigate into your application's directory and install its dependencies, then build it for production:

cd /home/myapp/your-next-app  # your git clone folder/your nextjs app folder (goto you nextjs app directory)
npm install
npm run build

2. Start Your Application with PM2

PM2 will run your Next.js application. Next.js by default runs on port 3000. We'll tell PM2 to start it:

pm2 start npm --name "my-next-app" -- run start

If you want to run it on a custom port:

pm2 start npm --name name_of_the_app -- start -- --port your_port

Replace "my-next-app" with a name you prefer. This command tells PM2 to run the npm run start script, which is Next.js's production start command.

Check the status:

pm2 list  # or  pm2 status

You should see your application listed as 'online'.

PM2 can generate startup scripts and configure them in order to keep your process list intact across expected or unexpected machine restarts. Followign this command:

pm2 save
pm2 startup

Congratulations, you have successfully published your application to the public. Now try accessing the application via http://your_public_ip_vps:your_port/.
Since no reverse proxy has been set up, access is via the VPS public IP. If a reverse proxy has been set up with your domain, you can access it via that domain!

If you want to run a another Node.js or Express.js application, you can do so in the following way:

pm2 start app.js --name my_node_app  # For running another node js app

app.js is file/root file of node/express js application

Common Challenges and How to Overcome Them

Even with a detailed guide, you might run into bumps. Here are some common issues and their solutions:

1. Firewall Issues (ufw)

Problem: You can't access your app even after Nginx is running.

Solution: Ensure your firewall (UFW) allows traffic on ports 80 (HTTP) and 443 (HTTPS).

sudo ufw status # Check current rules
sudo ufw allow # Allows allow port
sudo ufw enable # Enable UFW if it's not already
sudo ufw reload

sudo ufw allow [port_number]/[protocol]  # protoco: tcp or udp

2. Environment Variables

Problem: Your Next.js app works locally but fails on the server due to missing API keys or other configurations.

Solution: Next.js environment variables (e.g., those starting with NEXT_PUBLIC_) are baked into the build. Others might need to be set on the server. You can pass them to PM2:

pm2 start npm --name "my-next-app" -- run start --env production -- MY_API_KEY="your_secret_key"

For more complex scenarios, consider using a .env file in your app's root directory on the server, ensuring it's not committed to Git.

Conclusion

Deploying your Next.js application on a VPS is a powerful way to gain full control over your hosting environment and optimize your application's performance. While it involves a few more steps than managed services, the knowledge and flexibility you gain are invaluable. By following this comprehensive tutorial, you've learned how to set up your VPS, configure Node.js and Nginx, manage your application with PM2. You're now equipped to take your Next.js projects to the next level of production deployment!

What are your experiences with VPS deployments? Share your own tips and tricks in the comments section below!

Comments

Login to comment