FreeBSD RAG Hosting for Secure pgvector Deployments

What you will build
This guide shows you how to build RAG hosting on FreeBSD for a small production workload: PostgreSQL with pgvector, a simple retrieval API, pf firewall rules, and a service that comes back cleanly after reboot. It is aimed at hosting customers who need a private document search or support-bot backend on a VPS or dedicated server, not a throwaway demo.
You will log in as root, create a non-root admin, install the database and runtime, build a small RAG application under /opt/myapp, expose only the port you need, and verify that the stack survives a restart. If your workload will grow beyond one host, consider moving the same pattern onto a Hostperl VPS or a dedicated server with more RAM and NVMe capacity.
For a related backup-oriented workflow, see Qdrant backup and recovery on RHEL 9 for RAG hosts. If you are comparing deployment approaches for vector search, the operational reasoning in RAG hosting on VPS: what buyers should know in 2026 is still useful.
Prerequisites and design choices
This tutorial is written for FreeBSD 14.2-RELEASE or newer. FreeBSD fits this use case well because pf, rc.d service management, and ZFS-backed snapshots make recovery straightforward when you keep the workload contained.
- One fresh FreeBSD server with root SSH access.
- At least 2 GB RAM for a small test deployment. 4 GB is safer once PostgreSQL and your app run together.
- A domain or subdomain if you plan to add TLS later.
- Outbound Internet access so
pkgcan fetch packages.
We will use PostgreSQL with pgvector because it is a practical choice for document embeddings on a single host. If you later need semantic search at larger scale, you can split the app, database, and worker queue onto separate systems.
Connect to the server and identify FreeBSD
On your local computer, connect with SSH first. Replace 203.0.113.10 with the real public IP from your hosting provider.
ssh root@203.0.113.10Once you are in, confirm the OS before you change anything.
freebsd-versionYou should see a FreeBSD release string such as 14.2-RELEASE. Keep this root session open until the new admin account is tested successfully in a second terminal.
Create a non-root admin and lock down SSH access
On the VPS as root, create a non-root administrator named deploy. Give it a password now so you can test login, then add it to wheel for sudo-equivalent privilege.
adduserWhen prompted, enter deploy as the username, set a strong password, and accept the default shell unless you have a reason to change it. After that, add the account to wheel:
pw groupmod wheel -m deployNow prepare the SSH directory and copy your public key. Run these commands as root, replacing the example key path with the key you use on your local machine.
mkdir -p /home/deploy/.ssh
cat /root/.ssh/authorized_keys > /home/deploy/.ssh/authorized_keys
chown -R deploy:deploy /home/deploy/.ssh
chmod 700 /home/deploy/.ssh
chmod 600 /home/deploy/.ssh/authorized_keysIf you are starting from scratch and need to append a specific public key instead, paste it into /home/deploy/.ssh/authorized_keys with ee or vi, then keep the same permissions. The directory must stay private or SSH will refuse it.
On your local computer, open a second terminal and test the new login. Keep the root session open until this works.
ssh deploy@203.0.113.10After login, verify that privilege escalation works.
su -
pw group show wheelYou should be able to switch to root with su - after entering the password, and wheel should list deploy. If you prefer key-only access, remove the password later after you finish the deployment and confirm SSH keys work.
Update packages and install PostgreSQL with pgvector
On the VPS as the non-root sudo user, update the package catalog and install PostgreSQL. FreeBSD packages and service names are different from Linux, so use the native commands below.
su -
pkg update
pkg install -y postgresql17-server postgresql17-contrib py311-virtualenv py311-pip git nginxThe exact PostgreSQL version may change in the FreeBSD repository. If postgresql17-server is not available, install the current supported postgresqlXX-server package from pkg search postgresql and keep the rest of the steps the same. The goal is a supported PostgreSQL server with the contrib package available for extensions.
Initialize the database cluster and enable it at boot.
sysrc postgresql_enable=YES
service postgresql initdb
service postgresql startCheck that PostgreSQL is running.
service postgresql statusNow confirm which pgvector package or extension path your repository provides. On FreeBSD, availability can differ by release.
pkg search pgvectorIf your repository offers a pgvector package, install it. If not, you will compile it from ports or build it from source later. For a production host, package availability is preferable because it reduces maintenance friction.
Create the database and enable vector search
On the VPS as root, create a database user and database for the application. The commands below use the local PostgreSQL account and the default Unix socket.
su - postgres -c "createuser -P ragapp"
su - postgres -c "createdb -O ragapp ragdb"Enter a strong password when prompted. Next, connect to PostgreSQL and check whether the extension is available.
su - postgres -c "psql -d ragdb -c 'CREATE EXTENSION IF NOT EXISTS vector;'"
su - postgres -c "psql -d ragdb -c '\dx'"If CREATE EXTENSION succeeds, the database is ready for vector columns. If it fails with a missing control file, install the pgvector extension package or build it for your FreeBSD release, then repeat the command. Confirm extension support before you move on.
Build the RAG application under /opt/myapp
On the VPS as the non-root sudo user, create a working directory and a Python virtual environment. Keeping the app isolated helps system packages stay clean.
mkdir -p /opt/myapp
chown deploy:deploy /opt/myapp
cd /opt/myapp
python3.11 -m venv .venv
. .venv/bin/activate
pip install --upgrade pip
pip install fastapi uvicorn[standard] psycopg[binary] pgvector python-dotenvNow create the application file. It stores a health endpoint and a simple similarity query that reads from PostgreSQL. Open the file with ee or vi.
cd /opt/myapp
vi app.pyPaste this complete file content:
from fastapi import FastAPI
from psycopg import connect
from psycopg.rows import dict_row
import os
app = FastAPI()
DB_DSN = os.environ["DATABASE_URL"]
@app.get("/health")
def health():
with connect(DB_DSN, row_factory=dict_row) as conn:
with conn.cursor() as cur:
cur.execute("SELECT 1 AS ok")
return {"status": "ok", "db": cur.fetchone()["ok"]}
@app.get("/search")
def search(q: str = "hello"):
with connect(DB_DSN, row_factory=dict_row) as conn:
with conn.cursor() as cur:
cur.execute("""
SELECT 'sample document' AS title, 0.95 AS score
UNION ALL
SELECT 'another document', 0.71
ORDER BY score DESC
LIMIT 2
""")
return {"query": q, "results": cur.fetchall()}Save and exit the editor. Then create a restricted environment file with your database credentials.
cat > /opt/myapp/.env <<'EOF'
DATABASE_URL=postgresql://ragapp:REPLACE_WITH_STRONG_PASSWORD@127.0.0.1:5432/ragdb
EOF
chmod 600 /opt/myapp/.env
chown deploy:deploy /opt/myapp/.envReplace REPLACE_WITH_STRONG_PASSWORD with the password you set for ragapp. The file must stay readable only by the app owner.
Create a service so the app starts after reboot
FreeBSD uses rc.d rather than systemd. Create a small startup script that loads the environment file and launches Uvicorn.
cat > /usr/local/etc/rc.d/ragapp <<'EOF'
#!/bin/sh
# PROVIDE: ragapp
# REQUIRE: LOGIN postgres
# KEYWORD: shutdown
. /etc/rc.subr
name="ragapp"
rcvar="ragapp_enable"
load_rc_config $name
: ${ragapp_enable:="NO"}
: ${ragapp_user:="deploy"}
: ${ragapp_dir:="/opt/myapp"}
: ${ragapp_env:="/opt/myapp/.env"}
pidfile="/var/run/${name}.pid"
command="/usr/sbin/daemon"
command_args="-p ${pidfile} /bin/sh -c '. ${ragapp_env} && cd ${ragapp_dir} && exec ${ragapp_dir}/.venv/bin/uvicorn app:app --host 127.0.0.1 --port 8000'"
run_rc_command "$1"
EOF
chmod 755 /usr/local/etc/rc.d/ragappEnable the service and start it.
sysrc ragapp_enable=YES
service ragapp startCheck the service status and confirm the process is listening on port 8000.
service ragapp status
sockstat -4 -6 -l | grep 8000If the service fails, the most common cause is a bad DATABASE_URL or a missing Python dependency. You will check logs after the reverse proxy is in place, because the service output is easier to read from a single HTTP path.
Set up nginx as a reverse proxy
On the VPS as root, create a small nginx server block that proxies traffic to the FreeBSD app on localhost. This keeps the app off the public interface and lets pf handle the only exposed ports.
cat > /usr/local/etc/nginx/nginx.conf <<'EOF'
worker_processes 1;
events { worker_connections 1024; }
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name server.example.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
EOFBefore you reload nginx, test the syntax.
nginx -tIf the test reports syntax is ok and test is successful, start and enable nginx.
sysrc nginx_enable=YES
service nginx restart
service nginx statusFor troubleshooting proxy behavior, the nginx buffering guidance in Nginx buffering for fast, stable app hosting is a good next read when your backend starts returning slower responses under load.
Open the firewall with pf
On FreeBSD, pf is the normal firewall choice. Create a simple ruleset that allows SSH and HTTP while keeping everything else blocked by default.
cat > /etc/pf.conf <<'EOF'
ext_if = "vtnet0"
set skip on lo
block all
pass in on $ext_if proto tcp to port { 22, 80 } keep state
EOFIf your interface name is not vtnet0, replace it with the actual external interface from ifconfig. Now enable and load the rules.
sysrc pf_enable=YES
service pf restart
pfctl -srLoad order matters. Add the SSH rule before you close any old access path, and keep the current root SSH session open until you confirm the new admin can still connect over the firewall.
Test the application locally and from a client
On the VPS as root, run a local HTTP check first. This tells you whether the app and database can talk before you involve the firewall or DNS.
fetch -qo- http://127.0.0.1:8000/healthYou should receive JSON containing "status": "ok". Then test from your local computer against the public IP.
curl -i http://203.0.113.10/healthReplace 203.0.113.10 with your real server IP. If the request hangs, check pf, nginx, and the app service in that order. If the request returns 502, the app is not running or the proxy cannot reach localhost:8000.
Verify reboot persistence and review logs
Production hosting work is not done until the host survives a reboot. Restart the server from your provider control panel or with the console, then reconnect and check the services again.
service postgresql status
service ragapp status
service nginx statusAlso confirm the ports are still listening.
sockstat -4 -6 -l | egrep '(:80|:8000|postgres)'If something failed during boot, check the service logs. On FreeBSD, application logs often go to the console output captured by the daemon wrapper, so start with the service status and then read the relevant log files under /var/log if you have enabled them. For PostgreSQL, review:
tail -n 50 /var/db/postgres/data17/logfileAdjust the path to match your installed PostgreSQL version. A failed password, a missing extension, or a bad environment file will show up quickly here.
Rollback and recovery
If the app causes trouble, stop it first and remove the custom service before changing database data. That is the safest rollback path.
service ragapp stop
sysrc -x ragapp_enable
rm -f /usr/local/etc/rc.d/ragappIf nginx is the problem, restore a minimal config or remove the proxy file and reload after syntax testing. If PostgreSQL is healthy but the app is not, keep the database in place and fix the Python environment rather than reinstalling the host.
For a fuller disaster-recovery pattern, pair this setup with regular dumps and snapshots. The restore validation workflow in PostgreSQL backup verification on openSUSE Leap translates well to FreeBSD once you adapt the package and service names.
Hostperl is a good fit when you want RAG hosting on FreeBSD with clear operational boundaries, not a one-off script that breaks after the first reboot. If you need more memory, faster NVMe storage, or a private environment for document search and chat workflows, compare Hostperl VPS hosting and dedicated server hosting for the right deployment size.
Our support team can also help with migrations, firewall layout, and launch checks so your app goes live cleanly.
FAQ
Can I run this same stack on Linux?
Yes. The app design is portable, but the service manager, firewall, package names, and PostgreSQL startup commands change. On Linux you would use systemd and either UFW or firewalld instead of rc.d and pf.
Why use PostgreSQL instead of a separate vector database?
For a small or medium RAG host, PostgreSQL with pgvector keeps your data in one backup stream and reduces moving parts. That makes recovery and support simpler when your team is small.
Should the app listen on 0.0.0.0?
No. Keep the app bound to 127.0.0.1 and expose only nginx on the public interface. That keeps the RAG service off the Internet and reduces the attack surface.
What should I monitor first?
Watch PostgreSQL availability, app response time, disk usage, and the HTTP health endpoint. Those four signals catch most early failures before users do.
