Advanced Ubuntu Server Hardening & Optimization

A Comprehensive Guide to Server Security and Performance Tuning

Introduction

After completing the fundamental steps in server hardening, we now move to more advanced aspects of server security and optimization. This guide covers essential topics that will help you squeeze every bit of performance out of your Ubuntu server while maintaining robust security.

Important Note: You cannot effectively tune your hosting stack (nginx, MariaDB, PHP) without first optimizing the underlying server distribution for both performance and security.

Topics Overview

Time Zone Configuration

Set server time zone to match your local time for accurate task scheduling

💾

Swap Space Management

Configure virtual memory to prevent server crashes during memory exhaustion

🔒

Shared Memory Hardening

Secure shared memory space against potential exploits

🌐

IPv6 Disable

Disable IPv6 via GRUB configuration when not needed

🔧

TCP/IP Stack Optimization

Harden and optimize default TCP/IP stack configuration

📊

Congestion Control

Implement BBR algorithm to increase throughput and reduce latency

📁

File System Optimization

Disable access time tracking for performance boost

📈

Open Files Limit

Increase maximum open files per process

1. Time Zone Configuration

Why Time Zone Matters

Setting your server's time zone to match your local time is crucial for several reasons:

Check Current Time Zone

sudo timedatectl
Output:
Local time: 17:35
Universal time: 17:35
Time zone: UTC

List Available Time Zones

sudo timedatectl list-timezones

# Filter for specific region
sudo timedatectl list-timezones | grep Paris
Output:
Europe/Paris
# Filter by continent
sudo timedatectl list-timezones | grep Europe
Pro Tip: Use the pipe symbol (|) with grep to filter time zones by major city names closest to your location.

Set Time Zone

sudo timedatectl set-timezone Europe/Paris

# Verify the change
sudo timedatectl

# Alternative verification
date

Time Zone Configuration Flow

Check Current
Time Zone
Find Your
Time Zone
Set Time Zone
Verify
Configuration

2. Swap Space Management

Understanding Swap Space

Swap is disk space used when physical RAM is full. It acts as a safety net but is NOT a substitute for physical RAM.

Critical Warning: Swap is significantly slower than RAM. Frequent swapping leads to sluggish server performance. Consider swap as a last resort to prevent crashes, not as compensation for limited RAM.

Memory Hierarchy

RAM

Fast Access

Primary Memory

Limited Size

SWAP

Slower Access

Virtual Memory

Safety Net

Disk Storage

Slowest Access

Permanent Storage

Large Capacity

Understanding Your Current Setup: zram

When you run sudo swapon -s and see /dev/zram0, you have zram swap instead of a traditional swap file.

What is zram? zram is compressed RAM-based swap that's actually better than traditional swap files because:
  • It's faster (stays in RAM, just compressed)
  • It's more efficient for modern systems
  • Ubuntu often sets this up automatically

Check Existing Swap

sudo swapon -s
Output (if zram swap exists):
Filename                Type    Size    Used    Priority
/dev/zram0              partition  3933528  0      5
Output (if traditional swap file exists):
Filename                Type    Size    Used    Priority
/swapfile              file    2340000  0      -2
# Alternative check with htop
htop
# Look at Swap line: Swp 0K/2.34G

Two Swap Options

Option 1: Keep zram (Recommended for Most Cases)

If your system has zram and is running fine, keep it and just optimize the settings:

# Check current swappiness
cat /proc/sys/vm/swappiness

# Set swappiness to 1 (use swap only as last resort)
sudo sysctl vm.swappiness=1

# Set cache pressure to 50
sudo sysctl vm.vfs_cache_pressure=50

# Make these permanent
sudo nano /etc/sysctl.conf

Add these lines at the end of the file:

vm.swappiness=1
vm.vfs_cache_pressure=50

Then save (Ctrl+O, Enter, Ctrl+X) and apply:

sudo sysctl -p

# Verify
cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure
Why keep zram?
  • ✅ zram is already working (0 bytes used means your RAM is sufficient)
  • ✅ zram is faster than disk-based swap
  • ✅ It's already properly sized
  • ✅ You just need to optimize swappiness settings

Option 2: Replace zram with Traditional Swap File

Only do this if you specifically need a traditional swap file (usually not necessary).

Ubuntu Swap Size Recommendations (for Traditional Swap)

RAM Amount Recommended Swap Size Notes
1 GB 2 GB 2x RAM size
2-8 GB 4 GB Equal to RAM
16-24 GB 8 GB Half of RAM
> 24 GB 8-16 GB Swap becomes less critical

Remove Existing Traditional Swap File (If Applicable)

# 1. Disable swap
sudo swapoff /swapfile

# 2. Backup fstab
cd /etc
sudo cp fstab fstab.back

