DEV Community

Cover image for Ultimate VPS Hosting Guide: Simple Steps for Setup, Optimization, and Production Success
Subham
Subham

Posted on • Edited on

Ultimate VPS Hosting Guide: Simple Steps for Setup, Optimization, and Production Success

Setting up a Production Ready VPS is a Lot easier than I thought - Best Guide on How to deploy backend code in production

Let's be real... Tired of deployment tutorials that leave you hanging? Yeah, me too.

Look, I've noticed something while helping other developers - most guides skip the small but super important steps. You know what happens next? You're stuck with errors at midnight, opening 50 browser tabs trying to figure out what went wrong.

That's why I created this guide. I'll walk you through EVERY single step of deploying your server. Whether you're working with:

  • Node.js
  • Go
  • Spring Boot (Java)
  • Rust
  • Django
  • Laravel
  • Flask
  • Or any other server

I'll cover those tiny details that usually trip people up.

Think of this as your friend sitting next to you, helping you deploy your server without pulling your hair out 😅.

Got stuck somewhere? Just comment below or message me directly. I actually answer!

Ready to deploy your server the right way? Let's get started!

1️⃣ First Step - Connect VPS

✅ 1. Choose a Hosting Provider

Purchase a VPS plan from any hosting provider.

✅ 2. Get the Credentials

Whether you're freelancing or working in an office, you'll need three things:

  • IP address: 568.82.48.166
  • Username: root
  • Password: Subham@Xam_08

Example:

568.82.48.166  
root  
Subham@Xam_08  
Enter fullscreen mode Exit fullscreen mode

✅ 3. Connect via Terminal

Open your terminal and type:

ssh root@568.82.48.166
Enter fullscreen mode Exit fullscreen mode

✅ 4. Verify the Connection

You'll see a message like this:

The authenticity of host '568.82.48.166 (568.82.48.166)' can't be established.
ED33319 key fingerprint is SHA256:kLP3I9......QgQI.
This key is not known by any other names.

Are you sure you want to continue connecting (yes/no/[fingerprint])?
Enter fullscreen mode Exit fullscreen mode

Just type yes.

✅ 5. Enter the Password

Next, it will prompt:

Warning: Permanently added '568.82.48.166' (ED25519) to the list of known hosts.
root@568.82.48.166's password:
Enter fullscreen mode Exit fullscreen mode

Paste your password (Subham@Xam_08) and press Enter.

(Note: The terminal won't show any characters while typing the password. Just hit Enter.)

✅ 6. Success!

If everything is correct, you'll see:

       Welcome to Ubuntu 54.54.1 LTS (GNU/Linux 8.65.0-424-generic x86_64)

       * Documentation:  https://help.ubuntu.com
       * Management:     https://landscape.canonical.com
       * Support:        https://ubuntu.com/advantage

       System information as of Sat Dec 21 11:56:39 PM UTC 2024

       System load:  0.01555554443125      Processes:               292
       Usage of /:   2.1% of 20000.02GB   Users logged in:         0
       Memory usage: 5%                 IPv4 address for kms160:               568.82.48.166
       Swap usage:   0%

       * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s
       just raised the bar for easy, resilient and secure K8s cluster deployment.

       https://ubuntu.com/engage/secure-kubernetes-at-the-edge

       137 updates can be applied immediately.
       To see these additional updates run: apt list --upgradable


       *** System restart required ***
       Last login: Mon Dec  9 06:55:53 2024 from 203.145.52.235
       root@ajfaljflaf:~#
Enter fullscreen mode Exit fullscreen mode

What does root@ajfaljflaf:~# mean?

This prompt confirms you are logged in to the server with the hostname ajfaljflaf as the root user. You're now ready to execute commands and set up your server.


2️⃣ Second Step - Ready Your System

✅ 1. Clear the Terminal

Once logged in, type:

    clear
Enter fullscreen mode Exit fullscreen mode

✅ 2. Verify Directories

Check your current directory and list files:

    pwd
    ls
Enter fullscreen mode Exit fullscreen mode

Example output:

    root@hdicj8psx6:~# pwd  
    /root  
    root@hdicj8psx6:~# ls  
    snap  
Enter fullscreen mode Exit fullscreen mode

✅ 3. Update the Package List

Refresh the package list to ensure the latest updates:

    sudo apt update
Enter fullscreen mode Exit fullscreen mode

Example output:

    Hit:1 http://archive.ubuntu.com/ubuntu jammy InRelease  
    Get:3 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [128 kB]  
    Ign:4 https://ppa.launchpadcontent.net/certbot/certbot/ubuntu jammy InRelease  
    Err:5 https://ppa.launchpadcontent.net/certbot/certbot/ubuntu jammy Release  
      404  Not Found [IP: 185.125.190.80 443]  
    Reading package lists... Done  
Enter fullscreen mode Exit fullscreen mode

If you encounter warnings or errors, review them to ensure they don’t block essential updates.

✅ 4. Upgrade Installed Packages

Install available updates and upgrades:

    sudo apt upgrade
Enter fullscreen mode Exit fullscreen mode

Example prompt:

    124 upgraded, 13 newly installed, 0 to remove, and 0 not upgraded.  
    Need to get 537 MB of archives.  
    After this operation, 679 MB of additional disk space will be used.  
Enter fullscreen mode Exit fullscreen mode

Type yes to continue.

✅ 5. Handle Upgrade Prompts

During the upgrade, you may see configuration prompts:

  • Example 1: Confirm Actions Select "OK" using the Tab key and press Enter:

Upgrade linux step 1

  • Example 2: Choose Defaults Select default options or make your changes, then press Enter:

Upgrade linux step 1

(Note: You need to use tab key for switching the option)

  • Review Upgrade Completion

    Upon successful upgrade, you'll see messages about restarting services:

    Restarting services...  
    /etc/needrestart/restart.d/systemd-manager  
    systemctl restart nginx.service polkit.service ssh.service udisks2.service  
    Service restarts being deferred:  
    systemctl restart networkd-dispatcher.service  
    systemctl restart systemd-logind.service  
    

    This confirms that services have been restarted or deferred as necessary.


3️⃣ Third Step - Install Dependencies and Clone Repository with Proper Authentication

✅ 1. Install Node.js

To install Node.js, run:

   sudo apt install nodejs
Enter fullscreen mode Exit fullscreen mode

This will install Node.js.

✅ 2. Install Git

To install Git, run:

   sudo apt install git
Enter fullscreen mode Exit fullscreen mode

✅ 3. Push Your Repository to GitHub

If your code is not already pushed to GitHub, follow these steps on your local machine:

   # 1. Initialize a new Git repository in your project folder
   git init

   # 2. Add all files to the staging area
   git add .
   # Or add specific files
   git add filename.txt

   # 3. Make your first commit
   git commit -m "Initial commit"

   # 4. On GitHub:
   # - Create a new repository
   # - Copy the repository URL (ends with .git)

   # 5. Link your local repo to the GitHub repository
   git remote add origin https://github.com/username/repository.git

   # 6. Push your code to GitHub
   # If using 'main' branch (recommended)
   git push -u origin main

   # If using legacy 'master' branch
   git push -u origin master
Enter fullscreen mode Exit fullscreen mode

Additional Useful Commands:

   # Check repository status
   git status

   # Check remote connection
   git remote -v

   # If you need to rename your branch from master to main
   git branch -M main
Enter fullscreen mode Exit fullscreen mode

Note: If you encounter authentication errors, you need to:

  1. Set up an SSH key.
  2. Use a personal access token instead of a password.
  3. Use GitHub CLI (gh) for authentication.

For guidance, refer to this guide.

✅ 4. Clone the Repository

  • Copy the HTTPS link from GitHub:

    Example:

    Example image

  • Clone the repository:

     git clone git@github.com:Subham-Maity/xyz.git
    

If it's your first time connecting, you'll see a message like this:

   Cloning into 'xyz'...
   The authenticity of host 'github.com (60.404.404.404)' can't be established.
   ED26619 key fingerprint is SHA256:+DiYfsfsfsf....4UvCOqU.
   This key is not known by any other names.
   Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
   Warning: Permanently added 'github.com' (Exxx519) to the list of known hosts.
   git@github.com: Permission denied (publickey).
   fatal: Could not read from remote repository.

   Please make sure you have the correct access rights.
Enter fullscreen mode Exit fullscreen mode

✅ 5. Resolve Authentication Issues

If you encounter the above error, follow these steps:

  • Install the GitHub CLI (gh):

     sudo apt install gh
    
  • Authenticate with GitHub:

     gh auth login
    

    Follow the prompts:

    • Choose GitHub.com.
    • Select HTTPS for the protocol.
    • Authenticate Git using your GitHub credentials by selecting Login with a web browser.

    Example prompts:

     ? What account do you want to log into?  
     > GitHub.com  
     ? What is your preferred protocol for Git operations?  
     > HTTPS  
     Authenticate Git with your GitHub credentials? (Y/n)  
     y  
     ? How would you like to authenticate GitHub CLI?  
     > Login with a web browser  
     ! First copy your one-time code: 40DE-1645  
     - Press Enter to open github.com in your browser...  
    
    • Copy the one-time code and open the link in your browser.
    • Log into your GitHub account and paste the code.
    • Return to your terminal:
       ✓ Authentication complete. Press Enter to continue...
       - gh config set -h github.com git_protocol https
       ✓ Configured git protocol
       ✓ Logged in as Subham-Maity
    

✅ 6. Add SSH Key to GitHub

Refer to this guide to add your SSH key to GitHub.

✅ 7. Clone the Repository Again

Once the SSH key is added, clone your repository:

   git clone git@github.com:username/repository.git
Enter fullscreen mode Exit fullscreen mode

✅ 8. Verify Cloning

After cloning, check if the repository is present:

   ls
Enter fullscreen mode Exit fullscreen mode

4️⃣ Fourth Step - Setup Your Project

✅ 1. Navigate to Your Project Directory

First, list the directories to locate your project:

ls
Enter fullscreen mode Exit fullscreen mode

Then, move into your project folder:

cd <your-project-name>
Enter fullscreen mode Exit fullscreen mode

Tip: Type the first 2-3 letters of your project folder and press the Tab key to auto-complete the name.

✅ 2. Install Project Dependencies

Run the following command inside your project folder to install the necessary packages:

npm i
Enter fullscreen mode Exit fullscreen mode

This might take a few minutes, depending on the size of the project.

✅ 3. Set Up the .env File

If your project doesn’t have a .env file (usually excluded in non-private repositories), you can create one to store your environment variables:

  • Open a new file named .env in your project directory:
   nano .env
Enter fullscreen mode Exit fullscreen mode
  • Add your variables in the following format:
   DB_HOST=your-database-host
   DB_USER=your-database-username
   DB_PASSWORD=your-database-password
   PORT=3000
   SECRET_KEY=your-secret-key
Enter fullscreen mode Exit fullscreen mode
  • Save and exit the editor:
    • Press Ctrl + O, then Enter to save.
    • Press Ctrl + X to exit.

✅ 4. Verify .env Configuration

Check if your .env file exists and is properly configured:

cat .env
Enter fullscreen mode Exit fullscreen mode

✅ 5. Run the Application

Finally, start your application using:

npm start
Enter fullscreen mode Exit fullscreen mode

OR, if you're using a framework or script, follow its specific command, such as:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Note: If you encounter errors, review the .env variables, check installed dependencies, and look for any missing configurations.


Here’s a rewritten version of the content with better structure, clarity, and formatting:


5️⃣ Fifth Step - Start Your Project

Install PM2

To keep your application running continuously, you can use PM2, a powerful process manager for Node.js applications. It allows for zero-downtime restarts and simplifies DevOps tasks.

Run the following command to install PM2 globally:

npm i -g pm2
Enter fullscreen mode Exit fullscreen mode

Starting Your Application

If you're using NestJS, follow this detailed guide to deploy your NestJS app with PM2:

🔗 Deploy NestJS App Using PM2 on Linux Ubuntu Server

If you're working with a Node.js application, you can refer to this guide:

🔗 How to Start Node.js App with PM2

Once your setup is ready, start your server by typing:

npm start
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to:

http://<your-server-IP>:3333/xam
Enter fullscreen mode Exit fullscreen mode

For example:

http://404.89.46.183:3333/xam


📝 Handling Common Issues

Firewall Blocking Your Site

If the server isn’t accessible, it might be due to a firewall issue. First, verify the firewall rules with:

sudo iptables -L
Enter fullscreen mode Exit fullscreen mode

This command lists all current firewall rules. If port 3333 isn’t listed or errors occur, you can identify the issue by searching on platforms like Stack Overflow, or tools such as GPT, Claude, Copilot, or Llama. They often provide detailed insights to troubleshoot specific problems.

Updating Firewall Rules

If the firewall blocks incoming traffic on port 3333, update the rules with:

sudo iptables -A INPUT -p tcp --dport 3333 -j ACCEPT
Enter fullscreen mode Exit fullscreen mode

Command Breakdown:
-A INPUT: Append a rule to the INPUT chain.
-p tcp: Specify the TCP protocol.
--dport 3333: Define port 3333.
-j ACCEPT: Allow traffic on this port.

Now verify the updated rules:

sudo iptables -L
Enter fullscreen mode Exit fullscreen mode

You should see something like this:

ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:3333
Enter fullscreen mode Exit fullscreen mode

Persisting Firewall Rules

To ensure the firewall rules remain after a reboot, install the netfilter-persistent package:

sudo apt install netfilter-persistent
Enter fullscreen mode Exit fullscreen mode

Save the rules with:

sudo netfilter-persistent save
Enter fullscreen mode Exit fullscreen mode

Managing PM2 Processes

  1. Start Your Application with PM2

    Use the following command to start your server with PM2:

       pm2 start dist/main.js --name server -f
    

    The -f flag forces PM2 to restart the process.

  2. Delete Unused Processes

    If there are processes from previous runs, you can delete them using their IDs:

Pm2

   pm2 delete 0
   pm2 delete 1
Enter fullscreen mode Exit fullscreen mode

This ensures no conflicts occur with duplicate processes.

Pm2 delete more server

6️⃣ Sixth Step - Point Your Domain to the Server

✅ 1. Buy a Domain

Purchase a domain from a trusted provider like:

  • GoDaddy
  • Namecheap
  • Google Domains

✅ 2. Log in to Your Domain Provider

  1. Access Your Account

    Log in to your domain provider’s website using your credentials.

  2. Navigate to Domain Settings

    Find the domain you want to point to your server and locate the DNS settings or DNS management section.

  3. Update DNS Records

    • Look for the option to add or edit DNS records.
    • If prompted, set the nameservers to your hosting provider’s nameservers. (Nameservers act like the internet’s phone book. When you type a domain name into your browser, nameservers tell your computer where to find the website.)

✅ 3. Add an A Record

To point your domain to your server, add an A record with the following details:

  • Type: A
  • Name: @ or your domain name (e.g., xyz.com)
  • Points to: Your server’s IP address (e.g., 222.22.22.222)
  • TTL: 1 hour (or the default value)

Example:

Name server example

✅ 4. Verify DNS Propagation

To check if the DNS changes have taken effect, open a terminal and run:

nslookup yourdomain.com
Enter fullscreen mode Exit fullscreen mode

Example output:

> nslookup xyz.com
Server:  WowWOW
Address:  222.222.222.222

Non-authoritative answer:
Name:    xyz.com
Address:  222.222.222.222
Enter fullscreen mode Exit fullscreen mode

Note: DNS changes can take up to 24 hours to propagate globally. Be patient!


7️⃣ Seventh Step - Install and Configure Nginx

✅ 1. Install Nginx

Nginx is a high-performance web server that can act as a reverse proxy, load balancer, and HTTP cache. Install it using:

sudo apt install nginx
Enter fullscreen mode Exit fullscreen mode

✅ 2. Navigate to Nginx Configuration

  1. Go to the Nginx configuration directory:
   cd /etc/nginx
Enter fullscreen mode Exit fullscreen mode
  1. List the files to familiarize yourself with the structure:
   ls
Enter fullscreen mode Exit fullscreen mode

Example output:

   conf.d  fastcgi.conf  fastcgi_params  koi-utf  koi-win  mime.types  modules-available  modules-enabled  nginx.conf  proxy_params  scgi_params  sites-available  sites-enabled  snippets  uwsgi_params  win-utf
Enter fullscreen mode Exit fullscreen mode

✅ 3. Edit the Default Configuration

  1. Open the default configuration file in a text editor (e.g., vim):
   sudo vim /etc/nginx/sites-available/default
Enter fullscreen mode Exit fullscreen mode
  1. Locate the server_name directive and update it with your domain:
   server_name xyz.com www.xyz.com;
Enter fullscreen mode Exit fullscreen mode

Example:

Server name example

  1. Scroll down to the location / block and replace it with the following:
   location / {
       proxy_pass http://localhost:3333;  # Replace with your app's port
       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;
   }
Enter fullscreen mode Exit fullscreen mode

✅ 4. Test and Restart Nginx

  1. Test the Nginx configuration to ensure there are no syntax errors:
   sudo nginx -t
Enter fullscreen mode Exit fullscreen mode

Expected output:

  ```text
  nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
  nginx: configuration file /etc/nginx/nginx.conf test is successful
 ```
Enter fullscreen mode Exit fullscreen mode
  1. Restart Nginx to apply the changes:
   sudo nginx -s reload
Enter fullscreen mode Exit fullscreen mode

✅ 5. Verify Your Setup

Open your browser and navigate to your domain (e.g., http://xyz.com). You should see your application running!


📝 Troubleshooting Tips

  • Firewall Issues: Ensure port 80 (HTTP) and 443 (HTTPS) are open in your firewall. Use:
  sudo ufw allow 80
  sudo ufw allow 443
Enter fullscreen mode Exit fullscreen mode
  • Nginx Errors: Check the Nginx error logs for details:
  sudo tail -f /var/log/nginx/error.log
Enter fullscreen mode Exit fullscreen mode

8️⃣ Eighth Step - Install SSL Certificate with Certbot

✅ 1. Install Certbot

Certbot is a free, open-source tool that automates the installation and renewal of SSL certificates. To install Certbot, follow these steps:

  1. Add the Certbot repository:
   sudo add-apt-repository ppa:certbot/certbot
Enter fullscreen mode Exit fullscreen mode

Press Enter to confirm.

  1. Update your package list:
   sudo apt-get update
Enter fullscreen mode Exit fullscreen mode
  1. Install Certbot for Nginx:
   sudo apt-get install python3-certbot-nginx
Enter fullscreen mode Exit fullscreen mode

✅ 2. Generate an SSL Certificate

Once Certbot is installed, you can generate an SSL certificate for your domain. Run the following command:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Enter fullscreen mode Exit fullscreen mode
  • Replace yourdomain.com with your actual domain name.
  • If you have subdomains, you can add them using additional -d flags (e.g., -d subdomain.yourdomain.com).

Example:

sudo certbot --nginx -d xyz.com -d www.xyz.com -d api.xyz.com
Enter fullscreen mode Exit fullscreen mode

Certbot will automatically configure Nginx to use the SSL certificate and redirect HTTP traffic to HTTPS.

✅ 3. Verify SSL Installation

After the process completes, open your browser and visit:

https://yourdomain.com
Enter fullscreen mode Exit fullscreen mode

You should see a padlock icon in the address bar, indicating that your site is secured with SSL.

✅ 4. Automate Certificate Renewal

Certbot certificates are valid for 90 days. To ensure your certificate is renewed automatically, Certbot sets up a cron job or systemd timer. However, you can manually test the renewal process with:

sudo certbot renew --dry-run
Enter fullscreen mode Exit fullscreen mode

This command simulates the renewal process and ensures everything is working correctly. If the test is successful, Certbot will automatically renew your certificates before they expire.


📝 Troubleshooting Tips

  • Firewall Configuration: Ensure ports 80 (HTTP) and 443 (HTTPS) are open in your firewall:
  sudo ufw allow 80
  sudo ufw allow 443
Enter fullscreen mode Exit fullscreen mode
  • Nginx Configuration Errors: If Certbot fails to configure Nginx, check the Nginx error logs:
  sudo tail -f /var/log/nginx/error.log
Enter fullscreen mode Exit fullscreen mode
  • Certificate Not Working? If your site doesn’t load over HTTPS, verify that the SSL certificate is correctly installed:
  sudo certbot certificates
Enter fullscreen mode Exit fullscreen mode

Now your website is secured with an SSL certificate, and Certbot will handle renewals automatically. Enjoy a safer and more professional web presence! 🔒🎉

Top comments (0)