Skip to main content

Cloud and deployment · Intermediate · 20 min

Deploy a web service and PostgreSQL on Render with a Blueprint

By Padding · Updated 18 Nov 2026
Render · Node.js 26.13.1 · PostgreSQL 18

You will describe a Node.js web service and a Render Postgres database in one render.yaml Blueprint, deploy both from GitHub with migrations and a health check, try a pull request preview, and delete everything afterwards.

On this page

Render can create services from clicks in its dashboard, but then the setup lives only in your memory and in the dashboard. A Blueprint moves it into your repository: a file called render.yaml lists every service and database, how they connect and how they deploy. Render reads it, creates what is missing, and updates what changed each time you push.

In this tutorial you build Tally, a tiny Node.js app that counts visits in PostgreSQL. You write its Blueprint with a web service and a Render Postgres database, wire the database URL in without copying it anywhere, run migrations before each release, add a health check, keep a secret out of the file, try a pull request preview, and then delete the lot so nothing keeps running or billing.

If you are still deciding between platforms, read Compare Fly.io, Render and Railway first. This tutorial assumes you have chosen Render.

Step 1 · Build the Tally app

Tally uses Node's built-in http module and one dependency, the pg PostgreSQL driver. Create a folder for it and install the driver at a pinned version:

Bash
mkdir -p ~/tally-render-demo && cd ~/tally-render-demo
git init -b main
npm init -y
npm pkg set type=module
npm pkg set scripts.start="node server.js" scripts.migrate="node migrate.js"
npm install pg@8.23.1
echo "26.13.1" > .node-version
printf 'node_modules\n.env\n' > .gitignore

The .node-version file tells Render which Node.js release to use. Without it, Render builds with its own default, which in November 2026 is Node.js 24. Render reads a NODE_VERSION environment variable before this file, so do not set both.

Create server.js. It records a visit on /, answers /healthz only when the database replies, and shows a count on /admin/count to anyone who sends the admin token:

JavaScript
import http from 'node:http';
import { timingSafeEqual } from 'node:crypto';
import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const port = Number(process.env.PORT ?? 10000);
const adminToken = process.env.ADMIN_TOKEN;

function isAdmin(req) {
  if (!adminToken) return false;
  const given = Buffer.from(req.headers.authorization ?? '');
  const expected = Buffer.from(`Bearer ${adminToken}`);
  return given.length === expected.length && timingSafeEqual(given, expected);
}

function send(res, status, body) {
  res.writeHead(status, { 'content-type': 'text/plain; charset=utf-8' });
  res.end(body + '\n');
}

const server = http.createServer(async (req, res) => {
  try {
    if (req.url === '/healthz') {
      await pool.query('SELECT 1');
      return send(res, 200, 'ok');
    }
    if (req.url === '/') {
      const { rows } = await pool.query(
        'INSERT INTO visits DEFAULT VALUES RETURNING id'
      );
      return send(res, 200, `Tally: visit number ${rows[0].id}`);
    }
    if (req.url === '/admin/count' && isAdmin(req)) {
      const { rows } = await pool.query('SELECT count(*) AS n FROM visits');
      return send(res, 200, `Visits recorded: ${rows[0].n}`);
    }
    return send(res, 404, 'Not found');
  } catch (err) {
    console.error(err);
    return send(res, 500, 'Something went wrong');
  }
});

server.listen(port, '0.0.0.0', () => {
  console.log(`tally listening on port ${port}`);
});

Render web services must listen on host 0.0.0.0 and on the port in the PORT variable, which defaults to 10000. The last three lines do that. When ADMIN_TOKEN is not set, /admin/count behaves as if it does not exist, which matters later for previews.

Create migrate.js. It is the migration step: it creates the table if it is missing, so it is safe to run on every deploy:

JavaScript
import pg from 'pg';

const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
await client.query(`
  CREATE TABLE IF NOT EXISTS visits (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    seen_at timestamptz NOT NULL DEFAULT now()
  )
`);
await client.end();
console.log('migrate: visits table is ready');

A real project would use a migration tool with numbered, versioned files. The shape on Render is the same: one command that brings the schema up to date and exits.

Check it worked

Run these in ~/tally-render-demo:

Bash
npm ls pg
node --check server.js && node --check migrate.js && echo "syntax ok"

The first prints pg@8.23.1 under your project name, and the second prints syntax ok. To run Tally against a local database before you deploy, start PostgreSQL with Docker Compose as in Docker Compose with PostgreSQL and set DATABASE_URL in your shell.

Step 2 · Describe the service and database in render.yaml

Create render.yaml at the root of the repository. Render looks for it there by default:

YAML
services:
  - type: web
    name: tally-web
    runtime: node
    plan: 0.5c-512mb
    region: frankfurt
    branch: main
    buildCommand: npm ci
    preDeployCommand: npm run migrate
    startCommand: npm start
    healthCheckPath: /healthz
    autoDeployTrigger: commit
    envVars:
      - key: DATABASE_URL
        fromDatabase:
          name: tally-db
          property: connectionString
      - key: ADMIN_TOKEN
        sync: false

databases:
  - name: tally-db
    plan: free
    region: frankfurt
    databaseName: tally
    user: tally
    postgresMajorVersion: "18"

What each part does:

  • fromDatabase fills DATABASE_URL with the connection string of tally-db. The password never appears in your repository, and if Render rotates it, the variable follows. Because both resources sit in the same region, the service gets the internal URL, which stays on Render's private network.
  • buildCommand installs exact versions from package-lock.json. startCommand runs the app.
  • preDeployCommand runs npm run migrate after the build and before the new version takes traffic. If it fails, the deploy fails and the previous version keeps serving.
  • healthCheckPath makes Render call /healthz on each new instance. Any 2xx or 3xx answer within five seconds counts as healthy. Traffic moves to the new instance only when it is healthy, so a broken release does not replace a working one.
  • autoDeployTrigger: commit deploys on every push to main. Use checksPass instead to wait for your CI checks.
  • region cannot be changed after creation. Render offers oregon, ohio, virginia, frankfurt and singapore. Frankfurt is the closest of these for most readers in Africa and Europe; pick the one nearest your users, and keep the database in the same region as the service.
  • name, databaseName, user and postgresMajorVersion are also fixed once the database exists, so choose them now.

Health checks that touch the database tell you the app can really serve, but if the database is down for a minute, Render restarts the web instances too. For Tally that is the right trade. A larger app might keep /healthz to the process itself and watch the database separately.

Free plan or paid plan

The pre-deploy command is only available on paid web services, which is why the service uses 0.5c-512mb. Render's pricing page listed it at $7 a month in November 2026, billed by the second while it exists. The database uses the free plan.

To keep the whole tutorial free, set the web service to plan: free, delete the preDeployCommand line and run migrations as part of start instead:

YAML
    plan: free
    startCommand: npm run migrate && npm start

Know the limits before you choose this. A free web service spins down after 15 minutes with no traffic and takes about a minute to wake on the next request, which also costs a visitor on prepaid mobile data a long wait. Each workspace gets 750 free instance hours a month. A free database has 1 GB of storage, you can have only one active per workspace, and it expires 30 days after creation, with a 14-day grace period to upgrade before Render deletes it. These figures are from Render's free tier page as read in November 2026.

Check it worked

Open render.yaml in an editor with YAML schema support (VS Code with the Red Hat YAML extension picks up Render's schema from SchemaStore). Change runtime: node to runtime: nodee and confirm the editor underlines it, then change it back. If you have the Render CLI 2.7.0 or newer, render blueprints validate render.yaml checks the file against Render's rules and reports any errors.

Step 3 · Keep the admin token out of the file

ADMIN_TOKEN is listed with sync: false and no value. That tells Render the variable exists but its value lives only in Render: when you create the Blueprint, the dashboard asks you for it. Never put a secret under value: in render.yaml; anyone who can read the repository could read it, and it stays in Git history after you remove it. Keep secrets out of Git covers what to do if one slips in.

Generate a token now and save it in your password manager. You paste it into Render in the next step:

Bash
openssl rand -hex 32

Two details of sync: false catch people out. Render prompts for the value only the first time it creates the Blueprint; later syncs ignore that variable, so to change it you edit it on the service's Environment page in the dashboard. And sync: false values are not copied into preview environments.

For a secret that only the app needs and you never type yourself, such as a session signing key, generateValue: true makes Render create a random 256-bit value instead.

Check it worked

Look at how the variable appears in the Blueprint:

Bash
grep -n -A1 "ADMIN_TOKEN" render.yaml

The only match is - key: ADMIN_TOKEN, with sync: false on the next line and no value:. Then search the project for the first eight characters of your saved token with grep -rn "<first 8 characters>" --exclude-dir=node_modules . (replace the placeholder with your own characters). It prints nothing.

Step 4 · Push to GitHub and create the Blueprint

Commit the project and push it to a new private repository:

Bash
git add .
git commit -m "Tally app and Render Blueprint"
gh repo create tally-render-demo --private --source=. --push

The paid web service starts billing from here if you kept 0.5c-512mb. Now create the Blueprint in Render:

  1. In the Render dashboard, choose New > Blueprint.
  2. Click Connect next to tally-render-demo. If it is not listed, give Render's GitHub app access to the repository first.
  3. Give the Blueprint a name, such as tally, and choose the main branch. Leave Blueprint Path empty, because render.yaml is at the root.
  4. Render lists the resources it will create: tally-web and tally-db. It also shows a field for ADMIN_TOKEN. Paste the token from your password manager.
  5. Confirm. Render creates the database first, then builds and deploys the service.

From now on, auto sync is on: when a push to main changes render.yaml, Render applies the change to the matching resources.

Check it worked

The Blueprint's page lists two resources, tally-web and tally-db, both linked to render.yaml. On the tally-web Environment page, DATABASE_URL shows as linked to tally-db, and ADMIN_TOKEN is set but hidden.

Step 5 · Watch the first deploy and test it

Open tally-web and its latest deploy's logs. The order of events tells you each part of the Blueprint worked:

  1. The build runs npm ci, using Node.js 26.13.1 from .node-version.
  2. The pre-deploy command prints migrate: visits table is ready.
  3. The app starts and logs tally listening on port 10000.
  4. The health check on /healthz passes and the deploy is marked live.

If the migration fails, the log shows the error and the deploy stops there. If /healthz never answers 200, Render cancels the deploy after 15 minutes. In both cases nothing replaces a version that was already live.

Copy the service's onrender.com address from the top of its page and request it twice. Replace the address with your own:

Bash
curl https://tally-web-xxxx.onrender.com/
curl https://tally-web-xxxx.onrender.com/

To call the admin route without putting the token in your shell history or the process list, read it into a variable and hand the header to curl on standard input:

Bash
read -rs ADMIN_TOKEN
printf 'header = "Authorization: Bearer %s"\n' "$ADMIN_TOKEN" | curl -sS --config - https://tally-web-xxxx.onrender.com/admin/count

Paste the token when read waits (nothing is shown) and press Enter.

Check it worked

The two plain requests print Tally: visit number 1 and Tally: visit number 2. The admin request prints Visits recorded: 2, or a higher number if the health check or you visited more. The same URL without the header prints Not found.

Step 6 · Turn on pull request previews

A preview environment is a full copy of the Blueprint, with its own web service and its own database, created for a pull request and deleted when the pull request closes. Previews need a Pro workspace, which Render's pricing page listed at $25 a month plus compute in November 2026, and preview resources are billed like any others, by the second. If your workspace is not on Pro, read this step and skip to the clean-up.

Add a previews block at the top of render.yaml, and give the database a preview plan, because a workspace can have only one free database and tally-db already uses it:

YAML
previews:
  generation: manual
  expireAfterDays: 3

Under tally-db, below plan: free, add:

YAML
    previewPlan: 0.1c-256mb

manual means Render builds a preview only when the pull request's title contains [render preview], so every small pull request does not start a paid copy. automatic builds one for every pull request. expireAfterDays: 3 deletes a preview after three days with no new pushes.

Push the change to main so the Blueprint syncs, then open a pull request to try it:

Bash
git add render.yaml
git commit -m "Enable manual pull request previews"
git push
git switch -c preview-test
git commit --allow-empty -m "Try a preview"
git push -u origin preview-test
gh pr create --title "[render preview] Try a preview" --body "Testing Render previews."

Check it worked

Within a few minutes the pull request on GitHub shows a link to the preview, and the Render dashboard lists a preview environment with its own copies of the service and database. The preview's / counts from visit number 1, because it has its own empty database. Its /admin/count returns Not found even with your header, because sync: false values are not copied into previews and ADMIN_TOKEN is unset there. To give previews a secret, put it in an environment group and reference the group.

Close the pull request with gh pr close preview-test --delete-branch and confirm the preview disappears from the dashboard.

Step 7 · Delete the Blueprint's resources

Removing a resource from render.yaml does not delete it, and deleting a resource by hand while the Blueprint still lists it makes Render recreate it on the next sync. So delete in this order.

Before you delete the database, take a copy of anything you want to keep. Render keeps no backups or snapshots of a deleted database. Back up and restore PostgreSQL with pg_dump shows how, using the database's external URL.

  1. Close any open preview pull requests, so their previews are removed.
  2. Disconnect the Blueprint from its settings page (something like Disconnect Blueprint). This stops syncing and keeps the resources, so they no longer come back after you delete them.
  3. Open tally-web, go to its settings and delete the service at the bottom of the page.
  4. Open tally-db, scroll to the bottom of its Info page and click Delete Database. Render asks you to confirm the name.

If you no longer need the GitHub repository, delete it too. The gh command needs the delete_repo scope, which gh auth refresh -s delete_repo adds:

Bash
gh repo delete tally-render-demo

Then remove the local folder with rm -rf ~/tally-render-demo.

Check it worked

The Render dashboard shows no tally-web, tally-db or preview environment, and the Blueprints list no longer shows tally. curl https://tally-web-xxxx.onrender.com/ (with your address) no longer returns a Tally response. Check your workspace's billing page the next day to confirm no charges for these resources are still accruing.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.