Skip to content

Instantly share code, notes, and snippets.

@kylemcdonald
Created September 14, 2021 04:26
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kylemcdonald/ec975cc30425ab0e51f93d43d26eb1be to your computer and use it in GitHub Desktop.
Setting up a Digital Ocean droplet for node.js

Get the $IP from Digital Ocean and use the same $USERNAME as your main computer.

ssh root@$IP
adduser $USERNAME
usermod -aG sudo $USERNAME
ufw allow OpenSSH
ufw enable
rsync --archive --chown=$USERNAME:$USERNAME ~/.ssh /home/$USERNAME

Then logout and log back in:

ssh $USERNAME@$IP
sudo apt update && sudo apt upgrade -y

Install and prepare Node:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/install.sh | bash
nvm install 12.18.3

Keep running with pm2, and pm2 on startup:

npm install -g pm2
sudo env PATH=$PATH:/home/kyle/.nvm/versions/node/v12.18.3/bin /home/kyle/.nvm/versions/node/v12.18.3/lib/node_modules/pm2/bin/pm2 startup systemd -u kyle --hp /home/kyle

Remove the init script using pm2 unstartup systemd.

Once you have an app you want to add, run:

pm2 start app.js
pm2 save

Install nginx:

sudo apt install -y nginx
sudo ufw allow 'Nginx Full'

Write this to .nginx replacing $DOMAIN and $PORT:

server {
        listen 80;
        server_name $DOMAIN www.$DOMAIN;

        location / {
                proxy_set_header   X-Forwarded-For $remote_addr;
                proxy_set_header   Host $http_host;
                proxy_pass         "http://localhost:$PORT";
        }
}

Copy the config over:

sudo cp .nginx /etc/nginx/sites-available/$DOMAIN
sudo ln -s /etc/nginx/sites-available/$DOMAIN /etc/nginx/sites-enabled/
sudo systemctl reload nginx

Setup the DNS A record and install and configure Let's Encrypt:

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment