🐶
Next.js

Deploy NextJS with NGINX and PM2: Step-by-Step Guide

By Filip on 10/05/2024

Learn how to deploy your Next.js application with NGINX for optimal performance and scalability.

Deploy NextJS with NGINX and PM2: Step-by-Step Guide

Table of Contents

Introduction

This guide provides a step-by-step walkthrough for deploying a Next.js application on a Linux server using Nginx as a reverse proxy and PM2 for process management. You will need a Linux server with Node.js and npm installed, a registered domain name or server IP address, and a basic understanding of the Linux command line to follow this guide. We will start by building the Next.js application for production, then install PM2 to manage the application process. Next, we will configure Nginx as a reverse proxy to handle incoming traffic and direct it to our application. Finally, we will ensure our application is running correctly and accessible via our domain name or server IP address.

Step-by-Step Guide

This guide provides a comprehensive walkthrough of deploying a Next.js application on a Linux server using Nginx as a reverse proxy and PM2 for process management.

Prerequisites:

  • A Linux server with Node.js and npm installed.
  • A registered domain name or a server IP address.
  • Basic understanding of Linux command line.

Steps:

  1. Build your Next.js application:

    Navigate to your Next.js project directory and run the following command to build the production-ready application:

    npm run build
  2. Install PM2:

    PM2 is a process manager for Node.js applications that helps keep your application running and automatically restarts it in case of crashes. Install it globally using npm:

    npm install -g pm2
  3. Create a PM2 configuration file:

    Create a file named ecosystem.config.js in your project's root directory. This file will contain the configuration for PM2 to manage your Next.js application. Here's an example:

    module.exports = {
      apps: [{
        name: 'your-app-name',
        script: 'npm',
        args: 'start',
        cwd: './',
        instances: 1,
        exec_mode: 'cluster',
        watch: false,
        max_memory_restart: '1G',
        env: {
          NODE_ENV: 'production',
        },
      }],
    };

    Replace your-app-name with a descriptive name for your application.

  4. Start your application with PM2:

    From your project's root directory, run the following command to start your application using PM2:

    pm2 start ecosystem.config.js

    This will start your Next.js application in the background and keep it running.

  5. Install and configure Nginx:

    Nginx will act as a reverse proxy, directing incoming traffic to your Next.js application. Install Nginx using your server's package manager. For example, on Ubuntu:

    sudo apt-get install nginx
  6. Create an Nginx server block:

    Create a new server block configuration file for your application. For example, create a file named your-app-name in the /etc/nginx/sites-available directory. Here's an example 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 server IP address. The proxy_pass directive should point to the port where your Next.js application is running (default is 3000).

  7. Enable the server block:

    Create a symbolic link from the server block configuration file to the sites-enabled directory:

    sudo ln -s /etc/nginx/sites-available/your-app-name /etc/nginx/sites-enabled/
  8. Test and reload Nginx:

    Test your Nginx configuration for any errors:

    sudo nginx -t

    If there are no errors, reload Nginx to apply the changes:

    sudo systemctl reload nginx

Your Next.js application should now be accessible via your domain name or server IP address.

Additional Notes:

  • You can customize the Nginx configuration further to handle SSL certificates, load balancing, and other advanced features.
  • Consider using a monitoring tool to keep track of your application's performance and uptime.
  • Regularly update your server and dependencies to ensure security and stability.

Code Example

This PM2 configuration defines a single application named "your-app-name". It runs "npm start" in the current directory, using a single instance in cluster mode. The application doesn't automatically restart on file changes and restarts if it exceeds 1GB of memory. The NODE_ENV is set to "production".

module.exports = {
  apps: [{
    name: 'your-app-name',
    script: 'npm',
    args: 'start',
    cwd: './',
    instances: 1,
    exec_mode: 'cluster',
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production',
    },
  }],
};

This code defines the PM2 configuration for your Next.js application.

Explanation:

  • name: The name of your application in PM2.
  • script: The command to start your application. In this case, it's npm start.
  • args: Arguments passed to the script.
  • cwd: The working directory for your application.
  • instances: The number of instances of your application to run.
  • exec_mode: The execution mode. cluster mode utilizes multiple CPU cores.
  • watch: Whether to watch for file changes and restart the application automatically.
  • max_memory_restart: The maximum memory threshold before restarting the application.
  • env: Environment variables to set for your application.

Remember to replace "your-app-name" with the actual name of your Next.js application. This configuration file is used by PM2 to manage your application's processes, ensuring it runs smoothly and restarts automatically if needed.

Additional Notes

  • Port Configuration: Ensure the proxy_pass directive in your Nginx configuration points to the correct port where your Next.js application is running. The default port for Next.js applications is 3000, but you can customize it.
  • SSL Certificates: For production deployments, it's crucial to secure your application with SSL certificates. You can obtain SSL certificates from various providers like Let's Encrypt and configure Nginx to use them.
  • Load Balancing: If you anticipate high traffic, consider configuring Nginx for load balancing. This involves distributing incoming traffic across multiple instances of your Next.js application, improving performance and availability.
  • Caching: Leverage Nginx's caching capabilities to enhance performance. You can cache static assets like images and JavaScript files, reducing server load and improving response times for users.
  • Security Headers: Implement security headers in your Nginx configuration to protect your application from common web vulnerabilities like cross-site scripting (XSS) and clickjacking.
  • Monitoring: Utilize monitoring tools to keep track of your application's health, performance, and resource usage. This helps identify potential issues and optimize your server configuration.
  • Regular Updates: Keep your server, Nginx, PM2, and Node.js up to date with the latest security patches and performance improvements.
  • Error Logs: Regularly check Nginx and PM2 logs for any errors or warnings. This can provide insights into potential problems and help you troubleshoot issues effectively.
  • Backups: Implement a robust backup strategy for your server and application data to prevent data loss in case of hardware failures or other unforeseen events.
  • Deployment Scripts: Automate the deployment process using scripts to streamline updates and minimize manual intervention.
  • Staging Environment: Consider setting up a staging environment to test changes before deploying them to production. This helps catch potential issues early on and ensures a smoother deployment process.
  • Environment Variables: Utilize environment variables to manage sensitive information like API keys and database credentials securely. Avoid hardcoding such information directly in your application code.
  • Custom Domains: If you're using a custom domain, ensure your DNS settings are correctly configured to point to your server's IP address.
  • Firewall: Configure your server's firewall to allow incoming traffic on ports 80 (HTTP) and 443 (HTTPS) while restricting access to other unnecessary ports.
  • SSH Access: Secure your server by disabling root login via SSH and using SSH keys for authentication instead of passwords.
  • File Permissions: Set appropriate file permissions for your application files and directories to prevent unauthorized access or modifications.
  • Resource Limits: Configure resource limits for your PM2 processes to prevent excessive resource consumption that could impact server stability.
  • Next.js Configuration: Refer to the official Next.js documentation for advanced configuration options and best practices for production deployments.
  • Community Support: Leverage online forums, communities, and resources for assistance and guidance on deploying and managing Next.js applications.

Summary

This guide explains how to deploy a Next.js application on a Linux server using Nginx and PM2.

Step Description
1. Build Next.js App Run npm run build to create a production-ready build.
2. Install PM2 Install PM2 globally using npm install -g pm2.
3. Create PM2 Config File Create ecosystem.config.js to define how PM2 manages your app.
4. Start App with PM2 Run pm2 start ecosystem.config.js to start your app in the background.
5. Install and Configure Nginx Install Nginx and configure it as a reverse proxy to direct traffic to your app.
6. Create Nginx Server Block Create a server block configuration file in /etc/nginx/sites-available to define how Nginx handles requests for your domain.
7. Enable Server Block Create a symbolic link from your server block file to /etc/nginx/sites-enabled.
8. Test and Reload Nginx Test your Nginx configuration with sudo nginx -t and reload it with sudo systemctl reload nginx.

After these steps, your Next.js application should be accessible through your domain name or server IP address.

Conclusion

This guide demonstrated how to deploy a Next.js application on a Linux server using Nginx and PM2. By following these steps, you can ensure your application is served efficiently and reliably to your users. Remember to consider the additional notes for optimizing performance, security, and maintenance of your deployed application. By leveraging the combined power of Next.js, Nginx, and PM2, you can create a robust and scalable web application ready for production environments.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait