Skip to main content

Change SSH Key on Linux

· One min read
Femi Adigun
Senior Software Engineer & Coach

Changing SSH Key

  • Connect to your VPS using SSH with your current SSH key.
  • Edit the ~/.ssh/authorized_keys file using a text editor like nano or vim:

nano ~/.ssh/authorized_keys

  • Delete the existing SSH key and add the new one.
  • Save and exit the editor.

Change SSH Key on Linux

· One min read
Femi Adigun
Senior Software Engineer & Coach

Changing SSH Key

  • Connect to your VPS using SSH with your current SSH key.
  • Edit the ~/.ssh/authorized_keys file using a text editor like nano or vim:

nano ~/.ssh/authorized_keys

  • Delete the existing SSH key and add the new one.
  • Save and exit the editor.

OpenAPI Backend Schema as Frontend Types

· One min read
Femi Adigun
Senior Software Engineer & Coach

OpenAPI JSON as Frontend Types

install the requirement

npm install -D openapi-typescript-codegen

Add the type generator script to your package.json

{
"scripts": {
"generate-api": "openapi --input http://your-backend-url/openapi.json --output src/types/api --client fetch"
}
}

run the generator

npm run generate-api

You can now import and use the types in your application

import { Resume, UserResume } from "@/types/api";

interface Props {
resume: UserResume; // Generated type from your FastAPI schema
}

const ResumeComponent: React.FC<Props> = ({ resume }) => {
// ...
};

Linux For Beginners

· 4 min read
Femi Adigun
Senior Software Engineer & Coach

Introduction to Linux

Linux is an operating system similar to the famous Windows OS we are all used to. A computer is made up of Software, Hardware and Peripheral units as we were taught in introductory class to computer science. Operating System is a type of software (Any non-physical component of the computer is referred to as software). The Operating System manages and controls the computer's resources and facilitates the interaction between humans and the computer. The computer is uselss without an operating system.

Why Linux

Linux is free and open source operating system and powers a wide range of devices, from smartphones, laptops, servers and supercomputers. Linux is highly customizable and secure which has made it to keep growing in popularity among developers, programmers, DEVOPs, MLOPs, Cybersecurity and power users globally.

  • Open-source
  • Secure
  • Stable
  • Flexible
  • Huge Community
  • Highly customizable

Linux File System

The computer file system has a tree structure, navigating from a branch, node or leave to another is called walking the tree. You will need to navigate the tree structure to manage and use files and resources stored on the system. The image below shows the Linux file system. Linux File System

  • /home: User-specific files and configurations.
  • /etc: System-wide configuration files.
  • /var: Variable data like logs.
  • /bin and /sbin: Essential and administrative binaries.

Linux Distributions

A.k.a "distros" are customized versions of Linux OS for different end-user or target market. Popular distros include:

  • Ubuntu: A very popular user friendly distribution.
  • Fedora: Innovative and cutting-edge features
  • Debian: Stable software repository

Linux Commands

We split the basic commands into 2 parts: File Navigation and File Manipulation

File Navigation

  • ls: List files in or contents of a directory
  • cd: Changes the current drectory
  • pwd: Prints the current working directory.

File Manipulation

Linux provides powerful commands for file creation, editting and management:

  • touch: creates empty files.
  • cp: Copy files from source to destination. A copy is retained in source.
  • mv: Moves file from source to destination. No copy is retained in source.

Student Practice Exercises

  1. List the contents of the current directory:
ls
  1. List contents of current working directory including hidden contents.
ls -a
  1. Practise:

    1. Navigate to your home directory and list all its contents.
    2. Use ls -l to display detailed information about each file in the directory
  2. Change directory to a specific location

    I. Create a new directory called school

   mkdir school

II. Go into the new directory

cd school

III. Navigate to /tmp directory and back to your home directory

  1. create nested directories i.e one or more directories inside another directory.
mkdir -p school/classes
  1. create an empty file.
touch artclass.txt

I. create a file named notes.txt in the school/classes directory II. create three files at once: teachers.txt, students.txt, subjects.txt

  1. copy a file
cp notes.txt copy_of_notes.txt
  1. copy a directory recursively
cp -r school/ school_copy/

  1. Rename a file
mv old_name.txt new_name.txt

I. move a file to another directory:

mv notes.txt /home/backup/
  1. Delete a file
rm notes.txt
  1. Delete a directory and its contents recursively
rm -r classes/
  1. Remove an empty directory.
rmdir school/
  1. show command history
history
  1. run a specific command from history
