Host Next.js Application with Nginx on AlmaLinux

By Anurag Singh

Updated on Sep 04, 2024

Host Next.js Application with Nginx on AlmaLinux

In this tutorial, we'll explain how to host Next.js Application with Nginx on AlmaLinux 9 server.

In this tutorial, we'll explain how to host Next.js Application with Nginx on AlmaLinux 9 server. 

Next.js is a powerful React framework that enables developers to build fast, user-friendly web applications and websites. It simplifies the process of creating both static and dynamic web pages, offering built-in features like server-side rendering (SSR) and static site generation (SSG). These features enhance performance and SEO by allowing pages to be pre-rendered on the server.

Next.js also supports API routes, enabling developers to build full-stack applications within a single framework. With automatic code splitting, optimized performance, and a rich ecosystem of plugins and tools, Next.js is widely used for creating robust, scalable applications that deliver excellent user experiences. It integrates seamlessly with popular tools and platforms, making it a versatile choice for modern web development.

Deploying a Next.js application on an AlmaLinux VPS with Nginx as the reverse proxy is a reliable and efficient way to serve your web application. In this tutorial, we’ll walk through the steps to set up and deploy a Next.js application on an AlmaLinux server using Nginx.

Prerequisites

Before you begin, make sure you have the following:

  • A server running AlmaLinux 9 dedicated server or KVM VPS.
  • Basic knowledge of the Linux command line.
  • A root user access or normal user with sudo rights.

Host Next.js Application with Nginx on AlmaLinux

Step 1: Update and Secure Your Server      

Before deploying your application, it’s essential to update your server packages and secure it.

sudo dnf update -y

Step 2: Install Node.js and npm

For latest version, visit the Node.js official documentation page.

# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.0/install.sh | bash

# download and install Node.js (you may need to restart the terminal)
nvm install 20

Verify the installation:

# verifies the right Node.js version is in the environment
node -v # should print `v20.17.0`

# verifies the right npm version is in the environment
npm -v # should print `10.8.2`

Step 3: Deploy Next.js Application

There are two ways to deploy it. First clone your Git repository or create a Next.js application in the server. We have covered both ways.

Clone Git Repository

Next, you'll need to transfer your Next.js application to your VPS. If your project is hosted on GitHub, you can clone it directly:

git clone https://github.com/yourusername/my-nextjs-app.git

Navigate into your project directory:

cd my-nextjs-app

Install Dependencies and Build the Application. Inside your project directory, install the necessary dependencies:

npm install

Build your Next.js application:

npm run build

Create a Next.js Application

Let's proceed with the installation.

Run the following command to create a new Next.js application using the create-next-app tool:

npx create-next-app@latest my-nextjs-app

Above command will prompt questions:

create-next-app@14.2.7
Ok to proceed? (y) y

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes

Navigate to the Project Directory. After the project is created, navigate into the project directory:

cd my-nextjs-app

To build the application for production, use:

npm run build

Step 4: Install and Configure PM2

PM2 is a process manager for Node.js applications that ensures your application stays online.

npm install -g pm2

Start your Next.js application with PM2:

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

To ensure PM2 starts your application on system boot, run:

pm2 startup systemd
pm2 save

Check the status 

pm2 status

Output:

┌────┬────────────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name               │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├────┼────────────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0  │ my-nextjs-app     │ default     │ 0.40.0  │ fork    │ 4189     │ 50s    │ 0    │ online    │ 0%       │ 55.1mb   │ root     │ disabled │
└────┴────────────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Step 5: Configure Firewall

To allow traffic on HTTP and HTTPS ports, you need to configure the firewall:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Step 6: Install and Configure Nginx as a Reverse Proxy

Nginx will act as a reverse proxy, forwarding requests from your domain to the Next.js application running on http://localhost:3000.

Install Nginx:

sudo dnf install nginx -y

Create a new Nginx configuration file for your application:

sudo vi /etc/nginx/conf.d/your-domain.conf

Add the following configuration:

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;
    }
}

Replace your-domain.com with your domain name or server IP address. Save and close the file.

 

Test the Nginx configuration to ensure there are no errors:

sudo nginx -t

If the test is successful, restart Nginx:

sudo systemctl restart nginx

Step 7: Secure Your Application with SSL

It's highly recommended to secure your application with SSL. You can use Certbot to obtain a free SSL certificate from Let's Encrypt.

First, install Certbot:

sudo dnf install certbot python3-certbot-nginx -y

Then, run Certbot to obtain and configure the SSL certificate:

sudo certbot --nginx -d your_domain

Certbot will automatically configure SSL for your Nginx site.

Step 8: Configure SELinux

If you have enabled SELinux, follow this step.

Allow Nginx to Connect to the Network:

Use the following command to allow Nginx to establish outbound connections:

sudo setsebool -P httpd_can_network_connect 1

This command changes the SELinux policy to allow the httpd service (which includes Nginx) to connect to network resources.

Step 9: Verify Your Deployment

Your Next.js application should now be running on your domain https://your_domain. Visit your domain in a web browser to verify that everything is working correctly.

Conclusion

You have successfully seen how to host Next.js Application with Nginx on AlmaLinux server. With Nginx handling incoming traffic and PM2 managing the application process, your Next.js app is well-equipped to handle production workloads. Remember to keep your server and application updated to ensure optimal security and performance.