Bitdoze logo

VPS Setup for AI Coding Agents: Secure & Ready to Code

Step-by-step VPS setup for AI coding agents: SSH hardening, CrowdSec, opencode, tmux, and remote access from Zed, VS Code, or Termix. Secure it in one evening.

Dragos

Last updated: 19 min read

VPS Setup for AI Coding Agents: Secure & Ready to Code

Disclosure: this guide contains referral links. If you buy through them, I may earn a commission at no extra cost to you.

A VPS with 2 vCPUs and 4 GB RAM is enough to run AI coding agents, because opencode does its heavy lifting in the LLM APIs and not on your server. The setup below takes about 30 minutes: SSH keys, a locked-down user, CrowdSec, opencode V2, and a connection from your Mac through Zed, VS Code, or a browser terminal with Termix.

Running agents on a laptop is fine until the fan sounds like a jet engine and the battery falls off a cliff. A VPS runs 24/7, and you connect to it from your desk, a café, or your phone.

Hetzner €20 Free Credit Hostinger VPS

VPS prices jumped across the board in 2026. If you’re rethinking a rented box, see what changed and when a mini PC wins.

A VPS with 2 vCPUs and 4 GB RAM is enough to get started. opencode itself is lightweight. The heavy lifting happens in the LLM APIs, not on your server.

What this costs

The VPS is single-digit euros per month. The real cost center is LLM API tokens. A heavy agent day can exceed your VPS bill. Watch spend in your provider dashboard and in your opencode session logs. If you’re already burning more than $10/month in API keys, skip per-token pricing with the OpenCode Go $10/month plan (I break down the limits and models in my OpenCode Go $10/month plan review).

What you need before starting

  • A VPS running Ubuntu 26.04 LTS (current) or 24.04 LTS. 22.04 still works but standard support ends May 2027
  • A Mac as your local machine
  • An LLM credential: an API key for at least one provider (Anthropic, OpenAI, Google, …), or an OpenCode Go subscription, or a ChatGPT Plus/Pro account
  • Basic comfort with the terminal

Step 1: Create SSH keys on your Mac

Before touching the server, generate a key pair on your local machine. You’ll use this key to log in without passwords.

Open Terminal on your Mac and run:

bash
ssh-keygen -t ed25519 -C "[email protected]"

Press Enter to accept the default path (~/.ssh/id_ed25519), then set a passphrase when asked. You can leave it blank, but a passphrase adds a useful layer of protection if someone gets your laptop.

Check that the keys were created:

bash
ls ~/.ssh/
# id_ed25519  id_ed25519.pub

The .pub file is your public key. That goes on the server. The other file never leaves your machine.

Add the key to your SSH agent

So you don’t have to type the passphrase every time:

bash
eval "$(ssh-agent -s)"
ssh-add --apple-use-keychain ~/.ssh/id_ed25519

Step 2: First login and server prep

Log into your VPS as root using the temporary password or key your provider gave you:

bash
ssh root@your_server_ip

Update the system first:

bash
apt update && apt upgrade -y

Add swap space

Most budget VPS plans have limited RAM. Swap prevents out-of-memory crashes:

bash
fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' | tee -a /etc/fstab

Step 3: Create a user and add them to sudo

Running everything as root is asking for trouble. Create a regular user for daily work:

bash
adduser aidev

Follow the prompts. Set a password, skip the rest of the fields.

Add the user to the sudo group:

bash
usermod -aG sudo aidev

Allow sudo without a password (since you’ll be using SSH key auth, not passwords):

bash
echo "aidev ALL=(ALL) NOPASSWD:ALL" | tee /etc/sudoers.d/aidev
chmod 0440 /etc/sudoers.d/aidev

Copy your SSH public key to the new user

bash
mkdir -p /home/aidev/.ssh
cp /root/.ssh/authorized_keys /home/aidev/.ssh/
chown -R aidev:aidev /home/aidev/.ssh
chmod 700 /home/aidev/.ssh
chmod 600 /home/aidev/.ssh/authorized_keys

If your root account didn’t have an authorized_keys file (you logged in with a password), paste the contents of your local ~/.ssh/id_ed25519.pub into /home/aidev/.ssh/authorized_keys manually.

Test the new user before doing anything else

Open a second terminal on your Mac and verify the connection works:

bash
ssh aidev@your_server_ip

Once inside, confirm sudo works:

bash
sudo whoami
# root

Lockout protection

Keep both terminal windows open until you’ve finished locking things down. If you lock yourself out at any point (wrong sshd config, bad iptables rule), your provider’s web console (KVM/VNC) is the recovery path. Hetzner and Hostinger both have browser-based consoles that get you back in without SSH.

Step 4: Harden SSH access

Switch to the aidev session for the rest of this guide. Now tighten SSH so it only accepts keys and ignores passwords.

bash
sudo nano /etc/ssh/sshd_config

Find and set these lines:

PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes

Also add a 15-minute idle timeout so abandoned sessions don’t pile up:

ClientAliveInterval 900
ClientAliveCountMax 0

On Ubuntu 24.04 and 26.04, you can also drop these settings into /etc/ssh/sshd_config.d/99-hardening.conf instead of editing the main sshd_config. That is cleaner if you manage configs with Ansible or similar.

Save the file, then restart SSH:

bash
sudo systemctl restart ssh

Try connecting again from your Mac to confirm it still works. If it does, your key auth is solid. If you hit “Too many authentication failures” on reconnect, your SSH client is offering too many keys. See how to fix SSH too many authentication failures.

Step 5: Secure the server with CrowdSec

CrowdSec watches your logs for brute-force attempts, port scans, and other bad behavior. When it spots something suspicious, it blocks the source IP. It’s free. For scenarios, collections, and the community blocklist, see my full CrowdSec VPS security guide.

Install CrowdSec

bash
curl -s https://install.crowdsec.net | sudo sh
sudo apt update && sudo apt install crowdsec -y

Install the firewall bouncer

The bouncer drops traffic from blocked IPs:

bash
sudo apt install crowdsec-firewall-bouncer-iptables -y

On nftables-first systems, the equivalent package is crowdsec-firewall-bouncer-nftables.

Set up firewall rules

Allow only what you need:

bash
# Keep existing connections alive
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
sudo iptables -A INPUT -i lo -j ACCEPT

# Allow SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS (if you later add a web service)
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Drop everything else
sudo iptables -P INPUT DROP

Provider-side firewall

Many providers (Hetzner Cloud firewall, Hostinger firewall) filter traffic before it reaches the VM. Set up a provider-side firewall allowing only 22/80/443 as a cheap extra layer. It also prevents lockout while you’re changing local firewall rules. If you prefer UFW over raw iptables: ufw allow 22/tcp && ufw enable.

Those iptables rules cover host services only; when you add Docker later, follow the DOCKER-USER rules in the BSI report guide or the container ports stay open.

Make firewall rules survive reboots

bash
sudo apt install iptables-persistent -y
# Select Yes when asked to save IPv4 and IPv6 rules
sudo netfilter-persistent save

Verify CrowdSec is running

bash
sudo systemctl status crowdsec
sudo cscli collections list   # should show crowdsecurity/sshd
sudo cscli bouncers list       # should show the firewall bouncer

CrowdSec monitors SSH login attempts. When something looks like a brute-force attack, it bans the source IP without you lifting a finger.

Useful commands to check on it later:

bash
sudo cscli decisions list   # active bans
sudo cscli alerts list      # recent events
sudo cscli metrics          # is it seeing sshd events?

The first bans can take a few minutes of brute-force traffic to appear. Seeing no decisions at minute zero is normal.

Verify before you disconnect

Before you close that second terminal, run through this checklist:

  • SSH as aidev from a fresh terminal after the sshd restart
  • sudo ss -tlnp | grep -E ‘:(22|80|443)\s’ confirms what is listening on those ports
  • sudo journalctl -u ssh -n 20 proves key auth is working and no password attempts were accepted
  • sudo cscli metrics shows CrowdSec is seeing sshd events
  • Second-terminal SSH test before closing the first session after iptables -P INPUT DROP

If you lock yourself out at any point, your provider’s web console (KVM/VNC) is the recovery path.

Step 6: Set up Starship with Catppuccin theme

Starship puts Git status, language versions and exit codes in your prompt, and its theme is one TOML file.

Install Starship as the aidev user:

bash
curl -sS https://starship.rs/install.sh | sh

Add it to your shell’s config. For bash:

bash
echo 'eval "$(starship init bash)"' >> ~/.bashrc

Apply the Catppuccin Mocha theme

Download the theme palette directly into your Starship config:

bash
mkdir -p ~/.config
curl -o ~/.config/starship.toml \
  https://raw.githubusercontent.com/catppuccin/starship/refs/heads/main/themes/mocha.toml

Reload your shell:

bash
source ~/.bashrc

