DEV Community

Cover image for Setting Up Your Own Linux Server with Hetzner: A Technical Guide
ITpraktika.com
ITpraktika.com

Posted on • Originally published at itpraktika.com

Setting Up Your Own Linux Server with Hetzner: A Technical Guide

Introduction

In an era where cloud services and managed hosting solutions dominate the landscape, the ability to configure and maintain your own Linux server remains a valuable skill for developers. This guide walks through the process of setting up a production-ready Linux server using Hetzner Cloud, covering everything from initial provisioning to essential security hardening.

Why Hetzner?

Hetzner stands out in the VPS market for several compelling reasons:

  • Cost-effective pricing: Significantly cheaper than AWS, DigitalOcean, or Azure for comparable resources
  • European data centers: Excellent for GDPR compliance and low-latency European deployments
  • Transparent pricing: No hidden costs or complex billing structures
  • Robust infrastructure: German engineering standards with 99.9% uptime SLA
  • Generous bandwidth allocations: 20TB+ on most plans without overage charges

Prerequisites

  • Basic Linux command-line knowledge
  • SSH client installed on your local machine
  • A Hetzner Cloud account (requires payment method)
  • Domain name (optional, for web hosting)

🚀 Get €20 Free Credit

Before we dive in, here's a great opportunity: If you sign up for Hetzner Cloud using this referral link, you'll receive €20 in free credits. This bonus allows you to use their servers completely free for an extended period - almost 5 months on the smallest plan (CPX11)!

This is an excellent way to test the platform risk-free and see if it fits your needs before committing financially.

Step 1: Provisioning Your Server

Creating a Hetzner Account

  1. Navigate to Hetzner Cloud Console
  2. Complete the registration process
  3. Verify your payment method (credit card or PayPal)
  4. Create a new project (e.g., "Production Server")

Server Configuration

When creating your cloud server, consider these specifications:

Operating System Selection:

  • Ubuntu 24.04 LTS (recommended for most users)
  • Debian 12 (for stability-focused deployments)
  • Rocky Linux 9 (for RHEL-compatible environments)

Server Sizing:

  • CPX11 (2 vCPU, 2GB RAM, 40GB SSD) - ~€4.15/month - Ideal for small applications, development environments
  • CPX21 (3 vCPU, 4GB RAM, 80GB SSD) - ~€8.90/month - Good for medium-traffic websites
  • CPX31 (4 vCPU, 8GB RAM, 160GB SSD) - ~€16.50/month - Production applications with moderate load

Location Selection:

  • Nuremberg (nbg1): Primary German datacenter, excellent connectivity
  • Helsinki (hel1): Northern Europe option
  • Falkenstein (fsn1): Alternative German location

SSH Key Configuration

Generate SSH key pair (if you don't have one):

ssh-keygen -t ed25519 -C "your_email@example.com" -f ~/.ssh/hetzner_ed25519
Enter fullscreen mode Exit fullscreen mode

Add public key to Hetzner:

  • Copy your public key: cat ~/.ssh/hetzner_ed25519.pub
  • Paste it in the SSH Keys section during server creation
  • Name it descriptively (e.g., "workstation-2024")

Why ED25519?

  • Smaller key size (68 characters vs 544 for RSA-4096)
  • Better performance
  • More secure against certain attack vectors
  • Supported by all modern SSH implementations

Step 2: Initial Server Access

Once provisioned, Hetzner will display your server's IP address.

ssh root@YOUR_SERVER_IP -i ~/.ssh/hetzner_ed25519
Enter fullscreen mode Exit fullscreen mode

First Login Tasks

# Update package repositories
apt update

# Upgrade all packages
apt upgrade -y

# Install essential utilities
apt install -y curl wget git vim htop ufw fail2ban
Enter fullscreen mode Exit fullscreen mode

Step 3: System Hardening

Create Non-Root User

Running services as root is a critical security vulnerability.

# Create new user
adduser deploy

# Add to sudo group
usermod -aG sudo deploy

# Setup SSH directory for new user
mkdir -p /home/deploy/.ssh
cp /root/.ssh/authorized_keys /home/deploy/.ssh/
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keys
Enter fullscreen mode Exit fullscreen mode

Configure SSH Security

Edit SSH daemon configuration:

nano /etc/ssh/sshd_config
Enter fullscreen mode Exit fullscreen mode

Apply these security-focused changes:

# Disable root login
PermitRootLogin no

# Disable password authentication
PasswordAuthentication no

# Disable challenge-response authentication
ChallengeResponseAuthentication no

# Only allow specific user
AllowUsers deploy

# Use only SSH Protocol 2
Protocol 2

# Reduce login grace time
LoginGraceTime 30

# Maximum authentication attempts
MaxAuthTries 3

# Use strong ciphers only
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
Enter fullscreen mode Exit fullscreen mode

Restart SSH service:

systemctl restart sshd
Enter fullscreen mode Exit fullscreen mode

Test new connection (in a new terminal before closing root session):

ssh deploy@YOUR_SERVER_IP -i ~/.ssh/hetzner_ed25519
Enter fullscreen mode Exit fullscreen mode

Configure Firewall (UFW)

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

# Allow SSH (IMPORTANT: do this before enabling!)
ufw allow 22/tcp

# Allow HTTP/HTTPS (if running web server)
ufw allow 80/tcp
ufw allow 443/tcp

# Enable firewall
ufw enable

# Check status
ufw status verbose
Enter fullscreen mode Exit fullscreen mode

Fail2Ban Configuration

Fail2Ban protects against brute-force attacks by temporarily banning IPs with failed authentication attempts.

# Create local configuration
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
nano /etc/fail2ban/jail.local
Enter fullscreen mode Exit fullscreen mode

Configure SSH protection:

[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
Enter fullscreen mode Exit fullscreen mode

Start Fail2Ban:

systemctl enable fail2ban
systemctl start fail2ban

# Monitor banned IPs
fail2ban-client status sshd
Enter fullscreen mode Exit fullscreen mode

Step 4: System Monitoring

Install Monitoring Tools

# Install monitoring utilities
apt install -y htop iotop nethogs ncdu

# Install automatic security updates
apt install -y unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades
Enter fullscreen mode Exit fullscreen mode

Basic Resource Monitoring

# Real-time process monitoring
htop

# Disk usage analysis
ncdu /

# Network connection monitoring
nethogs

# Disk I/O monitoring
iotop
Enter fullscreen mode Exit fullscreen mode

Log Monitoring

# SSH authentication logs
tail -f /var/log/auth.log

# System logs
journalctl -f

# Fail2Ban logs
tail -f /var/log/fail2ban.log
Enter fullscreen mode Exit fullscreen mode

Step 5: Installing a Web Stack (Optional)

NGINX + PHP + PostgreSQL

# Install NGINX
apt install -y nginx

# Install PHP 8.3 and extensions
apt install -y php8.3-fpm php8.3-cli php8.3-pgsql php8.3-mbstring \
    php8.3-xml php8.3-curl php8.3-zip php8.3-gd

# Install PostgreSQL
apt install -y postgresql postgresql-contrib

# Start services
systemctl enable nginx postgresql php8.3-fpm
systemctl start nginx postgresql php8.3-fpm
Enter fullscreen mode Exit fullscreen mode

Basic NGINX Configuration

nano /etc/nginx/sites-available/default
Enter fullscreen mode Exit fullscreen mode
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/html;
    index index.php index.html;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
    }

    location / {
        try_files $uri $uri/ =404;
    }
}
Enter fullscreen mode Exit fullscreen mode

Test and reload:

nginx -t
systemctl reload nginx
Enter fullscreen mode Exit fullscreen mode

Step 6: SSL/TLS with Let's Encrypt

# Install Certbot
apt install -y certbot python3-certbot-nginx

# Obtain certificate
certbot --nginx -d your-domain.com -d www.your-domain.com

# Auto-renewal is configured automatically
# Test renewal process
certbot renew --dry-run
Enter fullscreen mode Exit fullscreen mode

Maintenance Best Practices

Regular Updates

# Create update script
nano ~/update.sh
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash
apt update
apt upgrade -y
apt autoremove -y
apt autoclean
Enter fullscreen mode Exit fullscreen mode
chmod +x ~/update.sh

# Run weekly via cron
crontab -e
# Add: 0 3 * * 0 /home/deploy/update.sh >> /var/log/updates.log 2>&1
Enter fullscreen mode Exit fullscreen mode

Backup Strategy

# Install backup tools
apt install -y rsync

# Create backup script
nano ~/backup.sh
Enter fullscreen mode Exit fullscreen mode
#!/bin/bash
BACKUP_DIR="/backup/$(date +%Y-%m-%d)"
mkdir -p $BACKUP_DIR

# Backup web files
rsync -av /var/www/ $BACKUP_DIR/www/

# Backup databases
sudo -u postgres pg_dumpall > $BACKUP_DIR/databases.sql

# Keep only last 7 days
find /backup -type d -mtime +7 -exec rm -rf {} +
Enter fullscreen mode Exit fullscreen mode

Monitoring Disk Space

# Add to crontab for daily alerts
0 9 * * * df -h | grep -E '^/dev/' | awk '$5+0 > 80 {print "Warning: " $0}' | mail -s "Disk Space Alert" your@email.com
Enter fullscreen mode Exit fullscreen mode

Cost Analysis

Example monthly costs (as of 2024):

Configuration vCPU RAM Storage Price/Month
Basic 2 2GB 40GB €4.15
Standard 3 4GB 80GB €8.90
Professional 4 8GB 160GB €16.50
Performance 8 16GB 240GB €32.90

Additional costs:

  • Backups: €0.49/month per 10GB
  • Floating IP: €1.19/month
  • Load Balancer: €5.39/month

Troubleshooting Common Issues

Can't Connect via SSH

# Check SSH service status
systemctl status sshd

# Check firewall rules
ufw status

# View SSH logs
tail -100 /var/log/auth.log
Enter fullscreen mode Exit fullscreen mode

High Memory Usage

# Identify memory-hungry processes
ps aux --sort=-%mem | head -10

# Check swap usage
free -h

# Add swap if needed (2GB example)
fallocate -l 2G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab
Enter fullscreen mode Exit fullscreen mode

Disk Space Issues

# Find large directories
du -sh /* | sort -h

# Clean package cache
apt clean
apt autoremove

# Find old log files
find /var/log -type f -mtime +30 -name "*.log"
Enter fullscreen mode Exit fullscreen mode

Advanced Configurations

Docker Installation

# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

# Add user to docker group
usermod -aG docker deploy

# Install Docker Compose
apt install -y docker-compose-plugin
Enter fullscreen mode Exit fullscreen mode

Automated Deployments with GitHub Actions

# .github/workflows/deploy.yml
name: Deploy to Hetzner
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Deploy to server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SERVER_IP }}
          username: deploy
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            cd /var/www/app
            git pull
            docker-compose up -d --build
Enter fullscreen mode Exit fullscreen mode

Conclusion

Setting up your own Linux server provides complete control over your infrastructure, deeper understanding of system administration, and significant cost savings for long-term projects. While managed services offer convenience, the skills gained from managing your own server are invaluable for any developer.

Hetzner's combination of performance, pricing, and reliability makes it an excellent choice for developers looking to self-host applications, learn DevOps practices, or simply escape the vendor lock-in of major cloud providers.

Additional Resources


What are your experiences with self-hosting? Share your Hetzner tips and configurations in the comments below!

Top comments (0)