Skip to content

Deploying LocalAI for OpenAI-compatible local inference on Ubuntu 22.04

Stand up a hardened LocalAI on Ubuntu 22.04 — OpenAI-compatible chat, audio, image, and embedding endpoints from a single binary, CPU or GPU, model gallery, nginx + Let's Encrypt.

You’ve spent the last quarter standing up separate services for everything an AI feature touches: vLLM for the chat model, TEI for embeddings, whisper.cpp for transcription, ComfyUI for image generation. Each one is a fine service on its own. Together, on a single workstation-class server that is sized for one specialist team’s intermittent use, they’re four daemons, four monitoring targets, four model caches, four auth shapes, and four sets of failure modes. The team you’re standing this up for has eight people; their combined inference traffic in a day is what a single GPU would otherwise be idle through. You want one daemon with one config that exposes /v1/chat/completions, /v1/embeddings, /v1/audio/transcriptions, and /v1/images/generations from the same process — and that lives or dies as a single systemd unit.

What’s happening

LocalAI is a single-binary OpenAI-compatible inference server that supports llama.cpp (GGUF), vLLM, transformers, whisper.cpp, sentence-transformers, stable-diffusion-cpp, and a handful of other backends as plug-in modules. Every endpoint speaks the OpenAI API shape: /v1/chat/completions, /v1/embeddings, /v1/audio/transcriptions, /v1/images/generations, /v1/rerank. Models are configured via YAML files in /build/models (or whatever directory you mount), one YAML per model, each pointing at the on-disk weight file plus a backend name. The “model gallery” is a curated list of preconfigured models you can pull with one CLI command. LocalAI is the right tool when you want a single endpoint host that serves the long tail of internal AI features — a small team’s chat, a small ingestion pipeline’s embeddings, and a marketing team’s occasional image generation — without operating four separate inference daemons. It is the wrong tool when one of those workloads dominates throughput: a high-QPS chat workload deserves a dedicated vLLM, and a high-throughput embedding workload deserves a dedicated TEI. LocalAI’s strength is consolidation, not raw single-endpoint throughput. Auth is set via the API_KEY env variable; without it, the endpoint is open. Telemetry is on by default and must be turned off. The model directory must be on a persistent volume; pulling GGUF files at every restart is not an acceptable cold start.

How to verify

After install, the host should expose only :443 and :22:

ss -lntp | grep -E ':(80|443|8080)\b'
# 0.0.0.0:443  nginx
# 127.0.0.1:8080 localai

A health check:

curl -sS https://ai.example.com/readyz
# OK

The model list, with auth:

curl -sS -H "Authorization: Bearer $LOCALAI_API_KEY" \
  https://ai.example.com/v1/models | jq '.data[].id'

A chat completion:

curl -sS -H "Authorization: Bearer $LOCALAI_API_KEY" \
  -H "Content-Type: application/json" \
  https://ai.example.com/v1/chat/completions \
  -d '{"model":"llama-3.1-8b-instruct","messages":[{"role":"user","content":"ping"}]}' \
  | jq '.choices[0].message.content'

An embeddings call:

curl -sS -H "Authorization: Bearer $LOCALAI_API_KEY" \
  -H "Content-Type: application/json" \
  https://ai.example.com/v1/embeddings \
  -d '{"model":"bge-large","input":"hello"}' \
  | jq '.data[0].embedding | length'

If the model list is empty, no YAML configs were dropped in /build/models. Confirm the volume mount and the model gallery pull:

docker exec -it localai ls -la /build/models | head

The fix

Save the script below as /root/setup-localai-ubuntu22.sh, then run it. It installs LocalAI on a fresh Ubuntu 22.04 VM via Docker Compose: base update, UFW (SSH + HTTP + HTTPS only), SSH hardening with root key preserved, unattended-upgrades, Docker CE + compose plugin, optional NVIDIA container toolkit (when LOCALAI_DEVICE=gpu), the LocalAI container with auth token and telemetry settings written to /opt/localai/.env with chmod 600, a model gallery preload (you choose which models), nginx terminating TLS with bearer-token auth checked at the edge, Let’s Encrypt via the certbot nginx plugin, and a poll loop that waits for /readyz.

#!/usr/bin/env bash
set -euo pipefail

### Ubuntu 22.04 LocalAI clean VM installer
### Single binary OpenAI-compatible LLM / embeddings / audio / image server
### CPU or NVIDIA GPU (set LOCALAI_DEVICE=gpu)
### Keeps root SSH key login enabled, disables SSH password login
### Bearer-token check at nginx edge
### Reboot remains manual

if [[ "$(id -u)" -ne 0 ]]; then
  echo "Run as root."
  exit 1
fi

: "${LOCALAI_DOMAIN:?Set LOCALAI_DOMAIN=ai.example.com}"
: "${LOCALAI_EMAIL:?Set LOCALAI_EMAIL=ops@example.com for Let's Encrypt}"
LOCALAI_DEVICE="${LOCALAI_DEVICE:-cpu}"   # cpu | gpu
LOCALAI_VERSION="${LOCALAI_VERSION:-v2.22.0}"
LOCALAI_API_KEY="${LOCALAI_API_KEY:-$(openssl rand -hex 32)}"
LOCALAI_PRELOAD_MODELS="${LOCALAI_PRELOAD_MODELS:-llama-3.1-8b-instruct,bge-large-en-v1.5,whisper-1}"

if [[ "${LOCALAI_DEVICE}" == "gpu" ]]; then
  LOCALAI_IMAGE="quay.io/go-skynet/local-ai:${LOCALAI_VERSION}-cublas-cuda12-ffmpeg"
else
  LOCALAI_IMAGE="quay.io/go-skynet/local-ai:${LOCALAI_VERSION}-ffmpeg"
fi

echo
echo "========================================"
echo "LocalAI Ubuntu 22.04 Setup (${LOCALAI_DEVICE})"
echo "Image: ${LOCALAI_IMAGE}"
echo "========================================"
echo

export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get -y upgrade

apt-get -y install \
  vim curl wget ca-certificates gnupg2 \
  chrony fail2ban unattended-upgrades \
  ufw lsof tcpdump dnsutils tar gzip \
  iproute2 net-tools openssl jq \
  software-properties-common pciutils ffmpeg

systemctl enable --now chrony
timedatectl set-ntp true

cat > /etc/sysctl.d/99-localai.conf <<'SYSCTL'
net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
kernel.dmesg_restrict = 1
kernel.kptr_restrict = 2
fs.file-max = 2097152
vm.max_map_count = 262144
SYSCTL
modprobe tcp_bbr || true
echo tcp_bbr > /etc/modules-load.d/bbr.conf
sysctl --system

cat > /etc/security/limits.d/99-localai.conf <<'LIMITS'
* soft nofile 64000
* hard nofile 64000
LIMITS

ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%F-%H%M%S)
set_sshd_option() {
  local key="$1"; local value="$2"
  if grep -qE "^[#[:space:]]*${key}[[:space:]]+" /etc/ssh/sshd_config; then
    sed -i "s|^[#[:space:]]*${key}[[:space:]].*|${key} ${value}|" /etc/ssh/sshd_config
  else
    echo "${key} ${value}" >> /etc/ssh/sshd_config
  fi
}
set_sshd_option PermitRootLogin prohibit-password
set_sshd_option PasswordAuthentication no
set_sshd_option PubkeyAuthentication yes
set_sshd_option X11Forwarding no
set_sshd_option ClientAliveInterval 300
set_sshd_option ClientAliveCountMax 2
sshd -t
systemctl restart ssh

mkdir -p /etc/fail2ban/jail.d
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban

cat > /etc/apt/apt.conf.d/20auto-upgrades <<'AUTOUPG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
AUTOUPG

install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
  | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu jammy stable" \
  > /etc/apt/sources.list.d/docker.list
apt-get update
apt-get -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
systemctl enable --now docker

if [[ "${LOCALAI_DEVICE}" == "gpu" ]]; then
  echo "==> Installing NVIDIA container toolkit"
  curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey \
    | gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg
  curl -fsSL https://nvidia.github.io/libnvidia-container/stable/deb/nvidia-container-toolkit.list \
    | sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' \
    > /etc/apt/sources.list.d/nvidia-container-toolkit.list
  apt-get update
  apt-get -y install nvidia-container-toolkit
  nvidia-ctk runtime configure --runtime=docker
  systemctl restart docker
fi

echo "==> Preparing /opt/localai layout"
mkdir -p /opt/localai /var/lib/localai/models /var/lib/localai/audio /var/lib/localai/images
chmod 700 /opt/localai /var/lib/localai

cat > /opt/localai/.env <<ENV
LOCALAI_IMAGE=${LOCALAI_IMAGE}
LOCALAI_API_KEY=${LOCALAI_API_KEY}
LOCALAI_PRELOAD_MODELS=${LOCALAI_PRELOAD_MODELS}
ENV
chmod 600 /opt/localai/.env

if [[ "${LOCALAI_DEVICE}" == "gpu" ]]; then
  cat > /opt/localai/docker-compose.yml <<'COMPOSE'
services:
  localai:
    image: ${LOCALAI_IMAGE}
    restart: unless-stopped
    runtime: nvidia
    environment:
      API_KEY: ${LOCALAI_API_KEY}
      DEBUG: "false"
      LOCALAI_LOG_LEVEL: info
      MODELS_PATH: /build/models
      AUDIO_DIR: /tmp/generated/audio
      IMAGE_PATH: /tmp/generated/images
      LOCALAI_TELEMETRY: "false"
      LOCALAI_PRELOAD_MODELS_CONFIG: /build/preload.yaml
      LOCALAI_PARALLEL_REQUESTS: "true"
      LOCALAI_SINGLE_ACTIVE_BACKEND: "true"
      LOCALAI_WATCHDOG_IDLE: "true"
      LOCALAI_WATCHDOG_IDLE_TIMEOUT: 15m
    deploy:
      resources:
        reservations:
          devices:
            - driver: nvidia
              count: 1
              capabilities: [gpu]
    volumes:
      - /var/lib/localai/models:/build/models
      - /var/lib/localai/audio:/tmp/generated/audio
      - /var/lib/localai/images:/tmp/generated/images
      - /opt/localai/preload.yaml:/build/preload.yaml:ro
    ports:
      - "127.0.0.1:8080:8080"
    ulimits:
      nofile:
        soft: 64000
        hard: 64000
COMPOSE
else
  cat > /opt/localai/docker-compose.yml <<'COMPOSE'
services:
  localai:
    image: ${LOCALAI_IMAGE}
    restart: unless-stopped
    environment:
      API_KEY: ${LOCALAI_API_KEY}
      DEBUG: "false"
      LOCALAI_LOG_LEVEL: info
      MODELS_PATH: /build/models
      AUDIO_DIR: /tmp/generated/audio
      IMAGE_PATH: /tmp/generated/images
      LOCALAI_TELEMETRY: "false"
      LOCALAI_PRELOAD_MODELS_CONFIG: /build/preload.yaml
      LOCALAI_PARALLEL_REQUESTS: "false"
      LOCALAI_SINGLE_ACTIVE_BACKEND: "true"
      LOCALAI_WATCHDOG_IDLE: "true"
      LOCALAI_WATCHDOG_IDLE_TIMEOUT: 15m
    volumes:
      - /var/lib/localai/models:/build/models
      - /var/lib/localai/audio:/tmp/generated/audio
      - /var/lib/localai/images:/tmp/generated/images
      - /opt/localai/preload.yaml:/build/preload.yaml:ro
    ports:
      - "127.0.0.1:8080:8080"
    ulimits:
      nofile:
        soft: 64000
        hard: 64000
COMPOSE
fi

# Build the preload list -- LocalAI reads gallery model names from this
PRELOAD_YAML="/opt/localai/preload.yaml"
echo "# Auto-generated preload list" > "${PRELOAD_YAML}"
echo "preloaded_models:" >> "${PRELOAD_YAML}"
IFS=',' read -ra PRELOAD_ARR <<< "${LOCALAI_PRELOAD_MODELS}"
for m in "${PRELOAD_ARR[@]}"; do
  echo "  - id: ${m}" >> "${PRELOAD_YAML}"
