Long-running service
the agent waits for jobs, polls a queue or serves webhooks continuously.
Practical VPS tutorial
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.

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.
the agent waits for jobs, polls a queue or serves webhooks continuously.
the agent runs once each morning and exits; use a systemd timer.
size 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.

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.txtUse 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-agentThis 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.
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.envAdd the names the application actually reads. For example:
MODEL_API_KEY=replace-with-your-provider-keyMODEL_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.
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.targetThere are three things to adapt before starting it:
ExecStart must match your agent. Use the virtual environment's absolute Python path./var/lib/ai-agent. Configure the app to save durable state there; its code directory is read-only to the service.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.
Check the unit first:
sudo systemd-analyze verify /etc/systemd/system/ai-agent.serviceFix 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-pagerAn 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.serviceClose 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.
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:
203/EXEC or an executable cannot be foundCheck ExecStart, the virtual environment and path permissions.ModuleNotFoundErrorInstall dependencies into the same virtual environment used by the service.Yes, when systemd owns the process. Confirm an actual job works after reconnecting, not just that the unit is marked active.
No. It manages one process on one VPS. Network failures, provider outages and lost task state still need monitoring and recovery.
Use a timer for that. Restart=always would repeatedly rerun a script that exits successfully.
Next step
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.
Affiliate links: you pay the same price as buying direct.