!5
  1. print a text
echo "I love linux."
  1. write text to a file
echo "I mean it, I really love Linux." > love_linux.txt
  1. read content of a file:
cat students.txt
  1. Combine files
cat students.txt classes.txt subjects.txt > combined.txt

More Practice

  1. Navigate to your home directory.
  2. Create a directory called linux_practice.
  3. Inside linux_practice, create two subdirectories: data and scripts.
  4. Create three files inside data: file1.txt, file2.txt, and file3.txt.
  5. Copy all files from data to scripts.
  6. Rename file3.txt in scripts to file3_backup.txt.
  7. Delete the data directory along with its contents.
  8. View your command history to confirm all the steps you performed.

Python Iterables

· 6 min read
Femi Adigun
Senior Software Engineer & Coach

Every collection item in python is iterable An iterable in python can return one item at a time from a collection of items.

An iterable provides iterator for loop and comprehensions i.e list comprehensions, set comprehensions, dictionary comprehensions, and generator expressions. Don't fret if you don't understand these terms, we'll explain them in future lessons.

One of the standout attributes of Horace Learning we use close-to-real-scenarios for our examples.

Lets use a converstaion between a teacher and a student to explain iterables.

Teacher: "Today, we're going to talk about iterables and generators in Python. Can anyone give me an example of an iterable?"

Student: "Um, is a list an iterable?"

Teacher: "Excellent! Yes, a list is an iterable. Can you think of why we might use iterables?"

Student: "I think we use them in for loops, right?"

Teacher: "Correct! Iterables are very useful in for loops. Now, let's talk about generators. They're a special kind of iterable that generates values on-the-fly."

Student: "On-the-fly? What does that mean?"

Teacher: "It means the values are created as you need them, rather than all at once. This can be very memory-efficient for large datasets."

Student: "Oh, I see. Can you show us an example?"

Teacher: "Of course! Let's create a simple generator that yields the squares of numbers."

One easy way to demystify computer science is to think in your native language not the abstract machine language.

  • For our first exercise, we will:
    • Get all the words from the teacher's first sentence.
    • Count the number of words in the sentence.
    • Finally, find repeated words in the sentence.

Get the Teacher's First Sentence

sentence = "Today, we're going to talk about iterables and generators in Python."

Get all the words from the teacher's first sentence.

words = sentence.split()
print("All words:", words)

Count the number of words in the sentence.

word_count = len(words)
print("Word count:", word_count)

Find repeated words in the sentence.

word_frequency = {}
repeated_words = []

for word in words: # Convert to lowercase to ignore case
word = word.lower() # Remove punctuation
word = word.strip('.,')

# Count word frequency
if word in word_frequency:
word_frequency[word] += 1
if word_frequency[word] == 2:
repeated_words.append(word)
else:
word_frequency[word] = 1

print("Repeated words:", repeated_words)

NB: There are more efficient ways to find repeated words such asusing a set to store the words and then use a dictionary to count the frequency of each word, or using wordcloud with matplotlib. However, this lesson teaches iteration with the for keyword

Exercise 1:

  • Print the top 10 most frequent words in the conversation.

Solution

import string

# Combine all the dialogue into one string
conversation = """
Today, we're going to talk about iterables and generators in Python. Can anyone give me an example of an iterable?
Um, is a list an iterable?
Excellent! Yes, a list is an iterable. Can you think of why we might use iterables?
I think we use them in for loops, right?
Correct! Iterables are very useful in for loops. Now, let's talk about generators. They're a special kind of iterable that generates values on-the-fly.
On-the-fly? What does that mean?
It means the values are created as you need them, rather than all at once. This can be very memory-efficient for large datasets.
Oh, I see. Can you show us an example?
Of course! Let's create a simple generator that yields the squares of numbers.
"""

# Clean and split the text
words = conversation.lower().translate(str.maketrans('', '', string.punctuation)).split()

# Count word frequencies
word_freq = {}
for word in words:
if len(word) > 3: # Ignore short words
word_freq[word] = word_freq.get(word, 0) + 1

# Sort words by frequency
sorted_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)

# Display top 10 words
print("Top 10 most frequent words:")
for word, freq in sorted_words[:10]:
print(f"{word}: {'*' * freq}")

