Students and teachers save a massive 71% on Creative Cloud All Apps

Black Friday and Cyber Monday 2023 Deals for Motion Designers, grab it now!

Cyber Monday: Save big on the Creative Cloud All Apps plan for individuals through 2 Dec

Search

How to Deploy a NestJS Application with Nginx on Ubuntu VPS

  • Share this:

Deploying a web application effectively requires the right tools, and using Nginx on Ubuntu VPS has become a popular choice among developers. If you're eager to learn how to deploy a NestJS application with Nginx on Ubuntu VPS, you're in the right place. In this guide, we will walk you through each essential step, from preparing your Ubuntu server to configuring Nginx for NestJS, ensuring your application is not only functional but secure and optimized for performance. Get ready to enhance your deployment skills and make your NestJS applications run smoothly in a production environment!

Understanding NestJS and its Benefits

NestJS is a progressive Node.js framework that leverages the power of TypeScript to build scalable server-side applications. With its modular architecture, it is particularly suited for creating robust web applications and microservices. Here are some key benefits of using NestJS:

BenefitDescription
ModularityNestJS encourages a modular organization of code, allowing developers to divide features into manageable, testable units.
TypeScript SupportBenefits from TypeScript’s static typing, which helps catch errors during development and improves code quality and maintainability.
ExtensibleThe framework is easily extensible, allowing the incorporation of various libraries and technologies suitable for your application.
Robust EcosystemWith a comprehensive collection of libraries and tools, NestJS simplifies common tasks such as validation, serialization, and testing.
Great CommunityA vibrant community offers support and resources, which means developers can easily find help or tutorials when needed.

By understanding these benefits, developers can better appreciate why NestJS has become a popular choice for building dynamic web applications. Furthermore, when you decide to deploy a NestJS application with Nginx on Ubuntu VPS, the benefits of NestJS will enhance the overall performance and maintainability of your project.

In next sections, we will discuss how to set up your environment efficiently and seamlessly. If you're eager to dive deeper into this process and explore how to set up Nginx for NestJS, stay tuned for the following steps.

Preparing Your Ubuntu VPS for Deployment

Before diving into the deployment process, it’s vital to prepare your Ubuntu VPS correctly. Proper preparation will ensure a smooth deployment of your NestJS application. Follow these key steps to set the stage for your server environment:

1. Update Your System

Keeping your system up-to-date is essential for security and performance. Run the following commands:

sudo apt update
sudo apt upgrade -y

2. Install Necessary Packages

To install Node.js and npm, which are necessary for running your NestJS application, use the following commands:

sudo apt install curl software-properties-common -y
curl -fsSL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt install nodejs -y

3. Verify Your Installation

Ensure Node.js and npm are correctly installed by checking their versions:

node -v
npm -v

4. Install Git

Git is crucial for version control and deploying your application from source. Install it with:

sudo apt install git -y

5. Create a New User (Optional)

For added security, consider creating a new user for your application. Replace “username” with your desired name:

sudo adduser username

6. Set Firewall Rules

If UFW (Uncomplicated Firewall) is enabled on your VPS, allow essential ports:

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable

Summary Table

StepCommand/Action
Update Systemsudo apt update and upgrade
Install Node.jssudo apt install -y nodejs npm
Verify Installationnode -v and npm -v
Install Gitsudo apt install git -y
Create New User (Opt.)sudo adduser username
Set Firewall Rulessudo ufw allow OpenSSH

Following these steps helps you effectively prepare your Ubuntu VPS for deployment, creating a solid foundation for the subsequent phases, including installing Nginx, configuring it as a reverse proxy, and setting up your NestJS application. Now you're ready to move on to the next step: installing Nginx on your Ubuntu VPS!

Installing Nginx on Your Ubuntu VPS

When it comes to deploying server-side applications, Nginx stands out due to its high performance and stability. To move forward with How to Deploy a NestJS Application with Nginx on Ubuntu VPS, let's dive into the installation process. Follow these simple steps:

Step-by-Step Installation

  1. Update Package Index
    Before installing Nginx, ensure your package index is up-to-date. Run the following command:

    sudo apt update
    
  2. Install Nginx
    With the package index updated, you can install Nginx using:

    sudo apt install nginx
    
  3. Start and Enable Nginx
    After installation, start the Nginx service and enable it to run on boot:

    sudo systemctl start nginx
    sudo systemctl enable nginx
    
  4. Check Nginx Status
    To check if Nginx is running properly, execute:

    sudo systemctl status nginx
    

Verify Installation

To confirm that Nginx is installed and operating, open a web browser and navigate to your server's IP address. You should see the default Nginx welcome page.

Configure Firewall (if applicable)

If you have a firewall enabled, allow HTTP and HTTPS traffic with:

sudo ufw allow 'Nginx Full'

Summary of Commands

StepCommand
Update Package Indexsudo apt update
Install Nginxsudo apt install nginx
Start Nginxsudo systemctl start nginx
Enable on Bootsudo systemctl enable nginx
Check Nginx Statussudo systemctl status nginx
Configure Firewallsudo ufw allow 'Nginx Full'

By following these instructions, you will have completed the installation of Nginx on your Ubuntu VPS. This sets the groundwork for the next crucial step: How to set up Nginx for NestJS. Make sure Nginx is running smoothly to ensure an optimal experience for your users.

Building Your NestJS Application for Production

Building your NestJS application for production is a critical step to ensure that it runs optimally and securely. By compiling your application into a production-grade build, you leverage improved performance and reduced latency. Here’s how to prepare your NestJS app effectively:

Steps to Build Your NestJS Application:

  1. Update Dependencies:

    • Check for any outdated dependencies using:
      npm outdated
      
    • Upgrade those that require updating.
  2. Environment Configuration:

    • Make sure to configure environment variables properly. Create a .env file for your production settings, ensuring sensitive data, like API keys and database credentials, are securely stored.
  3. Build the Application:

    • Use the following command to create a production build:
      npm run build
      
    • This command compiles your TypeScript files into JavaScript, optimizing performance.
  4. Run Migrations:

    • If you are using a database, run any pending migrations to ensure your database schema is up to date:
      npm run migrate
      
  5. Start the Application:

    • Utilize the following command to start your application:
      npm run start:prod
      
    • This ensures the application runs in production mode.

Key Points Summary:

StepCommandPurpose
Update Dependenciesnpm outdatedCheck for outdated packages
Build Applicationnpm run buildCompile TypeScript to JavaScript
Run Migrationsnpm run migrateUpdate database schema
Start Applicationnpm run start:prodRun the application in production mode

By following these steps, you can ensure your NestJS application is efficiently built and optimized for production, paving the way for a smooth deployment of your NestJS application with Nginx on Ubuntu VPS. Proper preparation at this stage will enhance your application’s reliability and performance in live environments.

Configuring Nginx as a Reverse Proxy for NestJS

To successfully deploy a NestJS application using Nginx on an Ubuntu VPS, it's crucial to configure Nginx as a reverse proxy. This setup allows Nginx to forward client requests to the NestJS application, enhancing performance and security. Below are essential steps to achieve this configuration:

Steps for Configuration:

  1. Create an Nginx Configuration File:

    • Navigate to the Nginx sites-available directory:
      cd /etc/nginx/sites-available
      
    • Create a new configuration file:
      sudo nano your-app.conf
      
  2. Edit the Configuration File:

    • Add the following block, replacing your-domain.com with your domain and 3000 with the port your NestJS application is running on:
    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;
        }
    }
    
  3. Enable the Configuration:

    • Link the configuration file to the sites-enabled directory:
      sudo ln -s /etc/nginx/sites-available/your-app.conf /etc/nginx/sites-enabled/
      
  4. Test the Nginx Configuration:

    • Run the following command to check for syntax errors:
      sudo nginx -t
      
  5. Restart Nginx:

    • Apply the changes by restarting Nginx:
      sudo systemctl restart nginx
      

Key Points Summary:

StepDescription
Create Config FileSet up a new Nginx configuration file.
Edit Config FileConfigure server settings for NestJS.
Enable ConfigurationLink it to enable the configuration.
Test Nginx ConfigurationEnsure there are no syntax errors.
Restart NginxApply the new configuration.

By following these steps on how to set up Nginx for NestJS, you will successfully configure Nginx as a reverse proxy for your application. This setup will improve the efficiency and security of your NestJS application hosted on your Nginx on Ubuntu VPS.

Securing Your Application with SSL Certificates

Securing your NestJS application is essential to protect user data and establish trust. One effective way to do this is by installing SSL certificates. This section will guide you through the process of adding SSL certificates to your Nginx on Ubuntu VPS.

Why Use SSL Certificates?

  • Encryption: SSL certificates encrypt data exchanged between the server and the user, ensuring privacy and security.
  • Trust: A secure site with HTTPS builds trust with users, enhancing your application's credibility.
  • SEO Benefits: Google favors secure sites, helping your application rank better in search results.

Steps to Secure Your NestJS Application

  1. Choose an SSL Certificate Provider: Consider options like Let's Encrypt, which offers free SSL certificates.
  2. Install Certbot:
    • Update your package manager:
      sudo apt update
      sudo apt install certbot python3-certbot-nginx
      
  3. Obtain the SSL Certificate:
    • Use Certbot to request a certificate for your domain:
      sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
      
  4. Configure Nginx:
    • Certbot automatically configures Nginx for NestJS by modifying the appropriate server block. Verify the settings by checking your Nginx configuration file:
      sudo nano /etc/nginx/sites-available/yourdomain.com
      

