How to Deploy a Website on DigitalOcean Droplet

How to Deploy a Website on DigitalOcean Droplet

In the digital age of today, having a reliable and scalable website is critical for both organizations and individuals. Whether you run an e-commerce platform, a portfolio site, or a corporate web application, selecting the correct hosting option can have a huge impact on your online business. DigitalOcean's Droplet service provides a powerful and flexible solution for deploying your website, allowing you to have complete control over your online presence.

Prerequisites

Prior to commencing, please ensure that you possess the following prerequisites:

  • An active DigitalOcean account

  • A registered domain name (optional)

Step 1: Provision a DigitalOcean Droplet

  • Go to the DigitalOcean website and log in to your account.

  • Choose an existing project or start a new one to host your Droplet.

  • Click the "Create" button, then select "Droplets" from the dropdown menu.

  • For best results, choose a server location that is nearest to your target audience.

  • Select the most recent Ubuntu LTS (Long-Term Support) image, which offers a reliable and well-supported operating system.

  • Determine the best CPU option based on your application's needs. For example, if you're running a Next.js application that needs additional resources during the construction process, you might want to consider the $18 option or higher.

  • Select your chosen authentication mechanism, such as SSH keys or password.

  • Review your options and click "Create Droplet" to begin the provisioning process.

Be cautious that supplying your resources may take some time, so be patient during this stage.

Step 2: Install dependencies

Before continue with the deployment, you must confirm that your server is up to current. To update and upgrade your server, execute the commands listed below:

sudo apt update && sudo apt upgrade

Now, let us install the required dependencies:

1. nginx: Nginx is a popular web server for hosting websites.

sudo apt install nginx

2. certbot: An SSL certificate is essential for securing your website and establishing visitor confidence.

sudo apt install certbot python3-certbot-nginx

3. npm and node: Depending on your application type, you may need npm and node. These are necessary for hosting a Next.js application. If you're working with a basic HTML website, you may skip this step.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
exec $SHELL 
nvm list-remote # View available versions
nvm install v19.4.0 # Install the desired version

4. pm2: To efficiently manage Node.js apps, we'll utilize pm2 as a process manager.

npm install -g pm2

Step 3: Configuring Nginx

Before hosting your website, you must configure Nginx to ensure that it works properly. Let's start with the firewall configuration.

Ubuntu uses ufw (uncomplicated firewall) as the default firewall configuration tool. To see the application settings compatible with ufw, execute the following command:

sudo ufw app list

This command displays a list of available application profiles.

Output
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

As shown in the report, there are three Nginx profiles available:

  • Nginx Full: This profile allows both conventional, unencrypted web traffic (port 80) and TLS/SSL encrypted traffic (port 443).

  • Nginx HTTP: This profile allows only port 80 (unencrypted web traffic).

  • Nginx HTTPS: This profile allows only port 443 (TLS/SSL encrypted communication).

    If OpenSSH is not already enabled, use the following command:

      ufw allow OpenSSH
    

Enabling the most restrictive profile that allows the preset traffic is advised. We'll limit traffic to port 80 for the time being:

sudo ufw allow "Nginx HTTP"

The firewall status can be checked to confirm the change:

sudo ufw status

Which HTTP traffic is permitted will be verified by the output:

Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere                  
Nginx HTTP                 ALLOW       Anywhere                  
OpenSSH (v6)               ALLOW       Anywhere (v6)             
Nginx HTTP (v6)            ALLOW       Anywhere (v6)

After Ubuntu finishes installing, Nginx is started, and the web server should be up and running. Use the systemd init system to make sure the service is operating:

systemctl status nginx

Step 4: Setup for Hosting

Server blocks, which are akin to virtual hosts in Apache, are useful for encapsulating configuration information and running numerous domains on a single Nginx web server. In this instance, we'll set up a domain called "ssw.com," but make sure to substitute your actual domain name for it.

On Ubuntu, Nginx has one server block activated by default, and it is configured to serve files from the /var/www/html directory. Although appropriate for a single site, administering several sites in this directory might get difficult. Therefore, let's create a directory structure inside /var/www for our "ssw.com" site rather than altering /var/www/html directly. If a client request doesn't match any other sites, /var/www/html will still be served by default.

cd /var/www

If your code resides on GitHub, clone it here or create a folder and copy your code into it. Next, assign ownership of the directory using the $USER environment variable:

sudo chown -R $USER:$USER /var/www/ssw #I am using SSW

Ensure correct permissions for your web roots by executing the following command, which sets default file permissions:

sudo chmod -R 755 /var/www/ssw

Now, navigate into that directory:

cd ssw

If you cloned a Node.js app, remember to run:

npm install

Then build it:

npm run build

To enable Nginx to serve this content, we need to create a server block with the appropriate directives. Instead of directly modifying the default configuration file, let's create a new one at /etc/nginx/sites-available/ssw:

cd /etc/nginx/sites-available

Create a file with the same name as that in /var/www:

touch ssw

Now, utilize your preferred text editor (such as Vim, Nano, or any other) to edit this file:

nano ssw #I am using nano

Please note that the following configuration is specific to a Next.js application (I will leave some references for other):

#nginx config file for Nextjs App
#place in /etc/nginx/sites-available/name_of_config_file
server {
        listen 80;
        server_name ssw.com www.ssw.com; #read further to understand

        gzip on;
        gzip_proxied any;
        gzip_types application/javascript application/x-javascript text/css text/javascript;
        gzip_comp_level 5;
        gzip_buffers 16 8k;
        gzip_min_length 256;

        location /_next/static/ {
                alias /var/www/ssw/.next/static/;
                expires 365d;
                access_log off;
        }

        location / {
                proxy_pass http://127.0.0.1:3000; #change to 3001 for second app, but make sure second nextjs app starts on new port in packages.json "start": "next start -p 3001",
                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 "ssw.com" with your actual domain name, e.g., rontennyson.com. If you want both "www" and non-"www" versions of your domain to redirect to your site, include:

server_name ssw.com www.ssw.com;

If you don't have a domain yet, use:

server_name _;

Note: Without a domain, you won't be able to obtain an SSL certificate.

Next, enable the file by creating a symbolic link from it to the sites-enabled directory, which Nginx reads during startup:

sudo ln -s /etc/nginx/sites-available/ssw/etc/nginx/sites-enabled/

Now, two server blocks are enabled and configured to respond to requests based on their directives. Test for any syntax errors in your Nginx files:

sudo nginx -t

If no issues are found, restart Nginx to implement your changes:

sudo systemctl restart nginx

Nginx should now serve your domain name. Test this by navigating to http://ssw.com. Congratulations, the major setup work is complete!

If see you site is not secure don't worry let's setup an SSL certificate (only possible if you have a domain)

Step 5: Obtaining an SSL Certificate

Let's Encrypt is a reliable Certificate Authority (CA) that provides an easy way to install TLS/SSL certificates and enable encrypted HTTPS communication on web servers. Let's Encrypt streamlines the procedure by offering Certbot, a software application that is intended to automate most, if not all, of the required procedures. At the moment, the Apache and Nginx servers have fully automated certificate installation and acquisition processes.

It is necessary to allow the Nginx Full profile while deleting any unnecessary permissions from the Nginx HTTP profile in order to enable HTTPS traffic:

sudo ufw allow 'Nginx Full'
sudo ufw delete allow 'Nginx HTTP'

After executing these commands, your firewall status should display:

sudo ufw status
Output
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
Nginx Full                 ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
Nginx Full (v6)            ALLOW       Anywhere (v6)

Then, start Certbot and let it retrieve your SSL certificates.

Certbot provides multiple ways to get SSL certificates via plugins. By managing Nginx reconfigurations and reloading the configuration as needed, the Nginx plugin simplifies the procedure. In order to use this plugin, run the command below:

sudo certbot --nginx -d ssw.com -d www.ssw.com

Using the -d argument to indicate the domain names for which the certificate should be valid, this command uses the --nginx plugin to call certbot.

If this is your first time using certbot, you will be asked to agree to the terms of service and provide your email address.
Nginx will receive the changed configuration settings after a successful verification, and certbot will verify the process's completion and the location where your certificates are stored.

Output
IMPORTANT NOTES:
 - Congratulations! Your certificate and chain have been saved at:
   /etc/letsencrypt/live/ssw.com/fullchain.pem
   Your key file has been saved at:
   /etc/letsencrypt/live/ssw.com/privkey.pem
   Your cert will expire on 2024-09-23. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot again
   with the "certonly" option. To non-interactively renew *all* of
   your certificates, run "certbot renew"
 - If you like Certbot, please consider supporting our work by:

   Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
   Donating to EFF:                    https://eff.org/donate-le

Make sure the modifications take effect by restarting Nginx with:

sudo systemctl restart nginx

Now when you reload your page, you should see that it is now fully decorated and HTTPS safe.

In conclusion, hosting your website on your own server, such a DigitalOcean Droplet, offers clear advantages in terms of control, scalability, cost-effectiveness, security, and customization, even while platforms like Vercel offer convenience and ease of use. Choosing self-hosting gives you total control over your hosting environment, enabling you to modify it as needed, scale resources effectively, reduce expenses, improve security, and easily incorporate custom solutions. Self-hosting gives you complete control and ownership over your website, while enabling you to build and manage a strong online presence thanks to the adaptability and dependability of services like DigitalOcean. Whether you run a large corporation, a small blog, or a developing startup, hosting on your own server provides unmatched customization and optimization options to make sure your website satisfies your unique needs and functions as well it can in the online world.

References: