DeployVeraDocs

TECHNICAL REFERENCE

App with a database and a worker

Run a web app, PostgreSQL and a background worker together on DeployVera: a copyable, step-by-step example.

Last reviewed: Markdown

What works

Yes: a managed PostgreSQL database, a background worker and a web app run together in one service. By default the panel does not run Docker Compose multi-service deployments; each service becomes its own application instead.

For prices and quotas see the live plans: https://deployvera.com/docker. The free plan includes 1 application slot; the web app and the worker are two applications, so you need at least 2 slots. The database counts against a separate quota.

  • Web app: a public application (access mode "Public").
  • Worker: a second application with access mode "Internal network only". Applications and databases in the same service reach it at an internal address like http://dv-xxxx:PORT. The worker takes its work from a table in the database, so it needs no outside address.
  • Database: managed PostgreSQL created on the Databases page; you copy its connection URL from the panel.
  • Environment variables are set per application, so DATABASE_URL is added to both.
  • Logs are read per application in the Container log section of its page.

Repository: package.json

Web and worker live in one repository. Every file in this guide sits at the repository root (package.json, Dockerfile, src/).

{
  "name": "web-worker-example",
  "private": true,
  "type": "module",
  "dependencies": { "pg": "^8.13.0" }
}

Repository: src/db.js

The pool and the schema of the table-based job queue. Both applications call it on start-up and create the table if it is missing.

import pg from "pg";

export const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 5 });
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Web and worker both call this at startup; the advisory lock makes it safe to run concurrently.
export async function migrate() {
  for (let attempt = 1; ; attempt++) {
    let client;
    try {
      client = await pool.connect();
      await client.query("SELECT pg_advisory_lock(727001)");
      await client.query(`CREATE TABLE IF NOT EXISTS jobs (
        id BIGSERIAL PRIMARY KEY,
        payload JSONB NOT NULL,
        status TEXT NOT NULL DEFAULT 'pending',
        error TEXT,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        finished_at TIMESTAMPTZ
      )`);
      await client.query("SELECT pg_advisory_unlock(727001)");
      return;
    } catch (error) {
      console.error(`migrate attempt ${attempt} failed: ${error.message}`);
      if (attempt >= 10) throw error;
      await sleep(3000);
    } finally {
      client?.release();
    }
  }
}

Repository: src/web.js

import http from "node:http";
import { pool, migrate } from "./db.js";

await migrate();

const json = (res, status, body) => {
  res.writeHead(status, { "content-type": "application/json" });
  res.end(JSON.stringify(body));
};

const server = http.createServer(async (req, res) => {
  try {
    if (req.method === "POST" && req.url === "/jobs") {
      const { rows } = await pool.query(
        "INSERT INTO jobs (payload) VALUES ($1) RETURNING id",
        [JSON.stringify({ queuedAt: new Date().toISOString() })],
      );
      return json(res, 202, rows[0]);
    }
    if (req.url === "/jobs") {
      const { rows } = await pool.query(
        "SELECT id, status, error, created_at, finished_at FROM jobs ORDER BY id DESC LIMIT 20",
      );
      return json(res, 200, rows);
    }
    json(res, 200, { ok: true });
  } catch (error) {
    console.error(error);
    json(res, 500, { error: "internal" });
  }
});

server.listen(Number(process.env.PORT || 3000), "0.0.0.0", () => console.log("web listening"));
process.on("SIGTERM", () => server.close(() => process.exit(0)));

Repository: src/worker.js

import http from "node:http";
import { pool, migrate, sleep } from "./db.js";

await migrate();

// The panel asks for a port on every application, so the worker answers on it too.
http.createServer((_req, res) => res.end("worker ok"))
  .listen(Number(process.env.PORT || 3000), "0.0.0.0");

let running = true;
process.on("SIGTERM", () => { running = false; });

// SKIP LOCKED lets several worker copies take different jobs without double processing.
async function claim() {
  const { rows } = await pool.query(`UPDATE jobs SET status = 'running'
    WHERE id = (SELECT id FROM jobs WHERE status = 'pending' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1)
    RETURNING id, payload`);
  return rows[0];
}

while (running) {
  let job;
  try { job = await claim(); } catch (error) { console.error("claim failed:", error.message); }
  if (!job) { await sleep(2000); continue; }
  try {
    console.log(`job ${job.id} started`);
    await sleep(1000); // your real work goes here
    await pool.query("UPDATE jobs SET status = 'done', finished_at = now() WHERE id = $1", [job.id]);
    console.log(`job ${job.id} done`);
  } catch (error) {
    console.error(`job ${job.id} failed:`, error.message);
    await pool.query("UPDATE jobs SET status = 'failed', error = $2, finished_at = now() WHERE id = $1", [job.id, String(error.message)]);
  }
}
process.exit(0);

Dockerfile

FROM node:22-slim
WORKDIR /app
COPY package.json ./
RUN npm install --omit=dev
COPY src ./src
# The web app uses this default; the worker application sets APP_ROLE=worker in its environment variables.
ENV APP_ROLE=web
CMD ["sh", "-c", "exec node src/${APP_ROLE}.js"]

1. Create the database

Open the Databases page in the panel, choose PostgreSQL as the engine and create a database attached to your service. When it is running, copy its connection URL. It looks like postgres://user:password@dv-... and is an internal address that only applications in the same service can reach.

Do not commit the URL. You enter it as an environment variable in the next steps.

2. Deploy the web app

In the new application wizard choose the repository and branch, pick Dockerfile as the build method and set the port to 3000. The access mode stays "Public".

Under advanced settings add the environment variable DATABASE_URL (the URL you copied in step 1). The Dockerfile defaults to APP_ROLE=web, so no other variable is needed. Start the deployment; once it is live, the /jobs path on the web address returns an empty list.

If you prefer Detect automatically (Nixpacks) over the Dockerfile, enter node src/web.js as the start command of the web app and node src/worker.js for the worker; the Dockerfile and APP_ROLE are then not needed.

3. Deploy the worker as a second application

Create a second application from the same repository (same service, same branch). Use the Dockerfile build method, port 3000 and access mode "Internal network only". Environment variables: the same DATABASE_URL and APP_ROLE=worker.

If the application already exists, switch the access mode with "Disable public access" on its detail page; this briefly restarts the running application.

The worker takes jobs from the jobs table with FOR UPDATE SKIP LOCKED, so even several worker copies never take the same job twice. No separate queue product is needed.

4. Try it and read the logs

Add a job on your web address and list the jobs. Within a few seconds the status should change from pending to done.

Read the logs on each application's detail page: the web app shows web listening, the worker shows job 1 started and job 1 done. For a build error, check that application's build log; common errors are in /docs/en/build-errors.

curl -X POST https://YOUR-WEB-ADDRESS/jobs
curl https://YOUR-WEB-ADDRESS/jobs

"Ship it" from Claude Code

With the DeployVera MCP server connected (setup: /docs/en/mcp) you can give a request like the one below in the repository.

The agent creates each application with create_project (which always asks for your approval in the browser), writes the variables with set_env_vars, follows the build with deploy and get_build, and reads logs with get_build_logs. Creating the database and setting the worker's access mode to "Internal network only" happen in the panel; the agent does not take those two steps.

Ship this repo to DeployVera as two applications. The web app is public; the worker app runs with APP_ROLE=worker. Give both the same DATABASE_URL. When the builds finish, read the logs of each application.

Limits

The panel does not run a Docker Compose file as is; each service is a separate application. Restricted Compose support only appears when it is enabled on the server (/docs/en/compose-migration).

The build directory and Dockerfile path setting may be disabled on the server, which is why the example uses one root Dockerfile and APP_ROLE. Do not rely on subdirectory builds.

Deploying the same repository as two applications builds it twice; resources are shared across all applications in the service.

The queue here is deliberately simple: moving jobs that a crashed worker left as running back to pending after a timeout is up to you. For database backups see /docs/en/backups.

Next steps

Plans and current prices: https://deployvera.com/docker. For persistence and database behaviour see /docs/en/persistence and /docs/en/plans-and-databases.