Verification and Renewal

  • Test SSL Configuration:

    • After installation, it’s important to check if SSL is functioning correctly. Visit https://yourdomain.com in your browser.
  • Automatic Renewal:

    • Set up a cron job for automatic renewal of the SSL certificate:
      sudo crontab -e
      
    • Add the following line:
      0 0 * * * /usr/bin/certbot renew --quiet
      

By securing your NestJS application with SSL certificates, you ensure a safer user experience and enhance your application's integrity. Now you're equipped with the knowledge of how to set up Nginx for NestJS applications securely!

Testing and Optimizing Your Deployment

Once you've successfully deployed your NestJS application using Nginx on Ubuntu VPS, the next crucial step is to test and optimize your deployment. This ensures that your application not only runs smoothly but also performs efficiently under various conditions. Here are some strategies and practices for effective testing and optimization:

Testing Your Deployment

  1. Functional Testing: Check all routes and features of your NestJS application. Use tools like Postman or Insomnia to send requests and validate responses.
  2. Load Testing: Simulate multiple users accessing the application simultaneously. Tools such as Apache JMeter or k6 can significantly help in evaluating how your application behaves under stress.
  3. Error Monitoring: Implement logging systems such as Winston or Pino to track errors and application performance. Analyze these logs to fix any issues promptly.

Optimizing Your Deployment

  • Cache Static Assets: Configure caching rules in Nginx for static files like images, CSS, and JavaScript to improve load times. Consider the following table for cache control settings:
Content TypeCache DurationDescription
Images30 daysReduces load time for images
CSS/JS1 weekEnsures users have updated files
HTMLno-storeAlways fetch fresh content
  • Gzip Compression: Enable Gzip compression in the Nginx configuration to minimize file sizes and enhance transfer speeds.

  • Database Optimization: Monitor and optimize your database queries using indexing or caching frameworks like Redis.

Following these steps on how to deploy a NestJS application with careful testing and effective optimizations ensures that your application provides an exceptional user experience. By making these enhancements, you can maintain a high-performance setup that scales efficiently as your user base grows.

Frequently Asked Questions

What are the prerequisites for deploying a NestJS application on Ubuntu with Nginx?

Before deploying a NestJS application on an Ubuntu VPS with Nginx, ensure you have a working Node.js environment, as NestJS is built on top of it. This includes having Node.js installed with npm or yarn for package management. Additionally, you should have Nginx installed and configured on your server to act as a reverse proxy, which is essential for directing traffic to your Node.js application. Familiarity with the Linux command line and basic security measures to secure your VPS are also important.

How do I install Nginx on my Ubuntu VPS?

Installing Nginx on your Ubuntu VPS is straightforward. Use the command 'sudo apt update' to update your package index. Then, install Nginx with 'sudo apt install nginx'. Once the installation is complete, you can start the Nginx service using 'sudo systemctl start nginx'. To enable it to start on boot, run 'sudo systemctl enable nginx'. You can verify the installation by visiting your server’s IP address in a web browser; you should see the default Nginx welcome page if everything is set up correctly.

How can I configure Nginx to serve my NestJS application?

To configure Nginx to serve your NestJS application, you will need to create a new server block configuration file under '/etc/nginx/sites-available'. Use a text editor to create this file, for example, 'sudo nano /etc/nginx/sites-available/myapp'. In this file, set the 'server_name' to your domain name or IP address and define the location block to forward requests to your NestJS application, which typically runs on a specific port (like 3000). After saving the configuration, create a symlink to this file in the 'sites-enabled' directory using 'sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/'. Finally, test the configuration with 'sudo nginx -t' and restart Nginx with 'sudo systemctl restart nginx'.

What should I do if my NestJS application is not responding?

If your NestJS application is not responding, first check if the application is running by connecting to your server via SSH and using the command 'ps aux | grep node'. This checks for any running Node.js processes. If your application is not listed, it may have crashed or failed to start, so check the logs for errors. If the application is running but not responding, it could be a port issue; make sure Nginx is correctly configured to pass requests to the correct port. Additionally, check your firewall settings to ensure that the necessary ports are open.

Aleksandar Maksim

Aleksandar Maksim

Hello, I’m Aleksandar. 

 My passion for technology spans a broad range, particularly focusing on working with servers and network devices. 
I have extensive experience in both system and network management.

 I am committed to continually advancing my skills and proving my expertise in the network field. 
By keeping up with the latest technologies, I am dedicated to building high-performance and secure systems. 
As a young professional, I strive to apply the latest innovations to deliver efficient and secure network solutions.

 If you would like to discuss system and network management further, I would be pleased to collaborate with you.

aleksandar.maksim@rdpcore.com

--
Why does a network engineer always carry a notebook?  
Because they might come up with a new 'bandwidth' idea at any moment!  
And of course, until the issues get 'packet'-ed and solved, that notebook might just fill up!

Leave a comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.