Linux Server Setup: Complete Ubuntu Tutorial for Beginners

Are you ready to master Linux server administration using only free, open-source tools? This step-by-step Linux Server Setup for Beginners tutorial empowers you to build, secure, and manage your own Ubuntu server from scratch—without any paid software or complex prerequisites. Designed specifically for beginners, hobbyists, students, and aspiring system administrators, this hands-on guide walks you through every essential skill: from safe remote access (SSH) and firewall hardening with UFW, to deploying local web servers (Apache/Nginx), setting up secure databases, automating system updates, and implementing basic monitoring and backup strategies.

Ubuntu server installation screen in VirtualBox or VMware

Whether you're building a development VM, personal lab, or a practice environment for certifications, this Linux tutorial delivers practical, real-world examples. All instructions are tailored for localhost or internal IP use—no domain name required—making this the perfect foundation for learning Linux in a secure, affordable, and accessible way.

Introduction

Linux server setup requires proper planning, security configuration, and system administration knowledge. This comprehensive Ubuntu server tutorial teaches beginners how to install, secure, and manage a Linux server from scratch using free, open-source tools. You'll learn essential skills including SSH configuration for secure remote access, Apache web server installation, MySQL database management, UFW firewall configuration, and automated backup strategies. Whether you're building a development environment, personal lab, or practice server for certifications, this step-by-step guide provides practical, real-world examples—no domain name or paid services required.

Real-world Applications

This setup is perfect for:

  • Small business websites - Host company websites and blogs.
  • Development environments - Test applications before production.
  • Learning platform - Practice Linux administration skills.
  • Personal projects - Host portfolio sites, APIs, or web apps.
  • Educational purposes - Teaching server management concepts.

Prerequisites

  • VirtualBox or VMware.
  • Basic command-line knowledge.
  • Internet connection for downloads.
  • 2GB RAM minimum, 20GB storage recommended.

Section 1: Install and Update Linux Server

This section covers the foundation of your Linux journey by guiding you through installing and updating a new Ubuntu server. You'll learn how to set up your system in a virtual machine or cloud environment, configure essential settings, and apply the latest security updates—ensuring your server is secure, stable, and ready for practical use.

✅ Beginner Setup Checklist

Step Task Tool / Notes
1 Choose your Linux distribution Ubuntu Server LTS or Debian
2 Download and verify ISO image Check SHA256 checksum
3 Install Linux in a VM or on a spare PC VirtualBox, VMware, or bare metal
4 Create a non-root user with sudo privileges adduser username && usermod -aG sudo username
5 Enable remote access Install and test openssh-server
6 Update the system sudo apt update && sudo apt upgrade
7 Set static IP (optional) Edit /etc/netplan/ config
8 Secure basic firewall Use ufw allow ssh and enable
9 Take a system snapshot or backup So you can revert before next sections

1. Deploy Ubuntu Server 24.04 LTS:

  • Select Ubuntu Server 24.04 LTS (Long Term Support).
  • Choose minimum 1GB RAM, 25GB storage.
  • Enable SSH keys during setup.
  • Ubuntu 24.04.3 LTS can be either GUI or non-GUI, depending on which edition (flavor or installer) you download. Let’s break it down clearly:

1.1 Ubuntu Desktop 24.04.3 LTS

Has GUI (Graphical User Interface)

  • Comes with the GNOME desktop environment.
  • Suitable if you want a full desktop experience like Windows or macOS.
  • ISO name usually looks like: ubuntu-24.04.3-desktop-amd64.iso
  • Good for general learning, GUI-based tools, or software testing.

1.2 Ubuntu Server 24.04.3 LTS

No GUI (Command-Line Interface only)

  • Optimized for performance, security, and server tasks.
  • Ideal for learning server administration, networking, ethical hacking labs, etc.
  • ISO name usually looks like: ubuntu-24.04.3-live-server-amd64.iso
  • You interact with it using the terminal (CLI) — but you can manually install a GUI later if you want.

Optional: Add GUI to Server Later

If you install the Server version and later decide you want a graphical interface, you can add one using:

1️⃣ Install the GUI

sudo apt update
sudo apt install xubuntu-desktop -y

This installs the XFCE desktop environment with a display manager (usually lightdm).

If you install the Server version and later decide you want a graphical interface, you can add one using:

2️⃣ Start the GUI manually

After installation, you can start the GUI with:

sudo systemctl start lightdm

lightdm is the display manager installed with Xubuntu.

Or if you installed Lubuntu:

sudo systemctl start sddm

sddm is the default for LXQt.

3️⃣ Enable GUI to start at boot

If you want your server to boot directly into the GUI instead of the command line:

sudo systemctl set-default graphical.target

To switch back to CLI boot:

sudo systemctl set-default multi-user.target

Recommendation (for learning)

Goal Recommended Version
Learn Linux commands, server setup, networking, ethical hacking Ubuntu Server 24.04.3 LTS
Learn GUI + basic Linux usage Ubuntu Desktop 24.04.3 LTS
Learn both (flexible) Install Server, then add GUI later if needed

Local Installation (VirtualBox/VMware)

1. Download Ubuntu Server 24.04 LTS:

2. Create Virtual Machine:

  • Allocate 2GB RAM, 20GB storage.
  • Mount Ubuntu ISO
  • Follow installation wizard

3. Basic Installation Steps:

  • Select language and keyboard layout.
  • Choose "Install Ubuntu Server".
  • Configure network settings.
  • Create user account with sudo privileges.
  • Install OpenSSH Server when prompted.

Initial System Update

Why important: Ensures latest security patches and packages are installed.

# Update package lists
sudo apt update

# Upgrade installed packages
sudo apt upgrade -y

# Install essential packages
sudo apt install -y curl wget git vim htop tree unzip

Tool Descriptions for Essential Linux Utilities

Here's a breakdown of what each tool does and why they're essential:

🌐 Network & Download Tools

1. curl - Client URL Tool

  • Purpose: Transfer data to/from servers using various protocols (HTTP, HTTPS, FTP, SCP).
  • Common Uses:
    • Download files from the internet.
    • Test API endpoints.
    • Check website availability.
    • Automate web interactions in scripts.
  • Example: curl -O https://example.com/file.zip

2. wget - Web Get Utility

  • Purpose: Non-interactive network downloader.
  • Common Uses:
    • Download entire websites (recursive).
    • Resume interrupted downloads.
    • Download files via FTP.
  • Key Feature: Better than curl for recursive downloads.
  • Example: wget -c https://example.com/large-file.iso (resumes download)

💻 Development & System Tools

1. git - Version Control System

  • Purpose: Track changes in source code during software development.
  • Common Uses:
    • Clone repositories: git clone https://github.com/user/repo
    • Track file changes.
    • Collaborate with other developers.
    • Manage code versions and branches.
  • Essential for: Developers, system administrators, anyone working with code.

2. vim - Text Editor

  • Purpose: Powerful, modal text editor.
  • Common Uses:
    • Editing configuration files.
    • Writing scripts and code.
    • Quick file modifications via SSH.
  • Key Feature: Available on virtually all Linux systems.

📊 System Monitoring & Management

1. htop - Interactive Process Viewer

  • Purpose:Real-time system monitoring (enhanced top).
  • Common Uses:
    • View CPU, memory, and swap usage.
    • Monitor running processes.
    • Kill misbehaving applications.
    • Sort processes by resource usage.
  • Advantage: Colorful, interactive, user-friendly interface

📁 File Management Utilities

1. tree - Display directory structures in a tree format

  • Purpose: Track changes in source code during software development.
  • Common Uses:
    • Visualize complex directory hierarchies.
    • Understand project structures.
    • Quick inventory of folder contents.
  • Example: tree /var/www shows entire website structure

2. unzip - Archive Extraction

  • Purpose: Extract files from ZIP archives.
  • Common Uses:
    • Unpack downloaded software.
    • Extract compressed backups.
    • Handle Windows-compatible archives.
  • Companion: Often used with zip for creating archives.

🛠 Practical Scenarios

    System Administrator:

  • Use curl to check web service health.
  • Use htop to monitor server performance.
  • Use vim to edit configuration files.

    Developer:

  • Use git for version control.
  • Use wget to download dependencies.
  • Use tree to view project structure.

    Power User:

  • Use unzip for file management.
  • Use htop for system diagnostics.
  • Use cur/wget for automated downloads.

Section 2: Set Up SSH for Secure Remote Access

Understanding SSH Security

SSH (Secure Shell) provides encrypted communication. Key-based authentication is more secure than passwords as it prevents brute-force attacks.

Step 1: Generate SSH Key Pair (From Local Machine)

On your local computer (Windows/Mac/Linux):

# Generate RSA key pair (4096 bits for extra security)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# When prompted:
# - Press Enter for default location (~/.ssh/id_rsa)
# - Enter a passphrase for extra security (optional but recommended)

Flag Breakdown:

-t rsa - Type of Key

  • Creates an RSA encryption key.
  • Alternative types: ed25519 (newer, faster) or dsa (older).

-b 4096 - Bit Strength

  • Specifies 4096-bit key length for enhanced security.
  • Default is 2048 bits - 4096 is much stronger.
  • Higher bits = harder to crack but slightly slower.

-C "your_email@example.com" - Comment/Identifier

  • Adds a label to identify the key owner.
  • Appears in the public key file.
  • Helps manage multiple keys

Common Usage:

# Add to GitHub/GitLab
cat ~/.ssh/id_rsa.pub

# Copy to server
ssh-copy-id user@server.com

Step 2: Copy Public Key to Server

Method 1: Using ssh-copy-id (Linux/Mac)

ssh-copy-id username@your-server-ip

Method 2: Manual copy (All platforms)

# Display your public key
cat ~/.ssh/id_rsa.pub

# Copy the output, then on your server:
mkdir -p ~/.ssh
nano ~/.ssh/authorized_keys
# Paste the public key, save and exit

# Set proper permissions
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

Step 3: Secure SSH Configuration

Why important: Default SSH settings are often insecure. These changes prevent common attacks.

# Backup original config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Edit SSH configuration
sudo nano /etc/ssh/sshd_config

# Make these changes:
Port 2222 # Change from default port 22
PermitRootLogin no # Disable root login
PasswordAuthentication no # Require key-based auth
PubkeyAuthentication yes # Enable key authentication
MaxAuthTries 3

Restart SSH service:

sudo systemctl restart ssh
sudo systemctl status ssh # Verify it's running

Test new configuration (open new terminal):

ssh -p 2222 username@your-server-ip

Section 3: Configure Firewall Using UFW

Understanding UFW

UFW (Uncomplicated Firewall) is a user-friendly command-line tool in Linux used to manage the system's firewall. It provides a simple and easy way to allow or block network traffic without needing to write complex iptables rules manually.

What UFW Does

  • Controls incoming and outgoing network connections.
  • Allows or blocks specific ports (e.g., 22, 80, 443).
  • Manages firewall rules in a simplified way.
  • Provides an easier interface to work with the underlying iptables/nftables.

UFW (Uncomplicated Firewall) simplifies iptables management. It follows the principle of "deny by default, allow by exception."

Step 1: Install and Enable UFW

# Install UFW (usually pre-installed)
sudo apt install ufw

# Check current status
sudo ufw status

# Set default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing

Step 2: Configure Essential Rules

Why each rule is important:

# Allow SSH (use your custom port)
sudo ufw allow 2222/tcp
# Critical: Do this BEFORE enabling UFW to avoid lockout

# Allow HTTP (web server)
sudo ufw allow 80/tcp

# Allow HTTPS (secure web)
sudo ufw allow 443/tcp

# Enable UFW
sudo ufw enable

# Check status
sudo ufw status verbose

Step 3: Additional Security Rules

# Allow specific IP for SSH (more secure)
sudo ufw allow from YOUR_HOME_IP to any port 2222

# Rate limiting for SSH (prevent brute force)
sudo ufw limit 2222/tcp

# Allow ping (ICMP)
sudo ufw allow in on eth0 from any to any port 22 proto icmp

Section 4: Create and Manage Users with Limited Privileges

Understanding User Management

User management with limited privileges in Linux means creating and controlling user accounts so they can perform only specific, restricted actions on the system. Users are given minimum required permissions instead of full administrative (root) access.

Step 1: Create Standard User

# Create new user
sudo adduser webdev

# Add to specific groups (without sudo)
sudo usermod -aG www-data webdev  # For web server access

# Create user with home directory
sudo useradd -m -s /bin/bash developer
sudo passwd developer

