Hosting your own artificial intelligence services on a VPS means taking back full control over your data, costs, and infrastructure. No more depending on SaaS platforms that change their pricing overnight — with a virtual private server, you are the boss.
In this comprehensive guide, we'll build together a VPS setup optimized for AI: from choosing the server to going to production, including security and reverse proxy. Whether you want to run OpenClaw, a FastAPI API, or simply keep your data at home, this tutorial is for you.
🤔 Why Self-Host Your AI Services?
Before diving into the technical stuff, let's ask the fundamental question: why bother?
Privacy and Data Sovereignty
When you use a classic cloud service, your data passes through third-party servers. Your prompts, your files, your conversations — everything is potentially accessible to the provider.
With self-hosting:
- Your data stays on YOUR server
- No third party has access to your prompts or results
- Simplified GDPR compliance (you know exactly where the data is)
- No resale of your data to train models
Total Control Over Infrastructure
| Aspect | Cloud/SaaS | Self-hosted |
|---|---|---|
| Uptime | Depends on provider | You decide |
| Updates | Imposed | At your pace |
| Configuration | Limited | Total |
| Customization | Per the offer | Infinite |
| Data | At their place | At yours |
Controlled Costs
A VPS at 5-15€/month easily replaces several SaaS subscriptions that would cost 50-100€/month combined. We detail the real costs below.
Learning and Skills
Self-hosting is also building skills in Linux, networking, security, and deployment. Skills that are worth gold on the job market.
🖥️ Choosing Your VPS: Minimum Specs
Not all VPS are created equal. Here's what you need to comfortably run an AI setup.
Minimum Recommended Specifications
| Component | Minimum | Recommended | Why |
|---|---|---|---|
| vCPU | 2 cores | 4 cores | API calls and parallel processing need CPU |
| RAM | 4 GB | 8 GB | Python + Node.js + database = hungry |
| Storage | 80 GB SSD | 160 GB NVMe | Logs and AI data grow fast |
| Bandwidth | 1 TB/month | Unlimited | API calls consume bandwidth |
| OS | Ubuntu 22.04+ | Ubuntu 24.04 LTS | Long-term support, massive community |
Which Provider to Choose?
After testing several hosts, here's our recommendation:
Hostinger VPS is our #1 choice for value. With 20% off through our link, you get a performant VPS for the price of a coffee per month.
| Provider | Price/month | vCPU | RAM | Stockage | Our take |
|---|---|---|---|---|---|
| Hostinger 🏆 | ~5-10€ | 2-4 | 4-8 GB | 80-200 GB NVMe | Best value, -20% with our link |
| Hetzner | ~5-15€ | 2-4 | 4-8 GB | 40-160 GB | Excellent, EU datacenters |
| OVH | ~6-12€ | 2-4 | 4-8 GB | 80-160 GB | French, good perf |
| DigitalOcean | ~12-24$ | 2-4 | 4-8 GB | 50-160 GB | Simple but pricier |
| Contabo | ~5-10€ | 4-6 | 8-16 GB | 200-400 GB | Generous specs, average support |
💡 Conseil : start with a plan à 2 vCPU / 4 GB RAM. You can always upgrade later. Avec Hostinger and the 20% discount, it comes to less than 6€/month.
🔧 Initial Ubuntu Setup: The Foundations
Got your VPS? Perfect. Here's how to configure it properly from the start.
Step 1: First SSH Connection
# Connect with the root password provided by your host
ssh root@VOTRE_IP_VPS
# First thing: update the system
apt update && apt upgrade -y
Step 2: Create a Non-Root User
NEVER work as root on a daily basis. This is security rule number 1.
# Create a user with sudo rights
adduser deploy
usermod -aG sudo deploy
# Copy SSH keys to the new user
mkdir -p /home/deploy/.ssh
cp ~/.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
Step 3: Secure SSH
# Edit SSH config
nano /etc/ssh/sshd_config
Modify these lines:
# Disable root login
PermitRootLogin no
# Disable password authentication
PasswordAuthentication no
# Change port (optional but recommended)
Port 2222
# Limit authorized users
AllowUsers deploy
# Restart SSH
systemctl restart sshd
⚠️ Important : before closing your root session, open a NEW terminal and test the connection with the
deployuser. If it doesn't work, you still have the root session to fix it.
Step 4: UFW Firewall
UFW (Uncomplicated Firewall) is your first line of defense.
# Install and configure UFW
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow SSH (on the port you chose)
sudo ufw allow 2222/tcp comment 'SSH'
# Allow HTTP and HTTPS (for reverse proxy)
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
# Enable firewall
sudo ufw enable
# Check status
sudo ufw status verbose
Expected result:
Status: active
To Action From
-- ------ ----
2222/tcp ALLOW IN Anywhere # SSH
80/tcp ALLOW IN Anywhere # HTTP
443/tcp ALLOW IN Anywhere # HTTPS
Step 5: Fail2ban Against Brute-Force
Fail2ban monitors logs and bans IPs that attempt repeated connections.
# Install fail2ban
sudo apt install fail2ban -y
# Create local config
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
Recommended configuration:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
banaction = ufw
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400
# Start fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
# Check status
sudo fail2ban-client status sshd
Step 6: Automatic Updates
Security vulnerabilities don't wait. Enable automatic updates for critical patches.
# Install unattended-upgrades
sudo apt install unattended-upgrades -y
# Configure
sudo dpkg-reconfigure -plow unattended-upgrades
# Check config
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades
Make sure these lines are uncommented:
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
"${distro_id}:${distro_codename}-updates";
};
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";
🏗️ Services to Host
Now that the server is secured, let's install the services. Here's the target architecture:
Internet
│
▼
┌─────────────┐
│ Caddy/Nginx│ ← Reverse proxy + SSL auto
│ (port 443) │
└──────┬──────┘
│
├──► OpenClaw (port 3000) ← Agent IA
├──► FastAPI (port 8000) ← API custom
└──► SQLite Web (port 8080) ← Interface DB
OpenClaw: Your Central AI Agent
OpenClaw is the brain of the operation. It's the AI agent that orchestrates everything.
# Install Node.js 20+
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs
# Install OpenClaw
sudo npm install -g openclaw
# Verify installation
openclaw --version
For full configuration, follow our guide Install OpenClaw on a VPS et Configure OpenClaw.
FastAPI: Your Custom API
FastAPI is perfect for creating custom endpoints that complement your AI setup.
# Install Python 3.11+
sudo apt install python3.11 python3.11-venv python3-pip -y
# Create a virtual environment
python3.11 -m venv /home/deploy/api-env
source /home/deploy/api-env/bin/activate
# Install FastAPI and dependencies
pip install fastapi uvicorn python-dotenv httpx
Minimal FastAPI service example:
# /home/deploy/api/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import os
app = FastAPI(title="Mon API IA", version="1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["https://mondomaine.com"],
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
@app.get("/health")
async def health():
return {"status": "ok", "service": "api-ia"}
@app.get("/api/stats")
async def stats():
# Vos métriques custom
return {
"uptime": "99.9%",
"requests_today": 1337,
"models_active": 3
}
# Create a systemd service
sudo tee /etc/systemd/system/fastapi.service << EOF
[Unit]
Description=FastAPI IA Service
After=network.target
[Service]
User=deploy
WorkingDirectory=/home/deploy/api
ExecStart=/home/deploy/api-env/bin/uvicorn main:app --host 127.0.0.1 --port 8000
Restart=always
RestartSec=5
EnvironmentFile=/home/deploy/api/.env
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable fastapi
sudo systemctl start fastapi
SQLite: Your Lightweight Database
SQLite is perfect for self-hosting: zero config, zero database server, single file.
# SQLite is already installed on Ubuntu, but let's install the tools
sudo apt install sqlite3 -y
# Create your database
mkdir -p /home/deploy/data
sqlite3 /home/deploy/data/app.db << 'SQL'
CREATE TABLE IF NOT EXISTS logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
level TEXT NOT NULL,
message TEXT NOT NULL,
metadata JSON
);
CREATE TABLE IF NOT EXISTS cache (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
expires_at DATETIME
);
CREATE INDEX idx_logs_timestamp ON logs(timestamp);
CREATE INDEX idx_cache_expires ON cache(expires_at);
SQL
💡 Why SQLite over PostgreSQL? For a personal/small project setup, SQLite easily handles millions of rows, barely consumes RAM, and backups are just copying a file. PostgreSQL becomes relevant when you need massive concurrent access or advanced features (advanced JSON, heavy full-text search, etc.).
Reverse Proxy: Caddy (Recommended) or Nginx
The reverse proxy is the gateway to your server. It handles SSL, routing, and security.
Option A: Caddy (recommended for simplicity)
Caddy gère automatiquement les certificats SSL via Let''s Encrypt. Zéro config SSL.
# Install Caddy
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy -y
Caddy configuration (/etc/caddy/Caddyfile) :
mondomaine.com {
# OpenClaw
handle /api/claw/* {
reverse_proxy localhost:3000
}
# FastAPI
handle /api/* {
reverse_proxy localhost:8000
}
# Static site (optional)
handle {
root * /home/deploy/www
file_server
}
# Security headers
header {
X-Content-Type-Options nosniff
X-Frame-Options DENY
Referrer-Policy strict-origin-when-cross-origin
}
}
# Reload Caddy
sudo systemctl reload caddy
Option B : Nginx
sudo apt install nginx certbot python3-certbot-nginx -y
# /etc/nginx/sites-available/mondomaine.com
server {
listen 80;
server_name mondomaine.com;
location /api/claw/ {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /api/ {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
root /home/deploy/www;
index index.html;
}
}
# Enable the site and get SSL
sudo ln -s /etc/nginx/sites-available/mondomaine.com /etc/nginx/sites-enabled/
sudo certbot --nginx -d mondomaine.com
sudo systemctl reload nginx
💰 Real Monthly Costs
Let's talk money. How much does this setup really cost?
| Item | Monthly Cost | Notes |
|---|---|---|
| VPS Hostinger | 5-10€ | With 20% off via our link |
| Domain | ~1€ | ~12€/year divided |
| APIs IA (OpenRouter) | 2-15€ | Depending on usage, free models available |
| External backups | 0-2€ | S3-compatible or rsync |
| Total | 8-28€/mois |
Comparison with SaaS Alternatives
| Service | SaaS | Self-hosted | Savings |
|---|---|---|---|
| AI Agent (ChatGPT Pro) | 20€/mois | 0€ (OpenClaw is free) | 20€/mois |
| API Gateway | 15-50€/mois | 0€ (Caddy is free) | 15-50€/mois |
| Database | 10-30€/mois | 0€ (SQLite is free) | 10-30€/mois |
| Monitoring | 10-25€/mois | 0€ (custom scripts) | 10-25€/mois |
| Total | 55-125€/mois | 8-28€/mois | 47-97€/mois |
💡 Sur un an, le self-hosting peut vous faire économiser 500 à 1 100€. L''investissement en temps (quelques heures de setup) est largement rentabilisé.
📋 Deployment Checklist
Before considering your setup "production-ready," check each point:
✅ Non-root user created
✅ SSH key-only (password disabled)
✅ SSH port changed
✅ UFW enabled (only 80, 443, SSH open)
✅ Fail2ban configured and active
✅ Automatic updates enabled
✅ Reverse proxy with SSL (valid certificate)
✅ Services in systemd (auto-restart)
✅ Backups configured (at minimum daily)
✅ Basic monitoring in place
Automatic Backup Script
#!/bin/bash
# /home/deploy/scripts/backup.sh
BACKUP_DIR="/home/deploy/backups"
DATE=$(date +%Y-%m-%d_%H-%M)
mkdir -p "$BACKUP_DIR"
# Backup SQLite (copie atomique)
sqlite3 /home/deploy/data/app.db ".backup $BACKUP_DIR/app_$DATE.db"
# Backup configs
tar czf "$BACKUP_DIR/configs_$DATE.tar.gz" \
/etc/caddy/Caddyfile \
/home/deploy/api/.env \
/etc/fail2ban/jail.local
# Rotation: keep last 7 days
find "$BACKUP_DIR" -name "*.db" -mtime +7 -delete
find "$BACKUP_DIR" -name "*.tar.gz" -mtime +7 -delete
echo "[$(date)] Backup terminé : $BACKUP_DIR"
# Add to cron (every day at 3am)
crontab -e
# Ajouter : 0 3 * * * /home/deploy/scripts/backup.sh >> /home/deploy/logs/backup.log 2>&1
🔒 Going Further with Security
This guide covers the basics, but security is an ongoing process. To go deeper:
- Advanced monitoring : install Netdata or Prometheus + Grafana to monitor performance
- Alerts : set up Telegram notifications when something goes wrong
- Audit : run
lynis audit systemregularly to detect weaknesses - Docker : isolez chaque service dans son conteneur pour limiter la surface d''attaque
For a complete hardening guide, check our article Secure OpenClaw.
🎯 Summary: Your Setup in 30 Minutes
- Order a VPS sur Hostinger (take advantage of the 20% discount)
- Secure : non-root user, SSH key-only, UFW, fail2ban
- Install : Node.js, Python, SQLite
- Deploy : OpenClaw, FastAPI, Caddy reverse proxy
- Automate : backups, updates, monitoring
- Enjoy : a complete setup for 8-15€/month
Le self-hosting n''est pas réservé aux experts. Avec ce guide, vous avez tout ce qu''il faut pour monter un serveur IA solide, sécurisé et économique. Et le meilleur ? Vous gardez le contrôle total sur vos données et vos outils.
📚 Related Articles
- Qu''est-ce qu''OpenClaw ? — Comprendre l''agent IA que vous allez héberger
- Install OpenClaw on a VPS — Guide d''installation pas à pas
- Configure OpenClaw — Customize your agent
- Secure OpenClaw — Going further with security
- AI APIs: OpenRouter vs Direct Calls — Choosing how to connect your AI models
- Automatiser sa vie avec l''IA — What you can do with your setup