BLOG POSTS
Initial Server Setup with Ubuntu – Step-by-Step

Initial Server Setup with Ubuntu – Step-by-Step

Setting up a fresh Ubuntu server properly is one of those fundamental skills that separates decent system administrators from great ones. Whether you’re spinning up a development environment, preparing a production server, or just learning the ropes, getting the initial configuration right can save you hours of headaches down the road. This guide walks you through the essential steps for hardening and configuring a new Ubuntu server, covering everything from basic security measures to performance optimization tricks that most tutorials skip over.

Understanding Ubuntu Server Architecture

Ubuntu Server differs significantly from its desktop counterpart. It ships without a GUI, focuses on stability over cutting-edge features, and includes server-specific packages out of the box. The LTS (Long Term Support) versions receive security updates for five years, making them ideal for production environments.

When you first boot into a fresh Ubuntu server installation, you’re looking at a minimal system designed for efficiency. The default installation includes essential services like SSH, but leaves most configuration decisions to you. This approach gives you maximum control but also means you need to handle security hardening manually.

Initial System Update and Package Management

Before diving into configuration, always start with a complete system update. Ubuntu’s package management system occasionally ships with outdated packages, and security patches might be waiting.

# Update package lists and upgrade system
sudo apt update && sudo apt upgrade -y

# Install essential packages that most servers need
sudo apt install -y curl wget vim htop tree unzip software-properties-common apt-transport-https ca-certificates gnupg lsb-release

# Clean up unnecessary packages
sudo apt autoremove -y
sudo apt autoclean

The software-properties-common package is particularly important as it provides tools for managing software repositories, which you’ll need when installing third-party applications like Docker or Node.js.

User Management and Sudo Configuration

Running everything as root is a security nightmare waiting to happen. Create a dedicated user account with sudo privileges for daily operations.

# Create new user (replace 'username' with your preferred name)
sudo adduser username

# Add user to sudo group
sudo usermod -aG sudo username

# Verify sudo access
sudo -l -U username

For production servers, consider implementing more granular sudo permissions. Edit the sudoers file using visudo to restrict specific commands:

# Allow user to restart specific services without password
username ALL=(ALL) NOPASSWD: /bin/systemctl restart nginx, /bin/systemctl restart mysql

SSH Hardening and Key-Based Authentication

SSH is your primary gateway to the server, so securing it properly is critical. Password-based authentication is vulnerable to brute force attacks, making key-based authentication essential for any internet-facing server.

# Generate SSH key pair on your local machine (not the server)
ssh-keygen -t ed25519 -C "your-email@example.com"

# Copy public key to server
ssh-copy-id username@your-server-ip

# Alternative manual method if ssh-copy-id isn't available
cat ~/.ssh/id_ed25519.pub | ssh username@your-server-ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

Now configure SSH for maximum security by editing /etc/ssh/sshd_config:

# Disable root login
PermitRootLogin no

# Disable password authentication
PasswordAuthentication no
PubkeyAuthentication yes

# Change default port (optional but recommended)
Port 2222

# Limit login attempts
MaxAuthTries 3
MaxSessions 2

# Disable unused authentication methods
ChallengeResponseAuthentication no
UsePAM yes

# Allow only specific users
AllowUsers username

# Enable key-based authentication only
AuthenticationMethods publickey

Restart SSH to apply changes:

sudo systemctl restart ssh
sudo systemctl status ssh

Firewall Configuration with UFW

Ubuntu’s Uncomplicated Firewall (UFW) provides a user-friendly interface to iptables. Start with a deny-all policy and explicitly allow required services.

# Enable UFW
sudo ufw enable

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

# Allow SSH (adjust port if you changed it)
sudo ufw allow 2222/tcp

# Allow HTTP and HTTPS for web servers
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Check firewall status
sudo ufw status verbose

For database servers, you might need additional ports:

# MySQL/MariaDB
sudo ufw allow from 10.0.0.0/8 to any port 3306

# PostgreSQL
sudo ufw allow from 10.0.0.0/8 to any port 5432

System Monitoring and Performance Tuning

Setting up basic monitoring from day one helps you understand your server’s behavior and catch issues early. Install and configure essential monitoring tools:

# Install monitoring tools
sudo apt install -y htop iotop nethogs ncdu

# Install and configure automatic security updates
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

Configure log rotation to prevent disk space issues:

# Edit logrotate configuration
sudo vim /etc/logrotate.conf