How Does Iteration Work?

  • Python checks if the object is iterable by calling __iter__() method. i.e iter(object)
  • If the object is iterable, Python calls __iter__() method to get an iterator.
  • If it is not iterable, Python raises a TypeError exception:

    TypeError: 'int' object is not iterable

  • If __iter__() method is not implementd, but __getitem__() is, Python uses the __getitem__() method to iterate over the object by index starting from 0.
  • The iterator is an object with a __next__() method.
  • The __next__() method returns the next item in the sequence.
  • If the iterator is exhausted, Python raises a StopIteration exception.

Handson 2:

Understanding Iterables and Iterators in Python

1. Python Checks if the Object is Iterable

class SimpleIterable:
def __iter__(self):
return iter([1, 2, 3])

simple = SimpleIterable()
iterator = iter(simple) # This calls __iter__()
print(list(iterator)) # Output: [1, 2, 3]

If the object is not iterable, Python raises a TypeError exception:

try:
iter(42)
except TypeError as e:
print(e) # Output: 'int' object is not iterable

If __iter__() method is not implemented, but __getitem__() is, Python uses the __getitem__() method to iterate over the object by index starting from 0.

class SimpleIterable:
def __getitem__(self, index):
return [1, 2, 3][index]

simple = SimpleIterable()
iterator = iter(simple)
print(next(iterator)) # Output: 1

Iterator with __next__() method

class SimpleIterable:
def __iter__(self):
return iter([1, 2, 3])

simple = SimpleIterable()
iterator = iter(simple)
print(next(iterator)) # Output: 1

In summary, a pythonic object is iterable if it has __iter__() or __getitem__() method.

Clean code guide

  • If you will be iterating over an object, its not necessary to check if the object is iterable. Python will raise a TypeError exception if the object is not iterable. No point re-inventing the wheel. The built in iter() function will mostly be used by python itself than by the developer.
  • Use try except to catch the TypeError exception instead of doing explicit checks. we will discuss exceptions in future lessons

Further Exercises

  • Count all sentences by the teacher.
  • Count all sentences by the student.
  • Count all words by the teacher.
  • Count all words by the student.
  • Count all punctuation marks by the teacher.
  • Count all punctuation marks by the student.
  • Count all vowels by the teacher.
  • Count all vowels by the student.
  • Count all consonants by the teacher.
  • Count all consonants by the student.
  • Count all numbers by the teacher.
  • Count all numbers by the student.
  • Count all special characters by the teacher.
  • Count all special characters by the student.

Python Generators

· 7 min read
Femi Adigun
Senior Software Engineer & Coach

Generators are a type of iterable in Python that can be used to generate a sequence of values. They are defined using a function that contains one or more yield expressions. When a generator function is called, it returns a generator object that can be iterated over lazily, yielding one value at a time.

Here's an example of a generator function that generates a sequence of even numbers:

def even_numbers(n: int) -> int:
"""
Generate a sequence of even numbers up to n.

Args:
n (int): The upper limit of the sequence (exclusive).

Yields:
int: The next even number in the sequence.
"""
for i in range(n):
if i % 2 == 0:
yield i

The yield keyword is used to return a value from the generator function and pause the execution of the function. The generator object can then be used to continue the execution of the function from the point where it was paused.

Traditional LoopGenerator Yield
Computes all values at onceGenerates values on-demand
Stores all values in memoryStores only the current value
Uses more memory for large datasetsMemory-efficient for large datasets
Faster for small datasetsSlightly slower due to overhead
Cannot pause executionCan pause and resume execution
Good for finite, small sequencesExcellent for large or infinite sequences

To get a value from the generator, you can use the next() function.

# Create a generator object that yields even numbers up to 10
even_nums = even_numbers(10)

# Get and print the first even number (0)
print(next(even_nums))

# Get and print the second even number (2)
print(next(even_nums))

# Get and print the third even number (4)
print(next(even_nums))

You can also use a for loop to iterate over the generator object.

def print_even_numbers(limit: int) -> None:
"""
Print even numbers up to the given limit.

Args:
limit (int): The upper limit for generating even numbers (exclusive).

Returns:
None
"""
for num in even_numbers(limit):
print(num)

print_even_numbers(10)

