Ubuntu VPS initial setup guide - terminal commands on a dark screen

So you just provisioned a fresh Ubuntu VPS — congratulations. The hosting provider handed you a root password, an IP address, and a blank slate. What you do in the next 30–60 minutes will determine how secure, stable, and maintainable your server is for years to come. Skipping these steps is a gamble that attackers count on: automated bots scan the entire IPv4 space in under an hour and will attempt to log in to your server within minutes of it going online.

This guide walks through the 10 most critical configuration tasks every Ubuntu VPS owner should complete before deploying any application. Whether you are launching a website, a mail server, or a private development environment, these foundations apply universally. Commands are tested on Ubuntu 22.04 LTS and Ubuntu 24.04 LTS.

Step 1 Update System Packages First

Before touching anything else, bring your system up to date. The default Ubuntu image your provider ships may be weeks or months old, and critical security patches may already be available. Running this first means every subsequent tool you install builds on a patched foundation.

# Refresh package lists and upgrade all installed packages
apt update && apt upgrade -y

# Remove packages that are no longer needed
apt autoremove -y && apt autoclean

This can take a few minutes on a fresh server. If you are prompted about a modified configuration file during the upgrade (for example /etc/ssh/sshd_config), choose keep the installed version if you plan to configure SSH manually in later steps.

Note: If the upgrade process asks you to restart services, go ahead and allow it. You may also want to reboot after a large kernel update with reboot and reconnect before continuing.

Step 2 Create a Non-Root Sudo User

Operating your server as root at all times is a serious security risk. Any command-line mistake — a misplaced rm -rf, a misconfigured script — executes with total system authority. Creating a dedicated administrative user with sudo privileges gives you a safety net and is considered a baseline best practice.

# Replace "deploy" with your chosen username
adduser deploy

# Grant sudo privileges
usermod -aG sudo deploy

# Switch to your new user to verify
su - deploy
sudo whoami   # Should print: root

Choose a username that does not reveal your purpose (avoid admin, webmaster, or ubuntu — bots try these by default). A name like deploy, ops, or your own name works well.

Why avoiding root matters

  • Accidental destructive commands have no safety net as root.
  • Logs and audit trails are cleaner when actions are tied to named users.
  • Disabling root SSH login (Step 4) removes the most targeted attack vector.
  • Some applications refuse to run as root for safety reasons.

Step 3 Set Up SSH Key Authentication

Passwords can be brute-forced. SSH keys cannot. A key pair consists of a private key (kept only on your local machine) and a public key (placed on the server). Even if someone intercepts your traffic, they cannot log in without the private key file.

Generate a key pair on your local machine (not the server)

# On your LOCAL computer (macOS, Linux, or Windows with WSL)
ssh-keygen -t ed25519 -C "[email protected]" -f ~/.ssh/asiagb_vps

# This creates two files:
# ~/.ssh/asiagb_vps       (private key — keep this secret)
# ~/.ssh/asiagb_vps.pub   (public key — copy this to the server)

Copy the public key to your server

# Option A: use ssh-copy-id (easiest)
ssh-copy-id -i ~/.ssh/asiagb_vps.pub deploy@YOUR_SERVER_IP

# Option B: manual copy (if ssh-copy-id is not available)
cat ~/.ssh/asiagb_vps.pub | ssh deploy@YOUR_SERVER_IP \
  "mkdir -p ~/.ssh && chmod 700 ~/.ssh && \
   cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Test your key login before closing your current session

ssh -i ~/.ssh/asiagb_vps deploy@YOUR_SERVER_IP
Important: Do not close your existing root SSH session until you have confirmed that key-based login works for your new user. Locking yourself out requires a console rescue operation through your provider.

Step 4 Harden SSH: Disable Root & Password Login

Once your SSH key is working, disable password authentication and root login entirely. This shuts out the vast majority of automated attack tools that rely on password guessing.

# Open the SSH daemon configuration
nano /etc/ssh/sshd_config

Find and update (or add) these lines:

PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
X11Forwarding no
MaxAuthTries 3
LoginGraceTime 20
# Restart SSH to apply changes
systemctl restart ssh

# Verify SSH status is active
systemctl status ssh

You can also change the default SSH port from 22 to a high port (e.g., 2222 or 49152–65535) by editing Port 22 to your chosen number. Remember to update your UFW rules and local SSH config file accordingly if you do this.

SSH Setting Default Value Recommended Value Why It Matters
PermitRootLogin yes / prohibit-password no Eliminates the most targeted login vector
PasswordAuthentication yes no Forces key-based auth, stops brute force
MaxAuthTries 6 3 Limits guessing attempts per connection
LoginGraceTime 120 20 Reduces the window for slow-connection attacks
X11Forwarding yes no Disables unused GUI forwarding attack surface
Port 22 Custom (optional) Moving off port 22 reduces automated scan noise

Step 5 Configure UFW Firewall

UFW (Uncomplicated Firewall) provides a straightforward interface to iptables. The strategy is simple: deny everything by default, then explicitly allow only what you need.

# Install UFW if not present
apt install ufw -y

# Set default policies: deny all incoming, allow all outgoing
ufw default deny incoming
ufw default allow outgoing

# Allow SSH (adjust port number if you changed it above)
ufw allow 22/tcp

# Allow HTTP and HTTPS if you are running a web server
ufw allow 80/tcp
ufw allow 443/tcp

# Enable the firewall (confirm with 'y' when prompted)
ufw enable

# Verify rules
ufw status verbose
Critical: Always allow SSH before enabling UFW. Enabling UFW without an SSH rule will immediately lock you out of your server. If this happens, use your provider's web console (KVM/VNC) to fix it.

Common additional rules you might need:

# Allow a specific IP to access MySQL (never expose DB to the world)
ufw allow from 203.0.113.10 to any port 3306

# Allow a custom application port
ufw allow 8080/tcp

# Rate-limit SSH to slow brute force further
ufw limit 22/tcp

# Delete a rule
ufw delete allow 8080/tcp

Step 6 Configure Swap Space

Swap is disk space used as overflow when physical RAM is exhausted. On VPS plans with 1–2 GB RAM, swap can prevent your server from crashing when a process spikes unexpectedly. Many providers do not create swap by default, so you should set it up manually.

# Check if any swap currently exists
swapon --show
free -h

# Create a 2GB swap file (adjust size to match your needs)
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

# Make swap permanent across reboots
echo '/swapfile none swap sw 0 0' >> /etc/fstab

# Verify swap is active
swapon --show
free -h

Tune swappiness for a server workload

# Check current swappiness (default is 60)
cat /proc/sys/vm/swappiness

# Set to 10 for server use (less aggressive swapping)
sysctl vm.swappiness=10

# Make permanent
echo 'vm.swappiness=10' >> /etc/sysctl.conf
RAM Size Recommended Swap Notes
512 MB 1 GB Minimum to survive OOM situations
1 GB 2 GB Good balance for small VPS
2 GB 2–4 GB Sufficient for most web stacks
4 GB 4 GB Diminishing returns above this ratio
8 GB+ 4–8 GB (optional) Consider upgrading RAM instead

Step 7 Set Timezone & Hostname

The default timezone on most VPS images is UTC, which is actually a reasonable choice for servers — logs from different contributors and services align more easily. However, you may want to set your local timezone, and you should always set a meaningful hostname.

# List available timezones
timedatectl list-timezones | grep Asia

# Set your timezone (example: Bangkok / ICT)
timedatectl set-timezone Asia/Bangkok

# Verify
timedatectl status
# Set a hostname that identifies this server
hostnamectl set-hostname web01.example.com

# Update /etc/hosts to match (replace the existing 127.0.1.1 line)
nano /etc/hosts
# Add: 127.0.1.1  web01.example.com  web01

# Verify
hostname
hostname -f

Enable NTP time synchronization

Accurate time is critical for SSL certificates, cron jobs, log correlation, and two-factor authentication. Ubuntu 22.04+ uses systemd-timesyncd by default, which is sufficient for most servers.

# Verify NTP is running
timedatectl show-timesync
systemctl status systemd-timesyncd

# If you need higher precision (e.g., for financial apps), install chrony
apt install chrony -y
systemctl enable --now chronyd

Step 8 Install Fail2Ban

Fail2Ban monitors log files and temporarily bans IP addresses that show signs of malicious activity, such as too many failed SSH login attempts. Even with SSH keys enabled, Fail2Ban is a valuable layer of defense that also covers services like Nginx, Postfix, and DirectAdmin.

# Install Fail2Ban
apt install fail2ban -y

# Copy the default config to a local override file
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Open the local config
nano /etc/fail2ban/jail.local

Find the [DEFAULT] section and set appropriate values:

[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 ::1 YOUR_HOME_IP

[sshd]
enabled = true
port    = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
# Start and enable Fail2Ban
systemctl enable fail2ban
systemctl start fail2ban

# Check status and active jails
fail2ban-client status
fail2ban-client status sshd

# View currently banned IPs
fail2ban-client get sshd banned
Tip: Add your home or office IP to ignoreip so you never accidentally lock yourself out. Use CIDR notation for ranges, e.g., 203.0.113.0/24.

Step 9 Enable Automatic Security Updates

Security vulnerabilities are discovered constantly. Manually running apt upgrade every few days is easy to forget. The unattended-upgrades package automatically applies security patches without requiring manual intervention, keeping your system protected even during busy periods.

# Install unattended-upgrades
apt install unattended-upgrades apt-listchanges -y

# Enable and configure
dpkg-reconfigure -plow unattended-upgrades
# Select "Yes" when prompted
# Review configuration
nano /etc/apt/apt.conf.d/50unattended-upgrades

Key settings to verify or adjust in that file:

// Automatically remove unused kernel packages
Unattended-Upgrade::Remove-Unused-Kernels "true";

// Automatically remove unused dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";

// Send email on upgrade errors (requires mail configured)
// Unattended-Upgrade::Mail "[email protected]";

// Reboot automatically if required (use with caution)
// Unattended-Upgrade::Automatic-Reboot "true";
// Unattended-Upgrade::Automatic-Reboot-Time "03:00";
# Test unattended-upgrades in dry-run mode
unattended-upgrade --dry-run --debug

# Force a run immediately to verify
unattended-upgrade -v

Step 10 Install Basic Monitoring Tools

Before deploying any application, equip yourself with tools to understand what is happening on your server. These lightweight utilities help you diagnose performance issues, track resource usage, and spot problems early.

# Install essential monitoring utilities
apt install -y htop iotop nethogs net-tools ncdu curl wget git unzip

# Optional but useful additions
apt install -y glances nload sysstat

Quick reference for common tools

# CPU and process overview (interactive)
htop

# Real-time disk I/O per process
iotop -o

# Real-time network usage per process
nethogs eth0

# Disk space usage by directory (interactive)
ncdu /

# Network interface statistics
netstat -tuln     # open ports and listening services
ss -tulnp         # modern replacement for netstat

# System resource history (requires sysstat)
sar -u 1 5        # CPU usage every 1 second, 5 samples

# Check memory details
free -m

# View running services
systemctl list-units --type=service --state=running

Optional: Install a lightweight uptime monitor

For production servers, consider a simple heartbeat check. Many providers include basic server metrics in their control panel, and you can complement these with free external monitors like UptimeRobot or Freshping that ping your site from multiple global locations every 1–5 minutes.

# Check your server's public IP address
curl ifconfig.me

# Quick connectivity test
curl -I https://asiagb.com

# View recent system logs
journalctl -n 50 --no-pager

# Follow live system log
journalctl -f

Summary: Your VPS Security Checklist

Completing all 10 steps takes about 30–60 minutes for a first-time setup and significantly reduces your attack surface. Here is a quick reference checklist:

  • Step 1 — System update: apt update && apt upgrade -y — patch known vulnerabilities immediately.
  • Step 2 — Non-root user: Create a named sudo user; stop using root for daily operations.
  • Step 3 — SSH keys: Generate an Ed25519 key pair; copy the public key to the server.
  • Step 4 — Harden SSH: Disable PermitRootLogin and PasswordAuthentication.
  • Step 5 — UFW firewall: Default deny; explicitly allow only SSH, HTTP, HTTPS.
  • Step 6 — Swap: Add 1–4 GB swap; set vm.swappiness=10.
  • Step 7 — Timezone & hostname: Set correct timezone; give the server a meaningful hostname.
  • Step 8 — Fail2Ban: Auto-ban IPs after repeated failed login attempts.
  • Step 9 — Auto security updates: Enable unattended-upgrades for hands-free patching.
  • Step 10 — Monitoring tools: Install htop, ncdu, nethogs to watch resource usage.

After completing these steps, your server is hardened against the most common automated attacks. From here, you can move on to deploying your web stack (Nginx, Apache), setting up your database, or configuring your control panel.

Ready to Launch Your VPS in Thailand?

AsiaGB.com offers high-performance SSD VPS hosted in Asia with 99% uptime SLA, instant deployment, and full root access — starting at affordable prices.

View VPS Thailand Plans →

Frequently Asked Questions

Do I need to set up a non-root user immediately?
Yes. Running everything as root is dangerous. Any typo or compromised script runs with unrestricted system access. Creating a named sudo user is the very first configuration step you should take after your first successful SSH login.
Which firewall should I use on Ubuntu VPS?
UFW (Uncomplicated Firewall) is the recommended choice for most users. It provides a friendly interface over iptables, comes pre-installed on Ubuntu, and handles the most common use cases well. For more complex networking rules (load balancers, multi-NIC setups), you may eventually graduate to direct iptables or nftables configuration.
Is SSH key authentication really necessary if I use a strong password?
Yes. Even a 20-character random password can be brute-forced given enough time, and credential stuffing attacks test billions of leaked passwords automatically. SSH keys use mathematical properties that make brute-force computationally infeasible with current technology. Key-based auth combined with disabled password login is the gold standard for server access.
How much swap space should I configure for my VPS?
A general guideline: use 1× to 2× your RAM for servers with 1–4 GB RAM. For a 2 GB RAM VPS, create a 2–4 GB swap file. For servers with 8 GB+ RAM, swap is less critical but 4–8 GB is still a reasonable safety net. Note that swap on SSD storage is much slower than physical RAM, so it should be a last resort, not a substitute for adequate RAM.
How often should I run system updates after initial setup?
For security patches, enable unattended-upgrades (Step 9) so critical fixes are applied automatically. For full package upgrades (including major version bumps), review and apply them manually every 2–4 weeks. Always test upgrades on a staging environment before applying to production if your application has strict dependency requirements.
Does Fail2Ban conflict with UFW?
No, they work together. UFW sets your baseline firewall rules, while Fail2Ban dynamically adds temporary ban rules (via iptables) when it detects attack patterns in your logs. You can verify that Fail2Ban inserts its rules correctly by running iptables -L -n and looking for the f2b-sshd chain after installation.
Should I install a control panel like DirectAdmin?
A control panel like DirectAdmin makes managing websites, email, and DNS much easier compared to managing everything via command line. It is especially recommended if you plan to host multiple websites or hand server management to non-technical users. For single-application deployments where you control everything, a bare server with manual configuration gives you more flexibility.