All guides
Networks & Security

DB-Enabled Bot on VPS: Setup, Security, and Backups

Learn how to run a database-enabled bot on a VPS with PostgreSQL, systemd, Docker Compose, security controls, backups, and recovery checks.

SJslipjar.app 1 December 2026 12 min read 37 views
On this page

A DB-enabled bot on a VPS should keep the bot process, database, secrets, backups, and restart policy under one controlled deployment. PostgreSQL uses TCP port 5432 by default, but a single bot usually needs no public database access: bind PostgreSQL to loopback, restrict the firewall, run migrations deliberately, and test restoration before trusting the setup.

  • Use PostgreSQL for structured bot state, user records, queues, and audit data; SQLite remains reasonable for a small single-process bot with low write concurrency.
  • Keep PostgreSQL on 127.0.0.1 unless another host genuinely needs access. PostgreSQL documents 5432 as its default TCP port.
  • Use systemd or Docker Compose to control startup, health checks, and recovery. Compose supports intervals, timeouts, start periods, and retry counts.
  • Back up with pg_dump or a tested physical-backup strategy. A backup that has never been restored is only an assumption.
  • For server selection, Подобрать VPS на Valebyte compares VPS and dedicated-server options for bots, VPNs, trading tools, and game servers.

What a DB-enabled bot on a VPS actually needs

A database-enabled bot is not simply a bot with a connection string added to its environment. The deployment has at least four moving parts: the application process, the database service, the schema migration path, and the recovery mechanism.

PostgreSQL stores durable state such as users, subscriptions, orders, permissions, conversation history, or scheduled jobs. Redis can handle short-lived queues and locks, but it should not automatically replace PostgreSQL as the source of truth. systemd or Docker Compose controls whether the bot starts after a reboot and how operators inspect failures.

The first design decision is data ownership. A bot that only stores a few preferences may work well with SQLite. A bot that receives concurrent webhooks, schedules jobs, records payments, or supports administrative queries benefits from PostgreSQL because transactions, constraints, indexes, and concurrent connections are explicit parts of the design.

Workload Practical database choice Main constraint
One process, small local state SQLite Write concurrency and file locking
Webhook bot with durable users and jobs PostgreSQL Connection management and migrations
Temporary queue or distributed lock Redis plus PostgreSQL Separate persistence responsibilities
High-risk financial or trading records PostgreSQL with strict transactions Backups, auditability, and recovery testing

For a broader comparison of server sizing decisions, the guide to bot databases on VPS is the closest related reference. The useful question is not “How many CPU cores does a bot need?” but “Which component becomes the first bottleneck: database writes, network calls, memory, or operator attention?”

Network isolation and PostgreSQL configuration

Bind the database to the smallest network surface

PostgreSQL exposes the listen_addresses setting for defining which addresses accept TCP connections. For a bot and database on the same VPS, 127.0.0.1 is usually the correct starting point. The database then accepts local connections without becoming a service that scans, attackers, or accidental clients can reach from the public internet.

PostgreSQL documents 5432 as the default port, but changing the port is not a substitute for access control. A port change may reduce low-effort noise; it does not replace firewall rules, authentication, or an allowlist.

# postgresql.conf
listen_addresses = '127.0.0.1'
port = 5432

# pg_hba.conf
local   all   bot_user                         scram-sha-256
host    botdb bot_user 127.0.0.1/32            scram-sha-256

The exact pg_hba.conf syntax depends on the PostgreSQL installation and authentication method. The principle is stable: give the bot its own database role, grant access only to its own database, and avoid using the PostgreSQL superuser in application code.

Use environment variables without making secrets public

A connection URL belongs in a protected environment file or a secret manager, not in a Git repository, Docker image layer, shell history, or error message. A minimal application configuration might look like this:

DATABASE_URL=postgresql://bot_user:[email protected]:5432/botdb
BOT_TOKEN=replace-with-secret
NODE_ENV=production

File permissions matter as much as the variable names. On a systemd deployment, use an environment file readable by the service account and root. On Docker Compose, keep the production secrets outside the repository and verify that logs do not print the complete connection URL.

Valebyte helps compare VPS and dedicated-server configurations when the bot needs a predictable place for its application, database, and backups. Review Valebyte hosting options before choosing a plan.

Подобрать VPS на Valebyte

Deployment patterns: systemd or Docker Compose

systemd for a host-native installation

systemd is a good fit when PostgreSQL is installed directly on the VPS and the bot is a normal binary, Node.js process, Python service, or compiled application. The service definition makes the startup command, working directory, user, environment file, and restart behavior visible.

[Unit]
Description=Database-enabled bot
After=network-online.target postgresql.service
Wants=network-online.target

[Service]
User=bot
WorkingDirectory=/opt/bot
EnvironmentFile=/etc/bot/bot.env
ExecStart=/usr/bin/node /opt/bot/dist/index.js
Restart=on-failure
RestartSec=5
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

systemd documentation describes Restart=on-failure as an appropriate choice for long-running services that should attempt recovery after errors. The same documentation states that RestartSec= controls the delay before restarting; the documented default is 100 milliseconds, so an explicit value such as 5 seconds avoids a tight crash loop.

Docker Compose for repeatable service boundaries

Docker Compose is useful when the bot, database, and migration process should be described as deployable services. A health check can prevent the application from being treated as ready before PostgreSQL responds.

services:
  db:
    image: postgres:16
    environment:
      POSTGRES_DB: botdb
      POSTGRES_USER: bot_user
      POSTGRES_PASSWORD: change-this-password
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U bot_user -d botdb"]
      interval: 10s
      timeout: 5s
      retries: 3

  bot:
    build: .
    env_file:
      - .env
    depends_on:
      db:
        condition: service_healthy

volumes:
  pgdata:

The values above are deployment settings, not performance benchmarks. Docker documents these health-check fields as durations and retry controls, and its startup-order documentation shows the service_healthy pattern for waiting on a dependency.

The choice is operational. systemd usually integrates more naturally with a VPS host and its existing PostgreSQL package. Compose makes service relationships and local reproduction clearer. Either approach still needs migrations, logs, backups, and a recovery procedure.

Schema migrations, queues, and failure handling

Make schema changes explicit

A production bot should not silently create or alter tables during every startup. Use a migration tool appropriate to the language: Prisma, Drizzle, Knex, Alembic, Flyway, Liquibase, or the migration system included with the framework.

Migration files should be ordered and committed with the application version that requires them. A safe deployment sequence is: create a backup, apply a backward-compatible migration, deploy the bot, verify logs, then remove obsolete columns in a later change.

Database constraints should enforce rules that the bot cannot afford to violate. A unique constraint on an external user ID prevents duplicate accounts. A foreign key prevents orphaned records. A transaction ensures that a payment record and its related state change succeed together or fail together.

Do not let retries duplicate side effects

Webhook delivery and network requests can be retried. A bot that inserts a new order every time it sees the same event can create duplicates even when PostgreSQL is healthy. Store an external event ID with a unique constraint, then process the event inside a transaction.

CREATE TABLE processed_events (
  event_id text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO processed_events (event_id)
VALUES ($1)
ON CONFLICT (event_id) DO NOTHING;

The application must check whether the insert affected a row. If it did not, the event was already seen and the side effect should not run again. This pattern is more valuable than adding another worker process before the data model is idempotent.

The contrarian choice: one VPS can be safer than premature separation

The conventional advice is to place the bot and database on separate servers as soon as possible. That can be correct for high-risk isolation, independent scaling, or strict availability requirements, but separation also adds network credentials, firewall rules, latency between services, another failure domain, and more backup paths.

For a single bot with moderate state, a database on the same VPS can reduce the number of moving parts. Loopback connections avoid exposing PostgreSQL to the internet, systemd can order the services, and one backup routine can cover the application configuration and database dump.

Non-obvious rule: service separation is not automatically a reliability improvement. A smaller deployment with a tested restore procedure can be easier to recover than a distributed deployment with untested credentials and network dependencies.

The deciding variables are not fashion or architecture diagrams. They are recovery objectives, data sensitivity, write volume, operational ownership, and whether the bot can tolerate the VPS being unavailable. If the database must survive a complete VPS loss, an external backup destination matters more than moving PostgreSQL to a second machine on the same provider.

For cost-oriented server comparisons, the article on choosing a VPS tariff for one bot provides a related framework. The correct plan is the one that leaves enough memory for PostgreSQL, the runtime, the operating system, and maintenance tasks without relying on swap as normal capacity.

Backups, monitoring, and recovery checks

Use logical backups for simple restoration

pg_dump creates a logical backup that can be restored into a PostgreSQL database. A basic command is:

pg_dump \
  --format=custom \
  --file=/var/backups/botdb-$(date +%F).dump \
  botdb

Store the dump outside the database data directory. A backup on the same disk does not protect against disk loss, filesystem damage, or an operator deleting the VPS. Restrict backup permissions and encrypt the destination when it leaves the server.

Monitor symptoms that explain user-visible failures

Monitor failed service starts, database connection errors, disk space, backup exit codes, and queue age. “The bot is online” is not enough if webhook events are accumulating, migrations are failing, or the database disk is nearly full.

PostgreSQL connection exhaustion often looks like an application outage. Use a connection pool, close connections correctly, and avoid opening a new database connection for every message. The right pool size depends on the runtime, database configuration, and workload; do not copy a large pool setting from a different application.

A restore drill should create a temporary database or isolated VPS, load a recent dump, run the bot’s read-only checks, and confirm that expected tables, indexes, and records exist. Record the commands required for recovery in the same operational documentation as the backup job.

What We Got Wrong / What Surprised Us

The most common mistake is treating VPS capacity as the main design problem. For a database-enabled bot, the harder failures often come from public database exposure, missing migrations, duplicate webhook processing, unverified backups, or a service that never restarts after a reboot.

The surprising observation is that a health check can create false confidence. Docker Compose can report a database container as healthy while the application still has invalid credentials, the wrong schema, a failed migration, or a connection pool problem. “Database accepts a probe” and “bot can complete its transaction” are different checks.

Another mistake is changing PostgreSQL’s port and assuming the service is protected. Port 5432 is documented as the default, but security comes from binding, authentication, firewall policy, least-privilege roles, and secret handling—not from obscurity.

Practical Takeaways

  1. Choose the database. Decide between SQLite and PostgreSQL after listing write concurrency, durable entities, and transaction requirements. Expected outcome: fewer migrations from the wrong storage model. Time: 30–60 minutes. Difficulty: low.
  2. Create a dedicated database role. Grant the bot access only to its own database and schema. Expected outcome: a compromised bot token does not automatically grant administrative database access. Time: 30 minutes. Difficulty: medium.
  3. Bind PostgreSQL locally. Use 127.0.0.1 for same-VPS deployments and permit remote access only when required. Expected outcome: a smaller attack surface. Time: 15–30 minutes. Difficulty: medium.
  4. Add service recovery. Configure systemd Restart=on-failure with an explicit delay, or use Compose health checks and dependency conditions. Expected outcome: controlled recovery after process crashes and reboots. Time: 30–60 minutes. Difficulty: medium.
  5. Make events idempotent. Store provider event IDs with a unique constraint before applying side effects. Expected outcome: retries do not create duplicate orders, users, or jobs. Time: 1–3 hours. Difficulty: medium.
  6. Automate and restore a backup. Run pg_dump, copy the result away from the VPS, then restore it into an isolated database. Expected outcome: a recovery procedure that has been verified rather than assumed. Time: 1–3 hours initially. Difficulty: medium.

Need a VPS for a bot with PostgreSQL, backups, and room for maintenance? Compare real VPS and dedicated-server offers, then choose a configuration that fits the bot’s database and recovery plan.

Подобрать VPS на Valebyte

FAQ

Can I run a database-enabled bot and PostgreSQL on one VPS?

Yes. A single VPS is often a sensible starting point when the bot and database share the same lifecycle and PostgreSQL can remain bound to 127.0.0.1. Separate servers become more useful when isolation, independent scaling, or protection from complete VPS loss is required.

Should PostgreSQL port 5432 be open on the internet?

Usually not for a bot and database running on the same VPS. PostgreSQL uses 5432 by default, but the port should remain private unless a remote client genuinely needs access; then use firewall allowlists, encrypted connections, strong authentication, and a dedicated role.

Is Docker Compose enough to keep the bot reliable?

No. Compose can define health checks and startup dependencies, but it cannot fix bad migrations, invalid credentials, duplicate webhook handling, or untested backups. Reliability requires application-level checks and a documented restore process.

How often should I test a bot database backup?

Test whenever the schema, backup command, storage destination, or deployment process changes. The schedule should match the bot’s acceptable data loss, but the key requirement is that restoration produces a usable database rather than merely creating a backup file.

PostgreSQL connection configuration documentation, systemd service restart documentation, and Docker Compose health check documentation provide the underlying configuration references.

SJ

slipjar.app

Editorial team

The slipjar.app team writes about hosting, servers and infrastructure in plain language.

Was this article helpful?
Networks & Security

Read next.

Whole category

New guides every week.

A digest of the best pieces on servers, VPN and self-hosted software. No ads, no spam.

1 email a weekOne-click unsubscribeRU · EN
Only slipjar.app articles, nothing else.