The prompt now shows Git status, the current directory, language versions, and exit codes in Catppuccin Mocha colors. The full setup walkthrough, including Ghostty terminal configuration, is in that guide.

Step 7: Install opencode

opencode is an open-source AI coding agent (now under the OpenCode project) that runs in your terminal. It ships a catalog of 300+ LLM providers via models.dev. For a deeper walkthrough of configuration and workflows, see the complete opencode setup guide.

OpenCode leads the coding lane of the 70 best AI GitHub repos; the other terminal agents there are Pi, Codex CLI and Gemini CLI.

Install opencode V2

bash
curl -fsSL https://opencode.ai/v2/install | bash

Coming from opencode V1?

If you installed opencode before late 2026, you’re on V1. The V2 curl installer replaces the binary. If you installed via a package manager (npm, brew), remove V1 first. Existing opencode.json and .opencode/ definitions keep working. See the migration guide for the full list of breaking changes (plugin API, server API, terminal config rename).

Verify the install:

bash
opencode --version
# should show v2.x

Alternative install paths: npm install -g @opencode/cli, brew install anomalyco/tap/opencode-v2, or Docker via ghcr.io/anomalyco/opencode:<tag>.

Connect a provider with /connect

Start opencode and type /connect. Pick a provider from the list, enter your credentials, then run /models to select a model. Three credential paths work:

  1. With an API key (Anthropic, OpenAI, Google, and others), pick the provider and paste the key. Straightforward.

  2. OpenCode Go gives you a curated set of coding models tested by the OpenCode team for $10/month flat. Subscribe in the console and paste the key via /connect. Worth it if you’re already spending more than $10/month in per-token API keys: do the arithmetic against your last invoice. See my OpenCode Go $10/month plan review for the limits and model list.

  3. With ChatGPT Plus/Pro sign-in, choose “OpenAI” and pick “Sign in with ChatGPT.” Usage counts against your plan, not a separate API key. Context caps: 500K tokens for GPT-6.1 Sol and newer, 272K for older models.

OpenCode Go

If you don’t want to manage API keys at all, the OpenCode Go $10/month plan removes that step. Billing is flat-rate, so a heavy agent day does not change the invoice.

For headless or scripted setups (CI, cron jobs), env vars remain a supported credential source:

bash
export ANTHROPIC_API_KEY="your-key-here"
echo 'export ANTHROPIC_API_KEY="your-key-here"' >> ~/.bashrc
source ~/.bashrc

Smoke test your auth end-to-end:

bash
opencode run "say hi"

If it replies, your credentials work and you’re ready for the interactive TUI.

Run opencode in a persistent session with tmux

If you want opencode to keep running after you disconnect, use tmux. (New to tmux? See tmux basics for beginners.)

bash
sudo apt install tmux -y

Start a named session:

bash
tmux new -s coding

Run opencode inside it, then detach with Ctrl+B, D. When you reconnect later, reattach with:

bash
tmux attach -t coding

Your session and whatever opencode was doing will be exactly where you left it.

V2’s background service can keep sessions alive even when the SSH client drops, but tmux preserves the full-screen TUI state. Keep tmux for reliability. If you just need a single terminal session from a phone or iPad, opencode pair is a lighter alternative to deploying Termix: it generates a one-time link (binds to 127.0.0.1, so tunnel it with ssh -L 49374:127.0.0.1:49374 ai-server).

Step 8: Configure SSH on your Mac

Now make connecting to the server as easy as typing its name. Edit your local SSH config:

bash
nano ~/.ssh/config

Add this block:

Host ai-server
    HostName your_server_ip
    User aidev
    IdentityFile ~/.ssh/id_ed25519
    AddKeysToAgent yes
    UseKeychain yes

Now you can connect with just:

bash
ssh ai-server

The alias covers the IP address, the username, and the key path.

Step 9: Connect with Zed IDE

Zed has built-in remote development support. Your Mac runs the editor UI, while the actual files and processes live on the server. This keeps the UI responsive even when the server is across the world.

A few 2026 notes: Zed requires v0.159 or newer locally. The old relay mode (traffic routed through Zed’s servers) was removed in v0.157. Everything now goes over your own SSH. That’s a privacy and ops improvement. “SSH works” is the only prerequisite.

  1. Download and install Zed on your Mac
  2. Open Remote Projects with Ctrl+Cmd+Shift+O (or press Cmd+Shift+P and search for “Remote Projects”)
  3. Click Connect New Server
  4. Enter your SSH host: ssh://ai-server (using the alias you set in ~/.ssh/config)
  5. Zed installs a small headless server on your VPS automatically
  6. Once connected, choose a folder to open (e.g., /home/aidev/projects)