done
chmod 644 "${PRELOAD_YAML}"

echo "==> Starting LocalAI"
docker compose --env-file /opt/localai/.env -f /opt/localai/docker-compose.yml up -d

echo "==> Waiting for LocalAI /readyz (model preload may take 10-30 minutes on first boot)"
LOCALAI_READY=0
for i in {1..900}; do
  if curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/readyz 2>/dev/null | grep -q '200'; then
    LOCALAI_READY=1
    break
  fi
  sleep 2
done

if [[ "${LOCALAI_READY}" -ne 1 ]]; then
  echo "LocalAI did not become ready in time"
  docker compose -f /opt/localai/docker-compose.yml logs --tail=200 localai || true
  exit 1
fi

apt-get -y install nginx certbot python3-certbot-nginx

cat > /etc/nginx/sites-available/localai <<NGINX
map \$http_authorization \$ai_authorized {
    default                          0;
    "Bearer ${LOCALAI_API_KEY}"      1;
}

upstream localai_backend {
    server 127.0.0.1:8080;
    keepalive 16;
}

server {
    listen 80;
    server_name ${LOCALAI_DOMAIN};
    return 301 https://\$host\$request_uri;
}

server {
    listen 443 ssl http2;
    server_name ${LOCALAI_DOMAIN};

    client_max_body_size 200M;
    proxy_read_timeout   600s;
    proxy_send_timeout   600s;
    proxy_buffering      off;

    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;

    location = /readyz       { proxy_pass http://localai_backend; }
    location = /healthz      { proxy_pass http://localai_backend; }

    location / {
        if (\$ai_authorized = 0) { return 401; }
        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;
        proxy_set_header Authorization "";   # auth verified at edge
        proxy_http_version 1.1;
        proxy_pass http://localai_backend;
    }
}
NGINX

ln -sf /etc/nginx/sites-available/localai /etc/nginx/sites-enabled/localai
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl enable --now nginx
systemctl reload nginx

certbot --nginx --non-interactive --agree-tos \
  -m "${LOCALAI_EMAIL}" -d "${LOCALAI_DOMAIN}" --redirect

systemctl enable --now certbot.timer

apt-get -y upgrade

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(80|443|8080)\b' || true

echo
echo "Containers:"
docker compose -f /opt/localai/docker-compose.yml ps

echo
echo "API key:    ${LOCALAI_API_KEY}"
echo "Endpoint:   https://${LOCALAI_DOMAIN}/v1/*"
echo "Preloaded:  ${LOCALAI_PRELOAD_MODELS}"
echo
echo "Loaded models (auth):"
curl -sS -H "Authorization: Bearer ${LOCALAI_API_KEY}" \
  "https://${LOCALAI_DOMAIN}/v1/models" | jq '.data[].id' || true
echo
echo "Watchdog will unload idle models after 15 minutes to free VRAM/RAM."
echo "Set LOCALAI_WATCHDOG_IDLE=false in /opt/localai/docker-compose.yml if you want them resident."
echo
echo "Model directory: /var/lib/localai/models (must be in your VM-level backup)"

Make it executable and run it:

chmod 700 /root/setup-localai-ubuntu22.sh
LOCALAI_DOMAIN=ai.example.com \
LOCALAI_EMAIL=ops@example.com \
LOCALAI_DEVICE=gpu \
LOCALAI_PRELOAD_MODELS=llama-3.1-8b-instruct,bge-large-en-v1.5,whisper-1 \
/root/setup-localai-ubuntu22.sh

The endpoint is https://ai.example.com/v1/... with the printed bearer token. Application code that previously talked to OpenAI gets one base_url change and one key swap. The model watchdog unloads idle models after fifteen minutes to free memory for the next request; that is the right default for a consolidation host. Disable the watchdog if a workload is hot enough to justify a resident model. Treat /var/lib/localai/models as data that the VM-level backup must cover — re-pulling a 4 GB GGUF every cold start is not what you signed up for.

Run LocalAI on Stack Harbor’s managed cloud compute with patching, monitoring, and Sev-1 escalation in place: Cloud compute. To size the host for your actual workload mix and plan the watchdog policy, start the conversation.