Deploy a Secure Node.js LLM Web App on Ubuntu 24.04
This tutorial explains how to deploy a minimal Express-based Node.js web app on Ubuntu 24.04 that forwards user messages to an OpenAI-compatible LLM API. It covers non-root user setup, SSH hardening, UFW configuration, installing Node.js 24 with nvm, dependency troubleshooting, protecting API keys with environment files, testing API connectivity, accessing the app through an SSH tunnel, running it as a systemd service, and verifying the final deployment.
Deploy a Secure Node.js LLM Web App on Ubuntu 24.04
Introduction: What This Tutorial Covers
Many developers want to run a chat page on their own server and forward user input to an LLM API. This approach has two advantages: the API key stays on your own machine, and the interface can be modified as needed. In practice, the main difficulties usually involve the Node.js version, server permissions, secret management, and network access.
This article does not rely on a third-party scaffold. Instead, it uses Express to build a minimal web app of about 60 lines. The page provides an input box, and the server forwards the input to any OpenAI-compatible endpoint. An OpenAI-compatible endpoint means the request URL ends with /chat/completions and the request body format matches the official OpenAI format. Many LLM platforms provide this type of endpoint.
Target environment: an Ubuntu 24.04 LTS server and a local computer with an SSH client (Windows users can use PowerShell or WSL). All operations in this article are performed as a regular user, not by logging in directly as root.
1. Prepare a Regular User and a Security Baseline
If you currently have only a root account, first create a dedicated regular user for deployment and running the app.
# Run on the server; set a password when promptedsudo adduser deploy# Grant sudo access only for privilege escalation when neededsudo usermod -aG sudo deploy
Next, copy your local SSH public key to the server. If you do not have a key yet, generate one first with ssh-keygen -t ed25519.
# Run on your local computer; replace <server-IP> with the actual addressssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@<server-IP>
Open a new terminal and confirm that you can log in with the key without a password. Only proceed after confirming this works; otherwise, you may lock yourself out of the server.
ssh deploy@<server-IP>
After confirming login works, disable password authentication and root remote login. Ubuntu 24.04 reads configuration files under /etc/ssh/sshd_config.d/, and for the same parameter, the first value read takes precedence. Cloud host images often include 50-cloud-init.conf, which enables password authentication. Therefore, this article names the configuration file 10-hardening.conf so that it takes effect earlier.
sudo tee /etc/ssh/sshd_config.d/10-hardening.conf > /dev/null <<'EOF'PasswordAuthentication noPermitRootLogin noEOF# Check the configuration syntax, then reload the service only if it passessudo sshd -t && sudo systemctl reload ssh# Confirm the final effective valuessudo sshd -T | grep -iE 'passwordauthentication|permitrootlogin'
The output should be passwordauthentication no and permitrootlogin no.
Finally, configure the firewall. Deny all inbound connections by default and allow only SSH. The web app in this article will not expose a port to the public internet. If your SSH service uses a custom port, replace OpenSSH with the corresponding port number, such as 2222/tcp; otherwise, your current connection will be disconnected.
sudo ufw default deny incomingsudo ufw default allow outgoingsudo ufw allow OpenSSHsudo ufw enablesudo ufw status verbose
default allow outgoing is necessary because the server needs to initiate requests to the LLM API.
2. Install and Verify Node.js with nvm
The Node.js version in the Ubuntu software repositories is often outdated. It is recommended to install Node.js with Node Version Manager (nvm), which installs Node.js and global packages under the user’s home directory without requiring sudo.
At the time of writing, Node.js 24 is the current Active LTS version, and Node.js 22 has entered maintenance. For new projects, choose 24. For the nvm version number, refer to the Releases page of the official repository; the example below uses v0.40.3.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.3/install.sh | bash# Reload the shell configuration. If you use zsh, change this to source ~/.zshrcsource ~/.bashrcnvm install 24nvm alias default 24# Verify the version and pathsnode -vnpm -vwhich nodenpm root -g
Expected results: node -v outputs v24.x.x. which node outputs a path beginning with /home/deploy/.nvm/versions/node/. npm root -g outputs lib/node_modules under the same version directory. This path will be useful later when troubleshooting global installation issues.
If which node shows /usr/bin/node, the system-provided Node.js is still ahead in the PATH. Run source ~/.bashrc again, or check whether the nvm loading code in ~/.bashrc is complete.
3. Create the App and Troubleshoot Installation Issues
The project structure is as follows:
llm-web/├── .env├── .gitignore├── .nvmrc├── package.json├── server.js└── public/└── index.html
Create the directory and install dependencies. .nvmrc records the Node.js major version. Later, when you enter this directory, run nvm use to switch to the same version.
mkdir -p ~/llm-web/public && cd ~/llm-webecho "24" > .nvmrcnpm init -ynpm pkg set type=modulenpm pkg set scripts.start="node --env-file=.env server.js"npm install express@5
The --env-file parameter has been supported since Node.js 20.6, so there is no need to install dotenv separately.
Create the server file server.js. It reads environment variables, forwards user messages to the model endpoint, and does not write the API key to logs.
import express from 'express';const {LLM_BASE_URL,LLM_API_KEY,LLM_MODEL,PORT = '3000',HOST = '127.0.0.1',} = process.env;if (!LLM_BASE_URL || !LLM_API_KEY || !LLM_MODEL) {console.error('Missing LLM_BASE_URL, LLM_API_KEY, or LLM_MODEL. Check the .env file.');process.exit(1);}const app = express();app.use(express.json({ limit: '32kb' }));app.use(express.static('public'));app.get('/healthz', (req, res) => res.json({ ok: true }));app.post('/api/chat', async (req, res) => {const message = typeof req.body?.message === 'string' ? req.body.message.trim() : '';if (!message || message.length > 4000) {return res.status(400).json({ error: 'Message must not be empty and must not exceed 4000 characters' });}try {const upstream = await fetch(`${LLM_BASE_URL}/chat/completions`, {method: 'POST',headers: {'Content-Type': 'application/json',Authorization: `Bearer ${LLM_API_KEY}`,},body: JSON.stringify({model: LLM_MODEL,messages: [{ role: 'user', content: message }],}),signal: AbortSignal.timeout(30_000),});if (!upstream.ok) {console.error('Upstream returned status code:', upstream.status);return res.status(502).json({ error: `Model endpoint returned ${upstream.status}` });}const data = await upstream.json();res.json({ reply: data.choices?.[0]?.message?.content ?? '' });} catch (err) {console.error('Model call failed:', err.name, err.message);res.status(502).json({ error: 'Model call failed. Check the server logs.' });}});app.listen(Number(PORT), HOST, () => {console.log(`Listening on http://${HOST}:${PORT}`);});
Create the frontend page public/index.html:
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>LLM Test Page</title></head><body><textarea id="msg" rows="4" cols="60"></textarea><br><button id="send">Send</button><pre id="out"></pre><script>document.getElementById('send').onclick = async () => {const r = await fetch('/api/chat', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ message: document.getElementById('msg').value }),});const d = await r.json();document.getElementById('out').textContent = d.reply ?? d.error;};</script></body></html>
Add .gitignore to prevent secrets and dependencies from being committed to the code repository:
printf ".env\nnode_modules/\n" > .gitignore
Troubleshooting in this directory usually centers on the installation phase. If npm install fails, use the table below.
| Symptom | Common cause | Resolution |
|---|---|---|
EACCES: permission denied |
The system Node.js is being used, or sudo npm was used by mistake |
Use which npm to confirm the path is under ~/.nvm, and do not use sudo npm install -g |
ENOTEMPTY |
A previous installation was interrupted, leaving an incomplete directory | First run ls "$(npm root -g)" to inspect leftovers, then delete only the package directory in the error path, not the entire node_modules |
SyntaxError or --env-file is not recognized |
Node.js version is lower than 20.6 | Run node -v, then use nvm use 24 to switch versions |
deprecated warning |
A dependency’s subpackage has been marked deprecated by its author | As long as npm install exits with code 0, the warning does not affect operation. It can be removed later by upgrading dependencies |
UNABLE_TO_VERIFY_LEAF_SIGNATURE or self-signed certificate |
A proxy in the network environment is replacing certificates | Import the enterprise root certificate and specify it with NODE_EXTRA_CA_CERTS=/path/to/certificate.pem. Do not set NODE_TLS_REJECT_UNAUTHORIZED=0 |
After installation, use npm ls express to confirm the dependency version. The output should be express@5.x.x.
4. Configure the LLM API and Verify Connectivity
Create the configuration file. The command below uses nano, which avoids writing the key into command-line history.
nano .env
Fill in the file with the following content. LLM_BASE_URL should follow the provider’s documentation; the OpenAI-compatible format usually looks like https://provider-domain/v1. The model name must also exactly match the name in the provider’s documentation, including capitalization.
# LLM API base URL; do not end with a slashLLM_BASE_URL=https://provider-domain/v1# API key created in the provider consoleLLM_API_KEY=sk-replace-with-your-key# Model name, for example the model ID in the provider documentationLLM_MODEL=replace-with-model-id# Listen only on the local loopback addressPORT=3000HOST=127.0.0.1
After saving, tighten file permissions so that only the file owner can read and write it:
chmod 600 .envls -l .env
The output should begin with -rw-------.
Before starting the app, test the model endpoint directly. This separates network, key, and application code issues.
# Load variables from .env into the current shell and disable automatic exportset -a; . ./.env; set +acurl -sS -m 30 "$LLM_BASE_URL/chat/completions" \-H "Content-Type: application/json" \-H "Authorization: Bearer $LLM_API_KEY" \-d "{\"model\":\"$LLM_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}]}"
If the returned JSON contains a choices field, the endpoint is working. If one of the following errors appears, troubleshoot in the corresponding direction:
401or403: The API key is incorrect, expired, disabled, or the account quota is exhausted. Check whether.envcontains extra spaces or line breaks.404:LLM_BASE_URLis missing/v1, orLLM_MODELis misspelled.curl: (28) Operation timed out: The server cannot access the external network. Check outbound firewall and proxy settings, and confirm thatdefault allow outgoinginufwis active.curl: (60) SSL certificate problem: This is the same certificate issue as in the previous table; handle it in the same way.
After the endpoint test passes, start the app and verify it locally on the server:
npm start
In another session, run:
curl -s http://127.0.0.1:3000/healthz# Output: {"ok":true}curl -s -X POST http://127.0.0.1:3000/api/chat \-H "Content-Type: application/json" \-d '{"message":"hello"}'
If the second command returns a reply field, the app can forward requests successfully. After confirming this, press Ctrl+C to stop the foreground process; next, systemd will manage it.
5. Access Through an SSH Tunnel and Set Up Persistent Operation
The app listens on 127.0.0.1:3000, so it cannot be accessed directly from external networks. This is intentional. Access is provided by creating an SSH tunnel from your local computer.
Run the following command on your local computer. -N means only forward ports and do not open a remote shell.
ssh -N -L 8080:127.0.0.1:3000 deploy@<server-IP>
Keep this window running, then open http://localhost:8080 in your local browser. All traffic is transmitted through the encrypted SSH channel.
After the tunnel is established, you can confirm the service listening address on the server with:
ss -tlnp | grep 3000
The address in the output should be 127.0.0.1:3000. If it shows 0.0.0.0:3000, the HOST setting in .env is incorrect; modify it and restart the service.
Configure a systemd Service
If you run npm start manually, the app stops when you close the terminal. systemd can start the app at boot and restart it automatically after a crash.
First, get the absolute path to Node.js. systemd does not load nvm’s shell configuration, so an absolute path is required.
which node
Assume the output is /home/deploy/.nvm/versions/node/v24.x.x/bin/node. Create the service file:
sudo nano /etc/systemd/system/llm-web.service
Write the following content, replacing the path in ExecStart with the output from the previous step:
[Unit]Description=LLM Web AppAfter=network-online.targetWants=network-online.target[Service]Type=simpleUser=deployWorkingDirectory=/home/deploy/llm-webExecStart=/home/deploy/.nvm/versions/node/v24.x.x/bin/node --env-file=.env server.jsRestart=on-failureRestartSec=5NoNewPrivileges=truePrivateTmp=true[Install]WantedBy=multi-user.target
Enable and start the service:
sudo systemctl daemon-reloadsudo systemctl enable --now llm-websystemctl status llm-web --no-pager
View logs:
# Last 50 log linesjournalctl -u llm-web -n 50 --no-pager# Follow logs in real timejournalctl -u llm-web -f
If the service restarts repeatedly, check the first error in the logs. It is usually caused by a missing variable in .env, an incorrect Node.js path, or a port already in use.
Choosing an Access Method
An SSH tunnel is suitable for personal use or a small number of users. It does not require a domain name or certificate, and the service is not exposed to the public internet. If multiple people need to access it directly through a browser, you can use Nginx as a reverse proxy and configure a Let’s Encrypt certificate and login authentication. In that case, the app should still listen only on 127.0.0.1, while Nginx provides HTTPS externally. This approach requires opening port 443 and taking on the maintenance work of certificate renewal and authentication management.
6. Checklist
After deployment, confirm the following items one by one:
- The
deployuser can log in with a key, root remote login is disabled, and password authentication is disabled. -
sudo ufw statusallows only the SSH port. -
node -voutputs v24.x.x, andwhich nodeis under~/.nvm. -
.envpermissions are-rw-------, and the file is included in.gitignore. - A direct call to the model endpoint returns JSON containing
choices. -
ss -tlnp | grep 3000shows127.0.0.1:3000. -
systemctl status llm-webshowsactive (running). - After creating the SSH tunnel locally,
http://localhost:8080can send messages and receive replies normally.
If an API key ever appears in chat history, screenshots, or a code repository, revoke it immediately in the provider console and generate a new one. Also set a usage limit in the console to control the cost risk of unexpected calls.
After completing the steps above, you will have an LLM web app running on Ubuntu 24.04 that can operate long term and is accessible only to you.