# Example configuration for application logs
sudo tee /etc/logrotate.d/application << EOF
/var/log/application/*.log {
    daily
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 0644 www-data www-data
}
EOF

Time Synchronization and Timezone Configuration

Accurate time is crucial for logs, SSL certificates, and distributed systems. Configure NTP properly:

# Check current time settings
timedatectl status

# Set timezone
sudo timedatectl set-timezone America/New_York

# Enable NTP synchronization
sudo timedatectl set-ntp true

# Verify NTP is working
systemctl status systemd-timesyncd

Storage and Filesystem Optimization

Depending on your use case, you might need to optimize storage performance. Here's how to check and configure storage settings:

# Check disk usage and filesystem types
df -h
lsblk -f

# Check for SSD and enable TRIM if available
sudo fstrim -v /

# Add TRIM to cron for regular maintenance
echo '#!/bin/bash
fstrim -v /' | sudo tee /etc/cron.weekly/fstrim
sudo chmod +x /etc/cron.weekly/fstrim

Common Pitfalls and Troubleshooting

Even experienced administrators run into issues during server setup. Here are the most common problems and their solutions:

Issue Symptoms Solution
SSH connection refused Connection timeout or refused Check UFW rules, SSH service status, and port configuration
Sudo password prompts User not in sudo group Add user to sudo group: usermod -aG sudo username
Package installation fails Dependency errors Run apt update first, then apt --fix-broken install
High memory usage System slowdown Check with htop, disable unnecessary services

Performance Benchmarking and Optimization

After initial setup, benchmark your server to establish baseline performance metrics:

# CPU benchmark
sysbench cpu --cpu-max-prime=20000 run

# Memory benchmark  
sysbench memory --memory-total-size=10G run

# Disk I/O benchmark
sysbench fileio --file-total-size=2G prepare
sysbench fileio --file-total-size=2G --file-test-mode=rndrw run
sysbench fileio --file-total-size=2G cleanup

Optimize kernel parameters for better performance by editing /etc/sysctl.conf:

# Increase file descriptor limits
fs.file-max = 65536

# Network performance tuning
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_congestion_control = bbr

# Apply changes
sudo sysctl -p

Server Comparison and Use Cases

Different server configurations suit different use cases. Here's how to choose the right setup:

Use Case Recommended Specs Key Considerations
Web Development 2GB RAM, 1 CPU, 20GB SSD Focus on fast package installation, development tools
Production Web Server 4GB+ RAM, 2+ CPU, SSD storage Security hardening, monitoring, backup automation
Database Server 8GB+ RAM, fast storage Memory optimization, storage performance
Container Host 4GB+ RAM, multiple CPUs Kernel optimization, container runtime configuration

For small to medium projects, consider starting with a VPS solution that allows easy scaling. Larger applications or high-traffic sites might benefit from dedicated server resources for better performance isolation.

Security Best Practices and Hardening

Beyond basic SSH configuration, implement additional security layers:

# Install and configure fail2ban
sudo apt install -y fail2ban

# Create custom fail2ban configuration
sudo tee /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3

[sshd]
enabled = true
port = 2222
logpath = /var/log/auth.log
maxretry = 3
EOF

# Start and enable fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban

# Check banned IPs
sudo fail2ban-client status sshd

Install and configure additional security tools:

# Install security scanning tools
sudo apt install -y lynis chkrootkit rkhunter

# Run security audit
sudo lynis audit system

# Check for rootkits
sudo chkrootkit
sudo rkhunter --check

Automation and Configuration Management

For managing multiple servers, consider automation tools. Here's a basic Ansible playbook for server setup:

---
- hosts: all
  become: yes
  tasks:
    - name: Update package cache
      apt:
        update_cache: yes
        upgrade: dist
        
    - name: Install essential packages
      apt:
        name:
          - curl
          - vim
          - htop
          - ufw
          - fail2ban
        state: present
        
    - name: Configure UFW
      ufw:
        rule: allow
        port: "{{ item }}"
      with_items:
        - ssh
        - 80
        - 443
        
    - name: Enable UFW
      ufw:
        state: enabled
        policy: deny
        direction: incoming

This approach becomes invaluable when managing infrastructure at scale, ensuring consistent configuration across all servers.

The Ubuntu documentation provides comprehensive guides for advanced configurations at https://help.ubuntu.com/lts/serverguide/. For security-specific guidance, the Center for Internet Security offers benchmarks at https://www.cisecurity.org/cis-benchmarks/.

Remember that server setup is an iterative process. Start with these fundamentals, then customize based on your specific requirements. Regular maintenance, monitoring, and security updates are just as important as the initial configuration. Document your setup process and configurations - your future self will thank you when you need to replicate or troubleshoot the environment.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked