Self-Hosted AI Assistant Deployment Guide: Runtime Setup to Secure Access
Learn how to deploy a self-hosted AI assistant on your own Linux server. This guide covers environment preparation, Node.js runtime setup via nvm, application installation, LLM API configuration, troubleshooting common errors, secure access through SSH port forwarding, and credential protection for long-term maintenance.
1. Why Self-Host
Cloud-based chat services are easy to start with, but teams often run into three problems over long-term use: conversation content must stay inside the internal network, switching models requires code changes, and API keys and usage are hard to manage centrally. A self-hosted AI assistant keeps the conversation entry point, model integration, and access control on your own server, letting you decide where data goes and which model services to connect.
It fits scenarios where conversation content has compliance requirements, where you need to switch between multiple model providers, or where keys and usage must be managed centrally. If no one is responsible for day-to-day operations, or you only need occasional use, a cloud service is usually less work.
| Dimension | Self-hosted | Direct cloud service |
|---|---|---|
| Data location | Stays on your server | Handled by the provider |
| Model switching | Edit a config file | Depends on each platform’s client |
| Ops burden | Requires upgrades, backups, monitoring | Essentially none |
| Cost structure | Server plus model API usage fees | Subscription or per-call billing |
This guide follows the deployment order: environment preparation, runtime installation, application installation, LLM API configuration, troubleshooting, accessing the admin interface via SSH port forwarding, and finally acceptance and rollback steps.
2. Environment Preparation
2.1 Verify the System and Resources
Use a long-term support release of a mainstream Linux distribution, such as Ubuntu LTS or Debian stable, which receive security updates for longer periods. Run the following commands to check system information and resource usage:
cat /etc/os-releaseuname -rfree -hdf -h
These four commands show the distribution version, kernel version, memory usage, and free disk space respectively. The resource recommendations in this guide assume a single-user, low-concurrency scenario: at least 2 GB of free memory and 5 GB of free disk space to hold the runtime, dependency packages, and logs. If you plan to retain logs long-term or serve multiple users concurrently, reserve additional space based on log growth and concurrency. When resources are insufficient, installation may fail midway, and the error message may not point to resource issues, so check resources first.
2.2 Use a Dedicated Non-Root User
Long-running services should not run as root. If the service process has a vulnerability, root privileges let an attacker take over the entire machine. Create a dedicated user and use sudo only for operations that require elevated privileges:
sudo adduser assistantsudo usermod -aG sudo assistantsu - assistant
The runtime, application, and configuration files in the following steps all live under this user’s home directory. Sudo is only used for installing system packages and modifying system configuration; daily operation does not require it.
2.3 Check Network Connectivity
The server needs HTTPS access to your chosen model provider’s API endpoint. Run:
curl -sS -o /dev/null -w "%{http_code}\n" https://<model-provider-domain>
Any HTTP status code in the response means DNS resolution, the TCP connection, and the TLS handshake all completed—the network path is working. This does not mean the API is usable; whether it works depends on authentication, covered in Section 5.
If the command times out or errors, troubleshoot in this order:
- Check DNS resolution with
getent hosts <model-provider-domain>. - Check whether the server’s egress firewall or cloud security group allows outbound port 443.
- If the server accesses the internet through a proxy, verify the
HTTPS_PROXYenvironment variable is set correctly. - For certificate errors, check the system time (
timedatectl) and CA certificate integrity. Do not usecurl -kto skip certificate verification.
2.4 Prepare the API Key
Create an API key in your model provider’s console. Save it to a secure location immediately—most platforms will not show the full key again. Create a separate key for each environment, and set usage limits where the platform supports it. Keys must never be committed to code repositories, pasted into chat logs, or captured in screenshots.
3. Install the Node.js Runtime
The application is distributed as a JavaScript package and requires Node.js and npm. There are two common installation approaches.
The first is installing from the system package repository. It is simple, but repository versions usually lag behind the official LTS releases, and upgrading or switching versions is awkward.
The second is using the version manager nvm to install a specific major version. Versions are controllable and switching is easy. This guide uses this approach; it installs into the user directory and does not require sudo.
First download the install script, review its contents, then execute it—avoid piping remote scripts straight into a shell:
curl -fsSLo nvm-install.sh https://raw.githubusercontent.com/nvm-sh/nvm/<nvm-version-tag>/install.shless nvm-install.shbash nvm-install.sh
Log in again or run source ~/.bashrc, then install the LTS version:
nvm install --ltsnvm alias default 'lts/*'
The specific major version should follow the application documentation. If the docs require a particular version, use nvm install <major-version> instead.
3.1 Version Verification
After installation, run:
node -vnpm -vwhich node
node -v and npm -v should output version numbers in the form v<major>.<minor>.<patch>. which node should point to a path under ~/.nvm/. Interpret the results as follows:
- Major version lower than required by the docs: switch to a compliant version, e.g.,
nvm use <major-version>. which nodepoints to/usr/bin/node: an older system-repository version takes precedence; check the PATH order.command not found: the shell configuration has not loaded; log in again and retry.
4. Install the Application
4.1 Install into a Dedicated Directory
Install the application into a dedicated directory with a pinned version. Do not use sudo npm install -g, which writes files into system directories and increases permission risk.
mkdir -p ~/assistant/appcd ~/assistant/appnpm install <package-name>@<pinned-version>
Then verify the binary entry point works:
npx <app-command> --versionls -la ~/assistant/app/node_modules/.bin
The package name, version, and start command should follow the application documentation.
4.2 Register as a User Service
Manage the process with a systemd user service to make starting, stopping, and viewing logs easy. Create ~/.config/systemd/user/assistant.service:
[Unit]Description=Self-hosted AI assistantAfter=network-online.target[Service]WorkingDirectory=%h/assistant/appEnvironmentFile=%h/assistant/config/.envExecStart=<absolute-node-path> <app-entry-file>Restart=on-failure[Install]WantedBy=default.target
%h represents the user’s home directory. You can find <absolute-node-path> with which node. Note that switching Node.js versions changes this path under nvm, so update this file accordingly.
Start and check the service:
systemctl --user daemon-reloadsystemctl --user enable --now assistantsystemctl --user status assistantjournalctl --user -u assistant -n 100 --no-pager
If the service must keep running after you log out, have an administrator run sudo loginctl enable-linger assistant.
5. Configure the LLM API
5.1 Write the Configuration File
Put API settings in a dedicated environment file—never in code or command-line arguments, since command-line arguments persist in shell history. The variable names below are conventions for this guide; replace them with the field names from the application documentation:
mkdir -p ~/assistant/configtouch ~/assistant/config/.envchmod 600 ~/assistant/config/.env
Write the following into the file with an editor:
MODEL_API_BASE=https://<model-provider-domain>/v1MODEL_API_KEY=<your-api-key>MODEL_NAME=<model-name>LISTEN_HOST=127.0.0.1LISTEN_PORT=3000
Field descriptions: MODEL_API_BASE is the API root URL, which usually includes a version path such as /v1. MODEL_API_KEY is the authentication key. MODEL_NAME must exactly match the model identifier provided by the provider. LISTEN_HOST set to 127.0.0.1 means the service only accepts local connections—do not change it to 0.0.0.0.
chmod 600 ensures only the file owner can read and write it. Do not paste the file contents into tickets, chats, or screenshots.
5.2 Connectivity and Authentication Test
If the provider offers a model list endpoint, use it to validate the key. The following commands load variables from the config file, so the key does not appear in command history:
set -a; . ~/assistant/config/.env; set +acurl -sS -w "\nHTTP %{http_code}\n" \-H "Authorization: Bearer $MODEL_API_KEY" \"$MODEL_API_BASE/models"
An HTTP 200 response means the key is valid and the network is reachable. The exact authentication method depends on the provider’s documentation—some providers do not use the Bearer format or do not offer a model list endpoint.
5.3 Error Reference
| Symptom | Common causes | Fix |
|---|---|---|
| 401 | Wrong, expired, or deleted key; stray spaces or quotes in .env | Recheck the key; remove leading/trailing whitespace |
| 403 | No account permission, insufficient balance, IP allowlist or region restriction | Check account status and access policies in the console |
| 404 | MODEL_API_BASE missing the version path, or wrong endpoint path | Correct the base URL per the provider’s docs |
| 429 | Rate limit or quota exceeded | Reduce concurrency, retry later, check usage |
| Request timeout | DNS, egress firewall, or proxy issues | Troubleshoot per Section 2.3 |
| Certificate error | Incorrect system time or missing CA certificates | Fix the time, update system CA certificates; do not disable verification |
If the API reports the model does not exist, check the spelling and capitalization of MODEL_NAME.
6. Troubleshooting Common Installation Failures
When installation or startup fails, work through this checklist:
- Missing dependencies: errors containing
Cannot find module, or native module compilation failures. Re-runnpm installand confirm the Node.js major version meets requirements. Compiling native modules requires system build tools such asbuild-essential, installed via sudo. - Permission denied: errors containing
EACCES. Runls -ld ~/assistant ~/assistant/appand confirm the owner is the assistant user. Do not fix npm permissions with sudo—fix the directory ownership instead. - Port in use: errors containing
EADDRINUSE. Runss -ltnp | grep 3000to find the process holding the port; stop it or changeLISTEN_PORT. - Network timeout: errors containing
ETIMEDOUTorENOTFOUND. Check DNS, egress, and proxy settings per Section 2.3. If the npm registry is unreachable, check the registry URL withnpm config get registry. - Version incompatibility: syntax errors or undefined APIs at startup. Confirm
node -vmatches the application documentation. - Configuration not applied: the service still uses default values. Verify the
.envpath, variable names, and file permissions, then runsystemctl --user restart assistant.
7. Secure Access via SSH Port Forwarding
The admin interface only listens on the server’s loopback address. You access it through an SSH tunnel that maps a local port to the server’s loopback port—no need to expose the admin port to the public internet.
7.1 Server-Side Verification
ss -ltnp | grep 3000
The local address in the output should be 127.0.0.1:3000. If it shows 0.0.0.0:3000 or [::]:3000, the service is listening on all interfaces. Go back to Section 5, fix LISTEN_HOST, and restart the service.
7.2 Establish the Tunnel Locally
On your local machine, run:
ssh -N -L 127.0.0.1:8080:127.0.0.1:3000 -o ExitOnForwardFailure=yes assistant@<server-address>
Parameter meanings: -N skips opening a remote shell and only forwards ports. -L forwards local 127.0.0.1:8080 to the server’s 127.0.0.1:3000. ExitOnForwardFailure=yes makes the command exit immediately if forwarding fails, avoiding the false impression that the tunnel is up.
Once the tunnel is established, open http://127.0.0.1:8080 in your local browser. The local port is bound to the loopback address, so other devices on the same LAN cannot use this tunnel. Use SSH key authentication rather than password login.
7.3 Verify the Port Is Not Publicly Reachable
Configure the server firewall to allow only SSH:
sudo ufw default deny incomingsudo ufw allow OpenSSHsudo ufw enablesudo ufw status verbose
Before enabling the firewall, confirm the SSH port is allowed. If SSH uses a non-standard port, replace OpenSSH with that port. If the server is on a cloud platform, also check the security group rules to allow only the SSH port.
From a machine outside the server’s network (e.g., tethered to a phone hotspot), run:
nc -vz <server-public-ip> 3000
The connection should be refused or time out. If it succeeds, stop the service immediately and review the firewall and security group rules.
7.4 SSH Hardening
Only after key-based login works should you disable password login and root login. Edit /etc/ssh/sshd_config:
PermitRootLogin noPasswordAuthentication no
Keep your current SSH session open while making changes. Check the configuration syntax and reload the service:
sudo sshd -tsudo systemctl reload ssh
The service name may be sshd depending on your system. After the change, test login in a new session; only close the old session after confirming the new one works.
7.5 Disconnect and Clean Up
Press Ctrl+C in the local terminal to close the tunnel. Verify the local port is released:
ss -ltn | grep 8080
No output means the tunnel is closed.
8. Key Protection and Long-Term Maintenance
- Keep
.envfile permissions at 600 and never commit it to version control. - Use a separate key for each environment. Rotate keys regularly per your organization’s policy, and rotate immediately if a leak is suspected.
- Rotation steps: create a new key in the console, update
.env, restart the service, run the tests from Section 5, and once everything checks out, delete the old key in the console. - Before upgrading, back up
~/assistant, then proceed with