Large directories

Zed does not handle opening very large directories well (for example / or ~ with more than 100,000 files). Open project subfolders, not your home directory, or the editor will hang.

You get a full editor experience (file tree, terminal, AI features), but all the heavy work happens on the server. You can also open it from the terminal:

bash
zed ssh://ai-server/home/aidev/projects/my-project

The terminal inside Zed connects directly to your server, so you can run opencode right there alongside your editor.

Step 10: Connect with VS Code

If you prefer VS Code, the Remote SSH extension gives you a similar experience.

  1. Install the Remote, SSH extension from the extensions panel
  2. Press Cmd+Shift+P and search for Remote-SSH: Connect to Host
  3. Select ai-server (it reads your ~/.ssh/config automatically)
  4. VS Code installs its server component on the VPS and opens a remote window
  5. Open a folder on the server and you’re in

The integrated terminal connects to the server, so you can run opencode, git, or anything else right alongside your editor. Extensions run on the server side, so Python linting, formatters, and language servers work exactly as they would locally.

One gotcha: for Starship icons to render in the VS Code integrated terminal, the Nerd Font must be installed on your Mac (the client renders the terminal, not the server). This trips people up when the font is only on the VPS.

Step 11: Access from anywhere with Termix

Zed and VS Code are great when you’re at your computer, but sometimes you want to jump into a terminal from a browser or another device without installing anything. Termix is self-hosted server management with a web terminal that you can run on your VPS. The project lives at Termix-SSH/Termix.

The full setup is covered in the Termix self-hosting guide. The short version: deploy Termix on your server, put it behind a reverse proxy with HTTPS, and you get a full terminal in any browser.

Once it’s running, you can:

  • SSH into sessions from your iPad or phone
  • Share a terminal link with a collaborator
  • Access your opencode sessions without installing anything on the client

If you just need one terminal session from a phone and don’t want to deploy anything, opencode pair + an SSH tunnel (covered in Step 7) is the lighter alternative. Termix is the richer, always-on option. If you want to control AI agents from your phone more broadly, that guide covers the pattern.

Security note

Put Termix behind authentication. The setup guide covers this, but do not skip it: a web terminal with no auth is a wide-open door. Use HTTP basic auth, an auth proxy, or Termix’s built-in token system.

What to do next

With the server running, here are a few things worth setting up:

Nerd Fonts for Starship icons

Starship uses icons that only render correctly with a Nerd Font. Install one like FiraCode Nerd Font in your terminal and configure it in Zed or VS Code. Remember: for VS Code remote, the font goes on your Mac, not the server.

Node.js or other runtimes

If you’re working on JavaScript projects, install Node.js via nvm so you can switch Node versions. Grab build tools first. Compiling native modules without them is a classic 1 AM time sink on a fresh VPS:

bash
sudo apt install build-essential -y
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.41.0/install.sh | bash
source ~/.bashrc
nvm install --lts

For the full walkthrough, see how to install Node.js using nvm.

Git configuration

Set your name and email on the server so commits look right:

bash
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

For SSH-based GitHub access (push/pull without HTTPS tokens), link GitHub with an SSH key.

Backups

Your AI agent will happily create files that exist only on this box. Commit or push after every task, or set up automated backups to S3-compatible storage. A VPS loss means code loss for anything not in git or a backup. I use Zerobyte Restic GUI to automate backups with restic. It handles scheduled snapshots to S3-compatible storage without much babysitting.

Automatic security updates

Keep the server patched without thinking about it:

bash
sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure --priority=low unattended-upgrades

How long does the VPS setup for AI coding agents take?

About 30 minutes, and it leaves you with:

  • A VPS with a locked-down user, key-only SSH, and CrowdSec watching for threats
  • A clean terminal with Starship and Catppuccin Mocha
  • opencode V2 with /connect auth and 300+ providers ready to go
  • tmux persistence so your agent keeps running across disconnects
  • SSH config on your Mac so connecting takes one command
  • Zed and VS Code wired up for full remote development
  • Termix for browser-based access when you’re away from your machine

After that, your laptop stays cool, and you can run AI coding agents on a VPS that keeps working even when you disconnect. You pick up where you left off from any device.

Did this guide work for you?

Need help with Astro, VPS, or a self-hosted app? View services →