You can also convert a generator object to a list. (But don't do this)

even_nums = even_numbers(10)
print(list(even_nums))

The yield Keyword, what does it mean?

In Python, yield is often described as a combination of "return" and "save."

Yield = Return + Save

When yield is encountered:

  • Return: The current value is returned to the caller.
  • Save: The generator's state is saved, including:
    • Local variables
    • Loop counters
    • Execution context

This saved state allows the generator to resume execution from the same point when next() is called.

Key differences from return:

  • Return exits: A return statement exits the function entirely.
  • Yield pauses: A yield statement pauses the function, saving its state.

Analogy:

Inserting bookmark in a book.

Think of yield as setting a bookmark in a book:

  • You return to the reader (caller) with the current page (value).
  • You save the bookmark (state) so you can resume reading from the same page later.

Note: Please don't convert a generator object to a list if you only need to iterate over it once. This will defeat the purpose of using a generator.

Note: The generator object is not a list, it is an iterator. You can only iterate over it once. If you need to use the values multiple times, you should convert the generator object to a list.

The Generator always remembers its state between calls and you can resume from there with no issues or state errors.

Benefits of Generator

  1. Memory Efficiency: Generators give values on-the-fly, so they don't require as much memory as traditional loops. This makes them ideal for processing large datasets.
  2. Performance: Generators can be faster than traditional loops because they don't require as much memory.
  3. Pause and Resume: Generators can pause and resume execution, which makes them ideal for processing large datasets.

Note: A generator doesn't raise a StopIteration exception, it is a feature of iterators and you don't have to worry about it. It just exits to make it clear that the generator has reached the end of the sequence.

Generator Expression

Generator expressions are similar to list comprehensions, but they return a generator object instead of a list.

Note: Remember, in python, if its iterable, then there is a comprehension. e.g List Comprehension, Set Comprehension, Dictionary Comprehension, and now Generator Comprehension.

# Create a generator expression that yields even numbers from 0 to 9
even_nums = (i for i in range(10) if i % 2 == 0)

# Print the generator object (not the actual values)
print(even_nums)

Here is a comparison of a generator expression and a list comprehension.

# Create a generator expression for even numbers from 0 to 9
even_nums = (i for i in range(10) if i % 2 == 0)

# Create a list comprehension for even numbers from 0 to 9
even_nums_list = [i for i in range(10) if i % 2 == 0]

# Print the generator object (not the actual values)
print(even_nums)

# Print the list of even numbers
print(even_nums_list)

Notice generator expression is wrapped in parentheses (), while list comprehension is wrapped in square brackets [].

Use Cases for Generator Expressions

User generator expressions when you need to generate a sequence of values on-the-fly, but don't need to store all the values in memory. Consider the cost of storing intermediate values in memory when choosing between a generator expression and a list comprehension. Note: When writting any comprehension, if the code spans more than one line, you may be better off with traditional for loop. For the following reasons:

  • Readability
  • Debugging
  • Complexity
  • PEP8
  • Flake8 However, consider the following exceptions to the rule:
  • Line lenght limit rules
  • Complex operations
  • Team code guide/rule
  • Generator expressions are always more efficient for large datasets than a loop that build a list.

Examples

# List comprehension to create a list of squares
squares = [x**2 for x in range(10)]

# Explanation:
# - This creates a list called 'squares'
# - It uses a list comprehension to generate squares of numbers
# - 'x**2' calculates the square of x
# - 'for x in range(10)' iterates over numbers 0 to 9
# - The result is a list of squares: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Multi-line comprehension (might be better as a loop)

# Define a complex calculation using list comprehension
complex_calculation = [
(x**2 + y**2) / (x + y) # Calculate (x^2 + y^2) / (x + y)
for x in range(1, 10) # Outer loop: x from 1 to 9
for y in range(1, 10) # Inner loop: y from 1 to 9
if (x + y) % 2 == 0 # Only include results where x + y is even
]

# Result:
# [1.0, 2.5, 2.0, 3.5, 3.0, 4.5, 4.0, 5.5, 5.0, 2.5, 4.0, 3.5, 5.0, 4.5, 6.0, 5.5, 7.0, 2.0, 3.5, 5.0, 4.5, 6.0, 5.5, 7.0, 6.5]

The above might be clearer as:

# Initialize an empty list to store the results
complex_calculation = []

# Outer loop: iterate over x from 1 to 9
for x in range(1, 10):
# Inner loop: iterate over y from 1 to 9
for y in range(1, 10):
# Check if the sum of x and y is even
if (x + y) % 2 == 0:
# Calculate the result using the formula (x^2 + y^2) / (x + y)
result = (x**2 + y**2) / (x + y)
# Append the calculated result to the complex_calculation list
complex_calculation.append(result)

# At this point, complex_calculation contains all the results

Thank you for reading this article. I hope you found it helpful. Next lesson, we will discuss map, filter vs list comprehension.

Please follow, like and subscribe to my channel and social media pages.

Data Science and AI

· 5 min read
Femi Adigun
Senior Software Engineer & Coach

Join Our 12-Week Journey into the World of Artificial Intelligence

Are you ready to dive into the world of AI and transform your career? Our 12-week AI Bootcamp is designed to take you from beginner to pro, equipping you with the skills and knowledge needed to excel in one of the fastest-growing fields today. Whether you're looking to enhance your current job skills or pivot into a new, exciting career in artificial intelligence, this course has everything you need.

From the fundamentals of machine learning to cutting-edge deep learning techniques, our bootcamp covers it all. You’ll work on real-world projects, gain hands-on experience, and learn from industry experts who are passionate about AI. By the end of the course, you'll be able to build, deploy, and maintain AI models, making you a valuable asset in any tech-driven organization.

Don’t miss this opportunity to be part of the AI revolution. Enroll today and take the first step toward a future where your skills in artificial intelligence open doors to endless possibilities!

AI Bootcamp Course Outline

Week 1: Introduction to AI & Machine Learning

  • Overview of AI and its Applications
    • What is AI?
    • History and evolution of AI
    • Real-world applications of AI
  • Introduction to Machine Learning
    • Types of Machine Learning: Supervised, Unsupervised, and Reinforcement Learning
    • Key concepts: Algorithms, models, training, and evaluation
    • Overview of the AI development lifecycle
  • Setting Up the Environment
    • Installing Python and essential libraries (NumPy, Pandas, Scikit-learn, TensorFlow, PyTorch)
    • Introduction to Jupyter Notebooks

Week 2: Data Science Fundamentals

  • Understanding Data
    • Types of data: Structured, unstructured, and semi-structured
    • Data collection methods and sources
    • Data cleaning and preprocessing techniques
  • Exploratory Data Analysis (EDA)
    • Data visualization tools and techniques
    • Identifying patterns and insights in data
    • Feature engineering and selection

Week 3: Supervised Learning

  • Regression Analysis
    • Linear and logistic regression
    • Model evaluation: R-squared, RMSE, confusion matrix, and ROC curve
  • Classification Algorithms
    • Decision trees, k-Nearest Neighbors (k-NN), and Support Vector Machines (SVM)
    • Hyperparameter tuning and cross-validation
  • Hands-on Project: Building a Predictive Model

Week 4: Unsupervised Learning

  • Clustering Algorithms
    • K-means clustering, Hierarchical clustering, and DBSCAN
  • Dimensionality Reduction
    • Principal Component Analysis (PCA) and t-SNE
    • Application of dimensionality reduction in real-world scenarios
  • Anomaly Detection
    • Techniques for identifying outliers in data
  • Hands-on Project: Customer Segmentation using Clustering

Week 5: Neural Networks & Deep Learning

  • Introduction to Neural Networks
    • Understanding perceptrons and activation functions
    • Building and training a simple neural network
  • Deep Learning Concepts
    • Convolutional Neural Networks (CNNs) for image processing
    • Recurrent Neural Networks (RNNs) for sequence data
    • Transfer learning and pre-trained models
  • Hands-on Project: Image Classification using CNNs

Week 6: Natural Language Processing (NLP)

  • Introduction to NLP
    • Text preprocessing techniques (tokenization, stemming, lemmatization)
    • Word embeddings (Word2Vec, GloVe)
  • NLP Models and Applications
    • Sentiment analysis, Named Entity Recognition (NER), and Machine Translation
    • Building chatbots and text classifiers
  • Hands-on Project: Sentiment Analysis using NLP

Week 7: Reinforcement Learning

  • Reinforcement Learning Fundamentals
    • Markov Decision Processes (MDP)
    • Exploration vs. Exploitation trade-off
  • Key Algorithms
    • Q-Learning, Deep Q-Networks (DQN), and Policy Gradients
  • Hands-on Project: Building an AI Agent for a Game

Week 8: AI Ethics and Responsible AI

  • Ethical Considerations in AI
    • Bias in AI models
    • Fairness, transparency, and accountability in AI systems
  • Privacy and Security
    • Data privacy laws and regulations
    • Ensuring data security in AI applications
  • AI for Social Good
    • Case studies on AI applications in healthcare, environment, and education

Week 9: AI in Production

  • Model Deployment
    • Techniques for deploying machine learning models
    • Introduction to cloud platforms (AWS, Google Cloud, Azure) for AI
    • API integration and serving models
  • Monitoring and Maintenance
    • Model performance tracking and optimization
    • Handling model drift and updating models in production
  • Hands-on Project: Deploying an AI Model to the Cloud

Week 10: Capstone Project

  • Project Planning and Development
    • Selecting a project topic and defining objectives
    • Data collection, preprocessing, and model selection
  • Implementation and Evaluation
    • Building, training, and testing the model
    • Evaluating the model's performance and refining it
  • Presentation and Feedback
    • Presenting the project to peers and instructors
    • Receiving feedback and making improvements
  • AI in Different Industries
    • AI in healthcare, finance, retail, and autonomous vehicles
  • Latest Trends in AI
    • Generative AI, AI for Edge Computing, and explainable AI
  • Career Paths in AI
    • Roles in AI: Data Scientist, Machine Learning Engineer, AI Researcher
    • Building a career in AI: skills, certifications, and job search tips

Week 12: Graduation and Next Steps

  • Final Project Showcase
    • Presenting the capstone projects to a panel of experts
    • Peer review and feedback
  • Certificate of Completion
    • Awarding certificates to participants
  • Networking and Career Support
    • Connecting with industry professionals
    • Resume building and interview preparation

This 12-week AI Bootcamp will equip you with the essential skills and knowledge to excel in the rapidly growing field of artificial intelligence.

Deploy FastAPI to Digitalocean Droplet

· 4 min read
Femi Adigun
Senior Software Engineer & Coach

Digitalocean is one of the leading cloud infrastructure service providers.

Provision a droplet

Visit digitalocean and create and account or login with your existing account. Select Ubuntu (my preferred, you can use any Linux distro) The $4/month plan is okay for a test/simple project Select a datacenter closer to your targeted audience not necessarily closest to you Choose SSH Key as authentication method Add your ssh key to the droplet so you can easily and securely access the droplet from your local computer

Generate SSH Key

To generate an SSH key, you can use the ssh-keygen command in your mac terminal. Here's how:

  1. Open your terminal.
  2. Type the following command and press Enter:
    ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    Replace "your_email@example.com" with your own email address.
  3. You will be prompted to choose a location to save the key. Press Enter to accept the default location (/Users/your_username/.ssh/id_rsa) or specify a different location.
  4. Next, you will be prompted to enter a passphrase. It's optional, but recommended for added security. Press Enter if you don't want to set a passphrase.
  5. The SSH key pair will be generated and saved in the specified location.
  6. You can now use the public key (id_rsa.pub) to add it to your DigitalOcean droplet.

Remember to keep your private key (id_rsa) secure and never share it with anyone.

Create a User Account

To create a user account on Linux, you can use the adduser command. Here's how:

  1. SSH into your droplet using the command:

    ssh username@your_droplet_ip

    Replace username with the desired username and your_droplet_ip with the IP address of your droplet.

  2. Once logged in, run the following command to create a new user:

    sudo adduser new_username

    Replace new_username with the desired username for the new account.

  3. You will be prompted to set a password for the new user. Follow the instructions to set a secure password.

  4. Provide additional information for the user, such as their full name and contact information, or press Enter to leave them blank.

  5. Confirm the information and press Enter.

Grant Privileges to the User

After creating the user account, you may want to grant administrative privileges to the user. Here's how:

  1. Run the following command to add the user to the sudo group:

    usermod -aG sudo new_username

    Replace new_username with the username you created earlier.

    Note: You may need to create a .ssh directory for the new user and copy the ssh you added to the user's .ssh directory.

    ADD SSH To User

    • login as root or current user
    • change user :

    su - new_username

    • Create .ssh directory

    mkdir ~/.ssh

    • Change directory permission

    chmod 700 ~/.ssh

    • Copy the SSH key (.pub file) and paste the content

    nano ~/.ssh/authorized_keys`

    • Exit and now login as the new user.

    read more here on how to add new user to your droplet

  2. The user now has administrative privileges and can execute commands with sudo.

Remember to replace new_username with the actual username you created. It's important to choose a strong password and keep it secure.

To SSH into your droplet, use the following command:

ssh username@your_droplet_ip

Update the droplet

Once connected to your droplet, use the folowing command to update the machine

sudo apt update && apt upgrade -y

NGINX

we wil be using NGINX a popular open-source web server software that serves as a reverse proxy server, load balancer, media streamer and HTTP Cache. use this code to install nginx

sudo apt install nginx -y

use the following command to start and enable nginx

systemctl start nginx
systemctl enable nginx

Docker

We will be using docker to containerize our application. Use this command to install docker

sudo apt-get install docker-ce docker-ce-cli containerd.io

setup docker compose

curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose

Your FastAPI Aplication

create a new directory for your project

mkdir -p /var/www/myapi