Digital Ocean - Terminal

  • Create a Droplet/ Server/ VPS
    • Create > Droplet
    • Select Ubuntu Image > Basic Plan > Regular CPU > Bangalore Region > SSH Key/Password > Choose a Hostname > Create Droplet
  • Rebuild a Droplet
    • Destroy > Select Ubuntu > Rebuild > Confirm
    • If facing trouble logging in through terminal then
    • cd .\.ssh\
    • rm .\known_hosts
  • Forgot Password
    • Access > Reset Root Password > You will get a Password in Email > Open Windows PowerShell
    • ssh root@ipAddress > yes > Enter Password from Email > Enter new Password
    • cd .ssh
    • rm .\known_hosts => Remove this
    • ssh root@ipAddress > yes
    • ssh-keygen -t rsa -b 4096 -C "email" => Generate ssh key for private repo
    • cat path => Copy the ssh key path generated and paste it here to generate ssh key
    • ssh @userNameipAddress => Log in your VPS by entering your Password
  • Basic Configuration & Applying Firewall
    • Options > Access Console > Launch Droplet Console (Login as)
    • user@hostName:/# => Logged in as this
    • root@hostName:/# => Root as all Permissions, Dangerous to use this
    • adduser userName => Add a User, Type Password
    • usermod -aG sudo userName => Give ROOT power to that User by making it sudo User, Can execute ROOT commands by using sudo before
    • sudo su => Login as ROOT user from any other user
    • su userName => Login as any other user
    • sudo ufw app list => List of available applications, UFW acts as a Firewall like a Solder and a Wall
    • sudo ufw status => Status of your App
    • sudo ufw allow OpenSSH => Allow this application, So that Solder allows you
    • sudo ufw enable => Firewall becomes active, Solder active
    • exit => Disconnect Console
  • Transfer Files Between Client And Remote Server Using SFTP
    • Open FileZilla > Connect > SFTP Port of Digital Ocean is 22 & FTP Port is 21
    • Go to any Directory > Drag & Drop any File anywhere
  • Generate SSH Key to Login without Password
    • Open Git Bash
    • ssh-keygen -t rsa => Press Enter for all
    • /c/Users/manav/.ssh/id_rsa_dileName => Put it separately by giving seperate file name
    • cat ~/.ssh/id_rsa.fileName.pub => Shows your Public Key, Copy it
    • ssh-copy-id root@IPAddress => To add the Key in your VPS, Or paste directly in Digital Ocean SSH Key
    • ssh-add ~/.ssh/id_rsa_filename => Add this new file as SSH => Run this before eval "$(ssh-agent)" if needed
    • ssh root@IPAddress => You will be logged in directly
    • Generate a File
      • Create a .txt file
      • start "" ssh root@IPAddress => Type this in that file
      • Rename .txt to .bat
      • Open it to directly Login to your Droplet => If you get error then it can be solved in "C:\Users\userName.ssh'
  • Using PuTTY
    • Open > Paste the IP Address > Open
    • Login with userName and Password
  • Deploying Node JS Application with pm2, nginx, domain, ssl
    • Login
    • curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - => Get Node JS from Node source
    • sudo apt install nodejs => Install Node JS
    • node --version && npm --version => Check if it is installed
    • cd ~
    • mkdir appname
    • cd appName/ => Clone your code from GitHub or make a test file
    • mkdir node nodsudo vi app.js
    • sudo vi app.js => Create this Folder
          const express = require("express");
          const app = express();
          const port = 3000;
      
          app.get("/", (req, res) => {
              res.send("Hello World!");
          });
      
          app.listen(port, () => {
              console.log(`Example app listening at http://localhost:${port}`);
          });
      
    • npm install express => Install Express
    • node app.js
    • sudo npm i pm2 -g => Install and use pm2 as a process manager
    • pm2 start app.js => Start the application
    • pm2 status
    • pm2 restart index.js
    • pm2 logs
    • pm2 flush
    • pm2 startup ubuntu => Start automatically at start
    • sudo apt install nginx => Install Nginx as a reverse proxy
    • sudo vi /etc/nginx/sites-available/default
          server{
          server_name yourDomain www.yourDomain;
      
              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;
              }
          }
      
    • sudo nginx -t => Check if everything is Ok
    • sudo service nginx restart
    • Your is ready to run on the IP Address
  • Add SSL with LetsEncrypt
    • sudo add-apt-repository ppa:certbot/certbot
    • sudo apt-get update
    • sudo apt-get install python-certbot-nginx
    • sudo apt-get install certbot python3-certbot-nginx => If above command does not work
    • sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
    • certbot renew --dry-run => Automatically renew after 90 days
  • Installing LAMP Stack
    • Install Apache
      • sudo apt update => Update apt commands
      • sudo apt install apache2 -y => It is a Web Server
      • sudo ufw app list => Gives list of Apps that want to pass Firewall
      • sudo ufw app info "appName" => Gives description about that App
      • sudo ufw allow in "appName" => Allow incoming traffic on required PORT for this App
      • Now your IP Address will work
    • Install MySQL
      • sudo apt install mysql-server => Install MySQL
      • sudo mysql => Opens MySQL terminal
      • SELECT user, authentication_string, plugin, host from mysql.user; => Shows how ROOT is logging in
      • ALTER user 'root'@'localhost' identified with mysql_native_password by 'yourPassword'; => Changes the authentication way for ROOT to given Password, Not Recommended
      • FLUSH PRIVILEGES:
      • exit => Close Terminal
      • sudo mysql -p => Now you have to login using Password
    • Install PHP
      • sudo apt install php libapache2-mod-php php-mysql => Install PHP and some other Modules
      • sudo nano /etc/apache2/mods-enabled/dir.conf
      • In text editor, Swap position of index.html and index.php as we want to run PHP before HTML
      • ctrl + X > Y > enter => Save & Exit
      • sudo service apache2 restart => Restart
      • cd /var/www => All Websites are by default in this folder
      • cd /html => Contains index.html file of Apache by default which is being served on your IP Address
      • sudo nano index.php => Create this File and write the given code to serve this instead
            <?php
            phpinfo();
            ?>
        
      • sudo service apache2 restart => Restart
      • Now your IP Address will show PHP page instead of Apache page
    • Install PHP MyAdmin
      • sudo apt install phpmyadmin php-mbstring php-gettext
      • y then press enter > Select apache2 by clicking space then press enter > Select yes then press enter
      • Enter Password
      • sudo phpenmod mbstring => Enables Modules
      • sudo service apache2 restart => Restart
      • sudo mysql -p => Login
      • Now in your IPAddress/phpmyadmin will show phpMyAdmin
      • create user 'userName'@'localhost' identified by 'yourPassword'; => Create a new user to Login in phpMyAdmin instead of ROOT
      • grant all privileges on *.* to 'userName'@'localhost' with grant option; => Give ROOT power to that user
    • Hosting Multiple PHP Websites On 1 Single Ubuntu 18 VPS Using Apache Server
      • cd /var/www
      • sudo mkdir fileName => Create this File
      • ls -lart => List with some information
      • sudo chown -R $USER:$USER fileName1 => Make current user owner of the file instead of ROOT
      • ls -lart => List with some information
      • cd fileName1/
      • sudo nano index.html => Create this file and edit using Nano
      • ctrl + X > Y > enter => Type some lines and Save & Exit
      • cd /etc/apache2/sites-available/ => Available Sites by Default
      • ls => 2 files will be there by default, 000-default.conf & default-ssl.conf
      • sudo cp 000-default.conf fileName2.conf => Copy that in a new file
      • sudo nano fileName2.conf => Open in nano
            ServerAdmin email@address
            ServerName domainName
            ServerAlias www.domainName
            DocumentRoot /var/www/fileName1
        
      • ctrl + X > Y > enter
      • sudo a2ensite fileName2.conf => Enable this Site
      • sudo a2dissite 000-default.conf => Disable old site
      • sudo service apache2 restart => Restart
      • sudo apache2ctl configtest => Checks if configuration is right
      • Syntax OK
      • Go to your Domain provider > DNS Management
      • Type A, Name @, Value IPAdress, TTL 600 seconds => Changes may take some time
      • Now you can go to your Domain and Check! => Follow the same steps to host multiple website on the same VPS
  • Host Flask App On Ubuntu 18 VPS using Virtual Environment
    • Login to your Droplet Console
    • Basic Configuration & Applying Firewall
    • Install Apache
    • sudo apt install libapache2-mod-wsgi-py3 => Mod of Apache that serves Python files using wsgi
    • cd /var/www
    • mkdir flaskapp
    • cd flaskapp/
    • mkdir flaskapp
    • cd flaskapp/ => You are in /var/www/flaskapp/flaskapp
    • sudo apt install python3-pip
    • pip3 install virtualenv => Install Virtual Environment using pip
    • sudo virtualenv venv => Virtual Environment created
    • source venv/bin/activate => (venv) will be written before user@hostName
    • pip3 install flask requests panda flask-sqlalchemy => Install anything you want
    • python => Python interpreter active, You can write python code here
    • exit() => Exit Editor
    • deactivate => Virtual Environment Deactivated (venv) removed
    • cd /etc/apache2/sites-available/
    • sudo cp 000-default.conf fileName.conf => Copy that in a new file
    • sudo nano fileName2.conf => Open in nano
          ServerName domainName
          ServerAdmin email@address
          WSGIScriptAlias / /var/www/flaskapp/flaskapp.wsgi
          <Directory /var/www/flaskapp/flaskapp/>
              Order allow,deny
              Allow from all
          </Directory>
          Alias /static /var/www/flaskapp/flaskapp/static
          <Directory /var/www/flaskapp/flaskapp/static>
              Order allow,deny
              Allow from all
          </Directory>
          DocumentRoot /var/www/flaskapp
          LogLevel warn
      
    • sudo a2ensite flaskapp.conf
    • sudo service apache2 restart => If there is no problem then this will work
    • `cd /var/www/flaskapp/
    • sudo nano flaskapp.wsgi
          #!/usr/bin/python
          activate_this = '/var/www/flaskapp/flaskapp/venv/bin/activate_this.py'
          exec(open(activate_this).read(), dict(__file__=activate_this))
          import sys
          import logging
          logging.basicConfig(stream=sys.stderr)
          sys.path.insert(0, "/var/www/flaskapp/")
          from flaskapp import app as application
          application.secret_key = 'Add-my-secret-1234-key!@$$%^&*(sdfsdf643535##$$'
      
    • cd flaskapp/
    • vim __init__.py
          from flask import Flask
          app = Flask(__name__)
          @app.route('/')
          def hello_world():
              return "Hello, World!"
      
    • python3 __init__.py => Run this file
    • sudo service apache2 restart
    • Go to your Domain provider and point it to this IP Address
    • Open your Domain!
    • cd var/log/apache2/
    • cat error.log => Shows error
  • Apache Directories
    • /var/www/html => It contains the actual Web Content, By default it contains Apache page, Can change it in Configuration file
    • /etc/apache2 => The Apache configuration directory
    • /etc/apache2/apache2.conf => The main Apache Configuration File
    • /etc/apache2/ports.conf => The file specifies the ports that Apache will listen on. By default, Apache listen on port 80 and additionally listens on post 443 when a module providing SSL capabilities is enabled
    • /etc/apache2/sites-available/ => The directory where per-site virtual hosts can be stored, Which directory to serve for different domains, Apache will not use the configuration files found in this directory unless they are linked to the sites-enabled directory
    • /etc/apache2/sites-enabled/ => The directory where per-site virtual hosts are stored, These are created by linking to configuration files found in sites-available directory with the a2ensite, Apache reads the configuration files and links found in this directory when it starts or reloads to compile a complete configuration
    • /var/log/apache2/access.log => By default, every request to your web server is recorded in this log file unless Apache is configured to do otherwise
    • /var/log/apache2/error.log => By default, all error are recorded in this file. The LogLevel directive in the Apache configuration specifies how much detail the error logs will contain
Share: