Deployment GuideUpdated August 22, 2026

Practical VPS tutorial

How to Host an AI Agent 24/7 on a VPS

Keep a Python AI agent running on an Ubuntu VPS with systemd, private API keys and restart limits. Test real jobs, persistence and recovery after SSH closes.

If your agent works only while a terminal is open, the next step is to make it a service. On Ubuntu, I'd use systemd: it starts the process after a reboot, collects logs and restarts it after an unexpected exit.

How to Host an AI Agent 24/7 on a VPS — overview

This guide deploys an existing Python agent that calls an external model API. Bring a project you can already run locally. We'll give it a separate Linux account, a Python environment and a service file; we aren't building the agent itself.

First, decide whether you need a service or a schedule

Long-running service

the agent waits for jobs, polls a queue or serves webhooks continuously.

Scheduler

the agent runs once each morning and exits; use a systemd timer.

Local model runtime

size and deploy the model runtime separately.

What the agent doesDeployment choice
Waits for jobs, polls a queue or serves webhooks continuouslyUse the long-running service below.
Runs once each morning and exitsUse a scheduler such as a systemd timer.
Loads an LLM locallySize and deploy the model runtime separately.

A restart policy won't turn a one-off script into a sensible worker. Check that the start command stays in the foreground and handles shutdown cleanly.

For one light API-backed worker, start testing with 2 vCPU, 2-4 GB RAM and 25-40 GB SSD. That's a planning estimate. Browser automation, file processing and local models can need much more; a remote API call alone doesn't justify a GPU VPS.

2 vCPUstarting test size for one light API-backed worker
2-4 GB RAMplanning estimate for that worker
25-40 GB SSDdisk to start testing with
How to Host an AI Agent 24/7 on a VPS — detail

1. Put the agent code on the VPS

Use a sudo-enabled login account. The example assumes app.py and requirements.txt; replace these with the entry point and installation instructions from your project.

Replace the repository URL and reviewed commit before running:

sudo apt update
sudo apt install -y git python3-venv
sudo mkdir -p /opt/ai-agent
sudo chown "$(id -u):$(id -g)" /opt/ai-agent
git clone YOUR_GIT_REPOSITORY /opt/ai-agent
cd /opt/ai-agent
git checkout --detach YOUR_REVIEWED_COMMIT
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt

Use the Python version the project supports. Keep dependencies pinned through its lock file where available. Avoid installing an unfamiliar agent as root just to get past a permissions error.

Now create a runtime account and protect the deployed code:

sudo useradd --system --user-group --home-dir /var/lib/ai-agent --shell /usr/sbin/nologin ai-agent
sudo chown -R root:root /opt/ai-agent

This account should have no sudo or Docker-group access. It can run the agent, but it cannot rewrite the deployed application. Updates go through your deployment process.

2. Give systemd the API key

Create a root-owned environment file, preserving it if it already exists:

sudo test -e /etc/ai-agent.env || sudo install -m 600 -o root -g root /dev/null /etc/ai-agent.env
sudoedit /etc/ai-agent.env

Add the names the application actually reads. For example:

MODEL_API_KEY=replace-with-your-provider-key

MODEL_API_KEY is a placeholder name, not a standard supported by every framework. Use NAME=value, without shell export commands. systemd reads this file before starting the process.

Use a dedicated provider key. Don't put it in the repository, a command-line argument or routine debug output.

3. Create the systemd service file

Save this as /etc/systemd/system/ai-agent.service using sudoedit:

[Unit]
Description=API-backed AI agent
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
Type=simple
User=ai-agent
Group=ai-agent
WorkingDirectory=/opt/ai-agent
EnvironmentFile=/etc/ai-agent.env
Environment=PYTHONDONTWRITEBYTECODE=1
ExecStart=/opt/ai-agent/.venv/bin/python -u /opt/ai-agent/app.py
Restart=always
RestartSec=10s
TimeoutStopSec=30s
StateDirectory=ai-agent
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true

[Install]
WantedBy=multi-user.target

There are three things to adapt before starting it:

  1. Start command: ExecStart must match your agent. Use the virtual environment's absolute Python path.
  2. Writable state: systemd creates /var/lib/ai-agent. Configure the app to save durable state there; its code directory is read-only to the service.
  3. Access requirements: the filesystem restrictions may block paths your tools previously used. Give the app specific working paths instead of removing all restrictions.

Restart=always handles process exits, except a deliberate service stop. The start limit prevents an endless rapid crash loop. It does not limit requests made by a still-running agent. These behaviors are documented in the systemd service reference.

4. Start it, then test an actual job

Check the unit first:

sudo systemd-analyze verify /etc/systemd/system/ai-agent.service

Fix errors before continuing:

sudo systemctl daemon-reload
sudo systemctl enable --now ai-agent.service
sudo systemctl status ai-agent.service --no-pager
sudo journalctl -u ai-agent.service -n 50 --no-pager

An active status is a useful first check. Now submit one harmless job and inspect its result. If the agent saves progress, confirm the state lands in the intended writable directory.

Then test a controlled restart:

sudo systemctl restart ai-agent.service
sudo systemctl is-active ai-agent.service

Close SSH, reconnect and check the service again. During a maintenance window, also verify it returns after a VPS reboot. That's much more useful than leaving a terminal open and hoping nothing disconnects.

If the service hits its start limit, read the journal and fix the error. Then use sudo systemctl reset-failed ai-agent.service and start it again.

Keep agent ports and paid requests under control

A polling worker may need no inbound port. For HTTP, bind the app to localhost and put authenticated HTTPS in front of public webhooks. Check listeners with sudo ss -lntp.

I'd set these limits before handing it real work:

  1. A timeout and bounded retries for provider calls.
  2. A maximum task duration and application-level usage cap.
  3. Duplicate detection for jobs that send messages or change data.
  4. Narrow tool permissions and approval for sensitive actions where needed.

Common systemd errors

SymptomLikely place to look
203/EXEC or an executable cannot be foundCheck ExecStart, the virtual environment and path permissions.
The app can't write a filePoint its state/cache path at an allowed directory.
ModuleNotFoundErrorInstall dependencies into the same virtual environment used by the service.
Repeated starts, then a failed unitRead the first application error rather than increasing the restart limit.
Active service, no completed jobsCheck the queue, API errors and application logs.

FAQ

Will my agent keep running when I close SSH?

Yes, when systemd owns the process. Confirm an actual job works after reconnecting, not just that the unit is marked active.

Does this guarantee 24/7 uptime?

No. It manages one process on one VPS. Network failures, provider outages and lost task state still need monitoring and recovery.

Can I use this service for an agent that runs once a day?

Use a timer for that. Restart=always would repeatedly rerun a script that exits successfully.

  1. Secure SSH and application ports
  2. Choose RAM for API agents and local models
  3. Back up persistent application data

Next step

Keep the deployment moving

Sources and further reading

Commands assume a fresh Ubuntu server. Replace domains, users, database names and provider-specific values before running them. VPS sizing is a practical starting point, not a guarantee: monitor the real workload and resize when CPU, memory, disk or network headroom becomes tight.

Where to run this

Affiliate links: you pay the same price as buying direct.