Skip to content

Connect to a private database using Tunnel

Hyperdrive can securely connect to your private databases using Cloudflare Tunnel and Cloudflare Access.

How it works

When your database is isolated within a private network (such as a virtual private cloud or an on-premise network), you must enable a secure connection from your network to Cloudflare.

  • Cloudflare Tunnel is used to establish the secure tunnel connection.
  • Cloudflare Access is used to restrict access to your tunnel such that only specific Hyperdrive configurations can access it.

A request from the Cloudflare Worker to the origin database goes through Hyperdrive, Cloudflare Access, and the Cloudflare Tunnel established by cloudflared. cloudflared must be running in the private network in which your database is accessible.

The Cloudflare Tunnel will establish an outbound bidirectional connection from your private network to Cloudflare. Cloudflare Access will secure your Cloudflare Tunnel to be only accessible by your Hyperdrive configuration.

A request from the Cloudflare Worker to the origin database goes through Hyperdrive, Cloudflare Access and the Cloudflare Tunnel established by cloudflared.

Before you start

All of the tutorials assume you have already completed the Get started guide, which gets you set up with a Cloudflare Workers account, C3, and Wrangler.

Prerequisites

  • A database in your private network, configured to use TLS/SSL.
  • A hostname on your Cloudflare account, which will be used to route requests to your database.

1. Create a tunnel in your private network

1.1. Create a tunnel

First, create a Cloudflare Tunnel in your private network to establish a secure connection between your network and Cloudflare. Your network must be configured such that the tunnel has permissions to egress to the Cloudflare network and access the database within your network.

  1. Log in to Zero Trust and go to Networks > Tunnels.

  2. Select Create a tunnel.

  3. Choose Cloudflared for the connector type and select Next.

  4. Enter a name for your tunnel. We suggest choosing a name that reflects the type of resources you want to connect through this tunnel (for example, enterprise-VPC-01).

  5. Select Save tunnel.

  6. Next, you will need to install cloudflared and run it. To do so, check that the environment under Choose an environment reflects the operating system on your machine, then copy the command in the box below and paste it into a terminal window. Run the command.

  7. Once the command has finished running, your connector will appear in Zero Trust.

    Connector appearing in the UI after cloudflared has run

  8. Select Next.

1.2. Connect your database using a public hostname

Your tunnel must be configured to use a public hostname so that Hyperdrive can route requests to it. If you don't have a hostname on Cloudflare yet, you will need to register a new hostname or add a zone to Cloudflare to proceed.

  1. In the Public Hostnames tab, choose a Domain and specify any subdomain or path information. This will be used in your Hyperdrive configuration to route to this tunnel.

  2. In the Service section, specify Type TCP and the URL and configured port of your database, such as localhost:5432 or my-database-host.database-provider.com:5432. This address will be used by the tunnel to route requests to your database.

  3. Select Save tunnel.

2. Create and configure Hyperdrive to connect to the Cloudflare Tunnel

To restrict access to the Cloudflare Tunnel to Hyperdrive, a Cloudflare Access application must be configured with a Policy that requires requests to contain a valid Service Auth token.

The Cloudflare dashboard can automatically create and configure the underlying Cloudflare Access application, Service Auth token, and Policy on your behalf. Alternatively, you can manually create the Access application and configure the Policies.

2.1 Create a Hyperdrive configuration in the Cloudflare dashboard

Create a Hyperdrive configuration in the Cloudflare dashboard to automatically configure Hyperdrive to connect to your Cloudflare Tunnel.

  1. In the Cloudflare dashboard, navigate to Storage & Databases > Hyperdrive and click Create configuration.
  2. Select Private database.
  3. In the Networking details section, select the tunnel you are connecting to.
  4. In the Networking details section, select the hostname associated to the tunnel. If there is no hostname for your database, return to step 1.2. Connect your database using a public hostname.
  5. In the Access Service Authentication Token section, select Create new (automatic).
  6. In the Access Application section, select Create new (automatic).
  7. In the Database connection details section, enter the database name, user, and password.

3. Query your Hyperdrive configuration from a Worker (optional)

To test your Hyperdrive configuration to the database using Cloudflare Tunnel and Access, use the Hyperdrive configuration ID in your Worker and deploy it.

Create a Hyperdrive binding

You must create a binding for your Worker to connect to your Hyperdrive configuration. Bindings allow your Workers to access resources, like D1, on the Cloudflare developer platform. You create bindings by updating your Wrangler file.

To bind your Hyperdrive configuration to your Worker, add the following to the end of your Wrangler file:

[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<YOUR_DATABASE_ID>" # the ID associated with the Hyperdrive you just created

Specifically:

  • The value (string) you set for the name (binding name) will be used to reference this database in your Worker. In this tutorial, name your binding HYPERDRIVE.
  • The binding must be a valid JavaScript variable name. For example, binding = "hyperdrive" or binding = "productionDB" would both be valid names for the binding.
  • Your binding is available in your Worker at env.<BINDING_NAME>.

Query your database using Postgres.js

Use Postgres.js to send a test query to validate that the connection has been successful.

Install the Postgres.js driver:

Terminal window
npm install postgres

Create a new sql instance and pass the Hyperdrive parameters:

import postgres from "postgres";
export interface Env {
// If you set another name in the `wrangler.toml / wrangler.json` file as the value for 'binding',
// replace "HYPERDRIVE" with the variable name you defined.
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
// NOTE: if `prepare: false` is passed when connecting, performance will
// be slower but still correctly supported.
const sql = postgres(env.HYPERDRIVE.connectionString);
try {
// A very simple test query
const result = await sql`select * from pg_tables LIMIT 10`;
// Clean up the client, ensuring we don't kill the worker before that is
// completed.
ctx.waitUntil(sql.end());
// Return result rows as JSON
return Response.json({ result: result });
} catch (e) {
console.log(e);
return Response.json({ error: e.message }, { status: 500 });
}
},
} satisfies ExportedHandler<Env>;

Now, deploy your Worker:

Terminal window
npx wrangler deploy

If you successfully receive the list of pg_tables from your database when you access your deployed Worker, your Hyperdrive has now been configured to securely connect to a private database using Cloudflare Tunnel and Cloudflare Access.

Troubleshooting

If you encounter issues when setting up your Hyperdrive configuration with tunnels to a private database, consider these common solutions, in addition to general troubleshooting steps for Hyperdrive:

  • Ensure your database is configured to use TLS (SSL). Hyperdrive requires TLS (SSL) to connect.