# 3. Edit fstab and remove swap entry
sudo nano fstab
# Remove line: /swapfile swap swap defaults 0 0

# 4. Delete swap file
cd /
sudo rm /swapfile

# 5. Verify removal
sudo swapon -s
# Should return no output

# 6. Reboot to confirm
sudo reboot

Remove zram (If You Want Traditional Swap Instead)

# 1. Disable zram
sudo swapoff /dev/zram0

# 2. Remove zram package (to prevent it from restarting)
sudo apt remove zram-config

# 3. Then proceed to create traditional swap file

Create New Traditional Swap File

Formula for Block Count:

# Create 2GB swap file
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152

# Set correct permissions (only root can read/write)
sudo chmod 600 /swapfile

# Format as Linux swap
sudo mkswap /swapfile

# Activate swap
sudo swapon /swapfile

# Verify swap status
sudo swapon -s

Make Traditional Swap Permanent

# Edit fstab
cd /etc
sudo nano fstab

# Add this line at the bottom:
/swapfile swap swap defaults 0 0

# Save and reboot
sudo reboot

# After reboot, verify
sudo swapon -s
htop

Swap File Creation Process

Check Existing
Swap
Remove Old
Swap (if exists)
Create New
Swap File
Set
Permissions
Format &
Activate
Make
Permanent

3. Swap Configuration Parameters

Swappiness

Swappiness is a Linux kernel property (range: 0-100) that defines how aggressively the system uses swap space:

MariaDB Consideration: We set swappiness to 1 because MariaDB may slow down or crash with excessive swapping. If MariaDB still crashes after setting swappiness to 1, you need more physical RAM.

VFS Cache Pressure

VFS (Virtual File System) Cache Pressure controls the kernel's tendency to reclaim memory used for caching directory and inode objects. We set this to 50 for optimal performance.

How Swappiness and VFS Cache Pressure Work Together:

Low swappiness keeps more data in RAM → Reduces disk access → More space for VFS cache → Stores frequently used directory/file information → Improved overall performance

Configuration Commands

# Check current swappiness
cat /proc/sys/vm/swappiness

# Set swappiness to 1 (temporary)
sudo sysctl vm.swappiness=1

# Set VFS cache pressure to 50 (temporary)
sudo sysctl vm.vfs_cache_pressure=50

# Make changes permanent - edit sysctl.conf
sudo nano /etc/sysctl.conf

# Add these lines at the end:
vm.swappiness=1
vm.vfs_cache_pressure=50

# Apply changes
sudo sysctl -p

# Verify settings
cat /proc/sys/vm/swappiness
cat /proc/sys/vm/vfs_cache_pressure

Parameter Summary

Parameter Default Value Recommended Value Purpose
vm.swappiness 60 1 Minimize swap usage for database performance
vm.vfs_cache_pressure 100 50 Balance between reclaiming cache and keeping it in memory

4. Practical Examples and Use Cases

Example 1: Upgrading Server RAM

Scenario: You upgrade your server from 1GB to 2GB RAM

Action Required (for traditional swap):

Action Required (for zram):

Example 2: Restoring fstab from Backup

# Check file sizes
ls -l /etc/fstab*

# Restore from backup
sudo cp /etc/fstab.back /etc/fstab

# Verify restoration
ls -l /etc/fstab*
# Both files should now have the same size

Example 3: Monitoring Swap Usage

# Real-time monitoring with htop
htop
# Press F2 for setup, configure display columns

# Check swap usage
free -h
Output:
              total       used       free    shared  buff/cache  available
Mem:       985Mi      234Mi      123Mi    8.0Mi      627Mi      598Mi
Swap:      2.0Gi        0B      2.0Gi
# Detailed swap information
sudo swapon --show

5. Best Practices Summary

6. Troubleshooting Common Issues

Issue: Swap Not Persisting After Reboot

# Check if swap entry exists in fstab
cat /etc/fstab | grep swap

# If missing, add it
sudo nano /etc/fstab
# Add: /swapfile swap swap defaults 0 0

Issue: Permission Denied When Creating Swap

# Ensure you're using sudo
sudo dd if=/dev/zero of=/swapfile bs=1024 count=2097152

# Check if you're in the root directory
pwd
# Should output: /

Issue: Server Slow After Enabling Swap

Possible Causes:

Solutions:

# Monitor with:
vmstat 1  # to see swap activity

Issue: zram Not Working After Removal

# Reinstall zram if you removed it and want it back
sudo apt install zram-config
sudo reboot

# Verify
sudo swapon -s

Conclusion

Advanced server hardening and optimization is essential for maintaining a secure, high-performance Ubuntu server. The topics covered in this guide provide a solid foundation for:

Next Steps: With these optimizations in place, you're ready to tune your hosting stack (nginx, MariaDB, PHP) for maximum performance and security. Remember to always test changes in a development environment before applying to production servers.