useradd Flags:

  • -m/--create-home - Create home directory at /home/developer.
  • -s /bin/bash - Set default shell to Bash (user's command interface).
  • Use Case - Automated user creation in scripts.

usermod Flags:

  • -aG - Append to Group (without removing from other groups).
  • www-data - Web server group for accessing web files.

Step 2: Create Administrative User

# Create admin user
sudo adduser sysadmin

# Add to sudo group (Ubuntu)
sudo usermod -aG sudo sysadmin

# Test sudo access (switch to user first)
su - sysadmin
sudo whoamisudo systemcl   # Should return 'root'

Step 3: Configure User Permissions

# View user groups
groups username
id username

# Remove from group
sudo deluser username groupname

# Set file ownership
sudo chown -R webdev:www-data /var/www/html/

# Set directory permissions
sudo chmod 755 /var/www/html/
sudo chmod 644 /var/www/html/index.html

chown Flags:

  • -R - Recursive - Apply to all files and subdirectories.
  • webdev:www-data - user:group ownership.

chmod Numeric Permission Breakdown:

  7     5      5
  ↓     ↓      ↓
Owner Group Others

What 755 means:

  • Owner (7): rwx - Read, Write, Execute
  • Group (5): r-x - Read, Execute
  • Others (5): r-x - Read, Execute

Section 5: Install and Configure Web Server

Option A: Apache Web Server

Apache Web Server, also called Apache HTTP Server, is an open-source web server software used to host websites, deliver web pages, and handle HTTP requests on the internet.

It is one of the oldest and most widely used web servers in the world.

Why Apache: Stable, well-documented, extensive module support.

# Install Apache
sudo apt update
sudo apt install apache2 -y

# Enable and start service
sudo systemctl enable apache2
sudo systemctl start apache2

# Check status
sudo systemctl status apache2

# Allow through firewall
sudo ufw allow 'Apache Full'

# Test installation
curl localhost
# Or visit http://your-server-ip in browser

Basic Apache Configuration:

# Main config file
# Edit the default virtual host configuration for Apache
# This file controls how Apache serves websites on port 80
sudo nano /etc/apache2/sites-available/000-default.conf

# Enable required modules
# Enable URL rewriting module - allows clean URLs and redirects
# Essential for WordPress, Laravel, and modern web frameworks
sudo a2enmod rewrite

# Enable SSL/TLS module - adds HTTPS support for secure connections
# Required for serving websites over encrypted HTTPS protocol
sudo a2enmod ssl

# Restart Apache
# Apply configuration changes by completely restarting the web server
# This loads the new modules and updated virtual host configuration
sudo systemctl restart apache2

Option B: Nginx Web Server

Nginx (pronounced “engine-x”) is a high-performance, open-source web server and reverse proxy. It is designed to handle a large number of simultaneous connections efficiently, making it ideal for modern, high-traffic websites.

Why Nginx: Lightweight, high performance, low resource usage.

# Install Nginx
sudo apt update
sudo apt install nginx -y

# Enable and start
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx

# Configure firewall
sudo ufw allow 'Nginx Full'

# Test installation
curl localhost

Basic Nginx Configuration:

# Main config
sudo nano /etc/nginx/sites-available/default

# Test configuration
sudo nginx -t

# Restart Nginx
sudo systemctl restart nginx

Create Test Page:

# Create simple HTML page
sudo nano /var/www/html/index.html

# Add content:
<!DOCTYPE html>
<html>
<head>
    <title>My Ubuntu Server</title>
</head>
<body>
    <h1>Welcome to Ubuntu Server!</h1>
    <p>Server setup completed successfully.</p>
</body>
</html>

Section 6: Set Up and Secure MySQL/MariaDB

MariaDB is a fast, open-source, relational database management system (RDBMS) that is used to store, manage, and retrieve data. It is a drop-in replacement for MySQL, meaning it works the same way but offers better performance, security, and updated features.

Why MariaDB: MariaDB is a MySQL fork offering better performance, security features, and active development.

Step 1: Install MariaDB

# Update system
sudo apt update

# Install MariaDB
sudo apt install mariadb-server mariadb-client -y

# Start and enable service
sudo systemctl start mariadb
sudo systemctl enable mariadb
sudo systemctl status mariadb

Step 2: Secure Installation

Critical security step:

# Run security script
sudo mysql_secure_installation

# Follow prompts:
# Set root password? Y
# Remove anonymous users? Y
# Disallow root login remotely? Y
# Remove test database? Y
# Reload privilege tables? Y

Step 3: Create Database and User

# Login to MariaDB
sudo mariadb -u root -p

# Create database
CREATE DATABASE webapp_db;

# Create user with limited privileges
CREATE USER 'webapp_user'@'localhost' IDENTIFIED BY 'secure_password_123';

# Grant specific permissions
GRANT SELECT, INSERT, UPDATE, DELETE ON webapp_db.* TO 'webapp_user'@'localhost';

# Apply changes
FLUSH PRIVILEGES;

# Exit
EXIT;

Step 4: Test Database Connection

# Test new user login
mariadb -u webapp_user -p webapp_db

# Show databases (should only see webapp_db)
SHOW DATABASES;
EXIT;

Section 7: Install PHP or Python

Option A: PHP (for LAMP Stack)

PHP is a server-side scripting language used in the LAMP stack (Linux, Apache, MySQL/MariaDB, PHP) to build dynamic websites and web applications.

# Install PHP and common modules
sudo apt install php libapache2-mod-php php-mysql php-curl php-gd php-mbstring php-xml php-zip -y

# Check PHP version
php --version

# Restart Apache
sudo systemctl restart apache2

# Create PHP info page (remove after testing)
sudo nano /var/www/html/info.php

# Add content:


# Test: visit http://your-server-ip/info.php
# Remove test file for security:
sudo rm /var/www/html/info.php

Option B: Python (for Web Applications)

Python is a powerful, easy-to-learn programming language widely used for building modern, scalable web applications. In web development, Python acts as the backend language — it processes logic, handles requests, connects to databases, and returns responses to the user.

# Install Python and pip
sudo apt install python3 python3-pip python3-venv -y

# Install Flask (lightweight web framework)
pip3 install flask

# Create simple Python app
mkdir ~/webapp
cd ~/webapp

# Create app.py
nano app.py

# Add content:
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return '<h1>Hello from Python!</h1>'

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

# Run application
python3 app.py

# Allow port in firewall
sudo ufw allow 5000/tcp

Section 8: Enable HTTPS Using Self-Signed SSL Certificates

Self-Signed SSL Certificates

A self-signed SSL certificate is an SSL/TLS certificate that is created and signed by the same person/server that will use it, instead of being signed by a trusted Certificate Authority (CA) like Let’s Encrypt or DigiCert.

It enables HTTPS encryption, but browsers do not trust it because it is not verified by a trusted CA.

Step 1: Generate Self-Signed Certificate

# Install OpenSSL (usually pre-installed)
sudo apt install openssl -y

# Generate certificate valid for 1 year
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout /etc/ssl/private/server.key \
  -out /etc/ssl/certs/server.crt

# When prompted, enter:
# Country: US
# State: YourState
# City: YourCity
# Organization: (optional)
# Common Name: localhost or your VM IP
# Email: (optional)

Flag Breakdown:

Part What It Does Example
openssl req The main OpenSSL command to create and process Certificate Signing Requests (CSRs) or certificates The main command
-x509 Creates a self-signed certificate directly instead of a Certificate Signing Request (CSR) Instructs OpenSSL to generate a certificate directly
-nodes "No DES" - instructs OpenSSL to not encrypt the private key with a password Prevents a password prompt when the server starts up
-days 365 Sets the validity period for the certificate to 365 days (1 year) The certificate will expire after one year
-newkey rsa:2048 Generates a new private key simultaneously with the certificate using the RSA algorithm and a 2048-bit key size Creates a strong, new RSA private key
-keyout /etc/ssl/private/server.key Specifies the output file path for the generated private key The private key is saved here; **keep this file secret!**
-out /etc/ssl/certs/server.crt Specifies the output file path for the generated X.509 certificate The public certificate is saved here

Step 2: Configure Apache for HTTPS

# Enable SSL module
sudo a2enmod ssl
sudo systemctl restart apache2

# Edit default SSL config
sudo nano /etc/apache2/sites-available/default-ssl.conf

# Update SSL certificate paths:
SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key

# Enable SSL site
sudo a2ensite default-ssl.conf
sudo systemctl reload apache2

Step 3: Configure Nginx for HTTPS (Alternative)

# Edit Nginx config
sudo nano /etc/nginx/sites-available/default
server {
    listen 443 ssl;
    server_name localhost;

    ssl_certificate /etc/ssl/certs/server.crt;
    ssl_certificate_key /etc/ssl/private/server.key;

    root /var/www/html;
    index index.html index.php;

    location / {
        try_files $uri $uri/ =404;
    }
}
# Test and restart
sudo nginx -t
sudo systemctl restart nginx

Step 4: Allow HTTPS Through Firewall

sudo ufw allow 443/tcp
sudo ufw reload

Step 5: Test HTTPS Access

# From server
curl -k https://localhost

# From browser
# Visit: https://192.168.x.x
# Accept certificate warning (expected for self-signed certs)

Ad

Section 9: Schedule Automatic Updates

Understanding Automatic Updates (unattended-upgrades)

It's a package that automatically installs security updates for your Ubuntu system without you needing to do it manually.

Step 1: Configure Unattended Upgrades

# Install package (usually pre-installed)
sudo apt install unattended-upgrades -y

# Enable the service
sudo systemctl enable unattended-upgrades
sudo systemctl start unattended-upgrades

# Configure automatic updates
sudo dpkg-reconfigure unattended-upgrades
# Select "Yes" when prompted

# Edit configuration
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

Key configuration options:

# Uncomment for security updates
"${distro_id}:${distro_codename}-security";

# Enable automatic reboots (optional)
Unattended-Upgrade::Automatic-Reboot "false";

# Reboot time if enabled
Unattended-Upgrade::Automatic-Reboot-Time "02:00";

Step 2: Enable Auto Updates

# Edit auto-update settings
sudo nano /etc/apt/apt.conf.d/20auto-upgrades

# Ensure these settings:
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
APT::Periodic::AutocleanInterval "7";

File Breakdown

File: /etc/apt/apt.conf.d/20auto-upgrades

  • Location: System configuration directory for APT (package manager).
  • Purpose: Controls automatic update behavior.
  • Syntax: SettingName "value";

Each Setting Explained

1. Update Package Lists

APT::Periodic::Update-Package-Lists "1";
Setting Value What It Does
Update-Package-Lists "1" Download fresh package information every day.
Equivalent Command sudo apt update Gets list of available updates.

Purpose: Checks Ubuntu servers daily to see what updates are available.

Automatic Upgrades

APT::Periodic::Unattended-Upgrade "1";
Setting Value What It Does
Unattended-Upgrade "1" Automatically install security updates.
Equivalent Command sudo apt upgrade Installs the updates.

Purpose: Actually installs the security updates that were found.

3. Auto-Clean

APT::Periodic::AutocleanInterval "7";
Setting Value What It Does
AutocleanInterval "7" Clean up old package files every 7 days.
Equivalent Command sudo apt autoremove Removes unnecessary packages.

Purpose: Keeps your system clean by removing old downloaded package files.

How It Works Together

Daily: Check for updates → If security updates found → Install them
Weekly: Clean up disk space by removing old package files   

Manual Equivalent Commands

If you did this manually instead of automatically:

# Daily: Check for updates
sudo apt update

# Install security updates
sudo apt upgrade

# Weekly: Clean up
sudo apt autoremove
sudo apt autoclean

Complete Configuration Example

sudo nano /etc/apt/apt.conf.d/20auto-upgrades

Add these lines:

# Daily update checks (Every day)
APT::Periodic::Update-Package-Lists "1";

# Auto-install security updates
APT::Periodic::Unattended-Upgrade "1";

# Weekly cleanup (Every 7 day)
APT::Periodic::AutocleanInterval "7";

# Download upgradeable packages (optional)
APT::Periodic::Download-Upgradeable-Packages "1";

Verification Commands

# Check if auto-updates are enabled
sudo cat /etc/apt/apt.conf.d/20auto-upgrades

# View update logs
sudo tail -f /var/log/unattended-upgrades/unattended-upgrades.log

# Check when updates last ran
sudo cat /var/lib/apt/periodic/update-stamp

Step 3: Test and Monitor

# Test dry run
sudo unattended-upgrades --dry-run --debug
Part What It Does
unattended-upgrades The automatic update program.
--dry-run Test mode - don't actually install anything.
--debug Show detailed information - extra logging
# Check logs
sudo tail -f /var/log/unattended-upgrades/unattended-upgrades.log

# Check service status
sudo systemctl status unattended-upgrades

Section 10: System Monitoring Setup

Step 1: Install htop (Process Monitor)

htop is a colorful, interactive task manager for Linux that shows you what's happening inside your computer in real-time.

# Install htop
sudo apt install htop -y

# Run htop
htop

# Key shortcuts in htop:
# F5: Tree view
# F6: Sort options
# F9: Kill process
# F10: Exit

Step 2: Install and Configure Fail2ban

fail2ban is a security guard for your server that automatically blocks hackers who try to guess passwords or attack your services.

How It Works

Hacker tries wrong password → fail2ban detects it → IP gets blocked temporarily

Simple Flow:

  1. Monitors log files for failed login attempts.
  2. Detects patterns (like multiple wrong passwords).
  3. Blocks IP addresses using firewall rules.
  4. Unblocks after a set time period

Why Fail2ban: Protects against brute-force attacks by banning suspicious IPs.

# Install Fail2ban
sudo apt install fail2ban -y

# Copy default configuration
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Edit local configuration
sudo nano /etc/fail2ban/jail.local

Basic Fail2ban configuration:

[DEFAULT]
bantime = 3600        # Ban for 1 hour
findtime = 600        # Look for failures in 10 minutes
maxretry = 3          # Ban after 3 failures

[sshd]
enabled = true
port = 2222           # Your custom SSH port
logpath = /var/log/auth.log
maxretry = 3

Start and enable Fail2ban:

sudo systemctl enable fail2ban
sudo systemctl start fail2ban
sudo systemctl status fail2ban

# Check banned IPs
sudo fail2ban-client status sshd

Step 3: Basic Performance Monitoring

These are system monitoring tools that help you see exactly what's happening with your network connections and disk activity.

Package Breakdown

  1. iotop - Disk I/O Monitor
  2. What it does: Shows which programs are reading/writing to your disk in real-time.

  3. netstat-nat - NAT Connection Viewer
  4. What it does: Shows network address translation connections (important for routers/firewalls).

  5. iftop - Network Bandwidth Monitor
  6. What it does: Shows real-time network traffic - who's talking to whom and how much data is moving.

# Install system monitoring tools
sudo iotop

# Monitor disk I/O
sudo iotop

# Monitor network connections
sudo netstat -tulnp

# Monitor network traffic
sudo iftop

Section 11: Backup and Restore Basics

Understanding Backup Strategy

Follow the 3-2-1 rule: 3 copies of data, 2 different storage types, 1 offsite backup.

Step 1: Simple File Backup with tar

# Create backup directory
sudo mkdir -p /backups

# Create compressed backup
sudo tar -czf /backups/website-backup-$(date +%Y%m%d).tar.gz /var/www/html/
Part What It Does Example
sudo Run the command with administrator/root privileges Needed for reading/writing system files and directories
tar The Tape Archive tool, used for archiving and compressing files and directories The primary backup program
-c Create a new archive "Make a new backup"
-z Compress the archive using `gzip` "Make it smaller"
-f File name follows "Save it as..."
/backups/website-backup-$(date +%Y%m%d).tar.gz Backup filename with date website-backup-20241021.tar.gz
/var/www/html/ What to backup Your website files
# Create database backup
sudo mysqldump -u root -p webapp_db | sudo tee /backups/database-backup-$(date +%Y%m%d).sql > /dev/ls

# List backups
ls -lah /backups/

From ls -lah:

-rw-r--r-- 1 root root 2.5M Oct 21 10:30 database-backup-20241021.sql
│         │ │  │   │    │     │               │
│         │ │  │   │    │     │               └─ Filename
│         │ │  │   │    │     └─ Modification time
│         │ │  │   │    └─ Size (2.5 MB)
│         │ │  │   └─ Group owner (root)
│         │ │  └─ User owner (root)
│         │ └─ Number of links
│         └─ Permissions (read/write for owner, read for others)
└─ File type (- = regular file, d = directory)
                    

MySQLDUMP Command Breakdown:

Part Flag/Component Description
sudo (none) Run as administrator – needed for database access or writing to protected directories.
mysqldump (none) The MySQL backup tool – exports database structure and data to an SQL file.
-u root -u Username – Username - specify database user (root).
-p -p Password prompt - will ask for database password.
webapp_db (none) The database name – specifies which database to backup.
| | Pipe – redirects the standard output of 'mysqldump' as standard input to the next command.
sudo tee tee Write to file - save output to file with sudo privileges.
/backups/database-backup-$(date +%Y%m%d).sql (filename) Backup file with date: database-backup-20241021.sql
2> /dev/null 2> /dev/null Suppress output - hide tee confirmation messages.
# Create backup script
sudo nano /usr/local/bin/backup.sh

# Add content:
#!/bin/bash
DATE=$(date +%Y%m%d)
BACKUP_DIR="/backups"

# Create directories
mkdir -p $BACKUP_DIR/daily

# Backup website files
tar -czf $BACKUP_DIR/daily/website-$DATE.tar.gz /var/www/html/

# Backup database
mysqldump -u root -p'your_password' --all-databases > $BACKUP_DIR/daily/database-$DATE.sql

# Remove old backups (keep 7 days)
find $BACKUP_DIR/daily/ -name "*.tar.gz" -mtime +7 -delete
find $BACKUP_DIR/daily/ -name "*.sql" -mtime +7 -delete

echo "Backup completed: $DATE" >> $BACKUP_DIR/backup.log

# Make executable
sudo chmod +x /usr/local/bin/backup.sh

Step 3: Schedule with Cron

Cron is a built-in Linux utility that automatically runs commands or scripts at scheduled times. It is mainly used for automation, such as backing up files, running scripts, updating systems, or sending reports.

# Edit crontab
sudo crontab -e

# Add backup job (runs daily at 2 AM)
0 2 * * * /usr/local/bin/backup.sh

# Check cron logs
sudo tail -f /var/log/cron.log

Step 4: Restore from Backup

# Restore website files
sudo tar -xzf /backups/daily/website-20241016.tar.gz -C /

# Restore database
mysql -u root -p < /backups/daily/database-20241016.sql

# Set proper permissions after restore
sudo chown -R www-data:www-data /var/www/html/
Part What It Does Example
sudo Run as administrator Needed to write system files
tar Tape Archive tool The restore program
-x Extract files "Restore from backup"
-z Uncompress gzip "Decompress the backup"
-f File to extract "From this backup file..."
/backups/daily/website-20241016.tar.gz Backup file to restore October 16, 2024 backup
-C / Change to root directory "Restore to original location"

Section 12: Install Optional Management Tools

Webmin (Web-based GUI)

Webmin is a web-based control panel that lets you manage your Linux server through a graphical interface in your browser instead of using the command line.

Common Tasks Made Easy

  1. User Management:
  2. Webmin → System → Users and Groups
    → Create user, set password, add to groups
    
  3. Service Control:
  4. Webmin → System → Bootup and Shutdown
    → Start/stop/restart services like Apache, MySQL
    
  5. File Management:
  6. Webmin → Others → File Manager
    → Upload, download, edit, delete files
    
  7. Package Management:
  8. Webmin → System → Software Packages
    → Search, install, remove software
    
  9. Firewall Configuration:
  10. Webmin → Networking → Linux Firewall
    → Add rules, open/close ports
    

Why Webmin: Provides graphical interface for server management tasks.

# Download and run setup script
curl -o webmin-setup.sh https://raw.githubusercontent.com/webmin/webmin/master/setup-repos.sh
Part What It Does
curl Download tool - fetches files from the internet
-o webmin-setup.sh Save as webmin-setup.sh
https://raw.githubusercontent.com/... Official Webmin script from GitHub
sudo bash webmin-setup.sh

# Install Webmin
sudo apt install --install-recommends webmin -y

# Allow through firewall
sudo ufw allow 10000/tcp
sudo ufw reload

# Access Webmin
# Visit: https://your-server-ip:10000
# Login with your sudo user credentials
# Use -k flag to ignore certificate warnings
curl -Ik https://localhost:10000

Access Webmin Now:

  1. Open your web browser and go to:
  2. https://YOUR_SERVER_IP:10000

    Example: https://192.168.1.100:10000

  3. When you see the SSL warning (normal for self-signed certificates):
    • Click "Advanced"
    • Click "Proceed to [IP] (unsafe)"
  4. Login with:
    • Username: root or your username
    • Password: Your user's system password

Port 10000 is the default port where Webmin runs its web interface. It's like a "door number" that Webmin uses to communicate.

Port Analogy

  • Port 22 = SSH door (command line access)
  • Port 80 = HTTP door (regular website)
  • Port 443 = HTTPS door (secure website)
  • Port 10000 = Webmin door (control panel)

Docker (Optional)

Why Docker: Containerization for running isolated applications.

# Add Docker GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker repository
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io -y

# Add user to docker group
sudo usermod -aG docker $USER

# Test installation
sudo docker run hello-world

Free Resources and Documentation

Official Documentation

Learning Resources

Free Tools and Alternatives

  • Text Editors: vim, nano, joe
  • Monitoring: htop, iotop, netdata, zabbix
  • Security: fail2ban, rkhunter, lynis
  • Backup: rsync, borgbackup, duplicati
  • SSL Testing: SSL Labs (ssllabs.com/ssltest)

Troubleshooting Common Issues

SSH Connection Problems

# Check SSH service status
sudo systemctl status ssh

# Check if port is listening
sudo netstat -tlnp | grep :2222

# Check firewall rules
sudo ufw status

# Debug SSH connection
ssh -v -p 2222 username@server-ip

Web Server Not Loading

# Check Apache/Nginx status
sudo systemctl status apache2
sudo systemctl status nginx

# Check error logs
sudo tail -f /var/log/apache2/error.log
sudo tail -f /var/log/nginx/error.log

# Test configuration
sudo apache2ctl configtest
sudo nginx -t

Database Connection Issues

# Check MariaDB status
sudo systemctl status mariadb

# Check logs
sudo tail -f /var/log/mysql/error.log

# Test connection
mysql -u username -p -h localhost

SSL Certificate Problems

# Check certificate status
sudo certbot certificates

# Test renewal
sudo certbot renew --dry-run

# Check web server SSL config
sudo apache2ctl configtest
sudo nginx -t

Next Steps:

  • Deploy your first web application.
  • Set up additional monitoring with Netdata or Grafana.
  • Configure email notifications for system alerts.
  • Implement more advanced backup strategies.
  • Explore containerization with Docker.

Conclusion

Congratulations! You now have a fully configured, secure Ubuntu server with:

✅ Secure SSH access with key-based authentication.

✅ Firewall protection with UFW.

✅ Web server (Apache or Nginx) serving HTTPS content.

✅ Database server (MariaDB) with proper security.

✅ Automatic updates for security patches.

✅ Monitoring and alerting with Fail2ban.

✅ Backup system for data protection.

✅ SSL certificates with automatic renewal

This foundation provides a secure, maintainable server suitable for hosting websites, web applications, or serving as a learning platform. Regular maintenance, monitoring, and keeping up with security updates will ensure your server remains secure and performant.

Happy server administration!

About Website

TechTutorials is a beginner-friendly learning platform offering step-by-step tutorials in programming, ethical hacking, networking, automation, and Windows setup. Learn through hands-on projects, clear explanations, and real-world examples using practical tools and open-source resources—no signups, no tracking, just actionable knowledge to accelerate your technical skills.

Color Space

Discover Perfect Palettes

AD

Featured Wallpapers (For desktop)

Download for FREE!

Wallpaper 1
Wallpaper 23
Wallpaper 46
Wallpaper 81
Wallpaper 111
Wallpaper 116

AD

Featured Wallpapers (For desktop)

Download for FREE!

Wallpaper 1
Wallpaper 23
Wallpaper 46
Wallpaper 81
Wallpaper 111
Wallpaper 116

AD