Cloudflare Hyperdrive Docker PostgreSQL

In the modern landscape of distributed application development, edge computing has become a dominant paradigm. Cloudflare Workers, in particular, have gained massive traction due to their global deployment capabilities and ultra-low latency. However, a significant architectural challenge arises when these edge functions need to interact with traditional relational databases.

Because Cloudflare Workers are ephemeral and stateless, they are not designed to maintain long-lived TCP connections. When a high volume of edge requests hits a standard PostgreSQL instance—such as one running in a Docker container—the database often suffers from "connection exhaustion" and significant network latency overhead.

Cloudflare Hyperdrive solves this exact problem. By acting as an intelligent connection pooler and a global caching layer, Hyperdrive bridges the gap between the ephemeral edge and your persistent data layer. This guide provides a complete, end-to-end solution for connecting Cloudflare Hyperdrive to a PostgreSQL database running in Docker.
Before diving into the implementation, ensure you have the following ready:

  • A Cloudflare account with access to Workers and Hyperdrive.
  • Wrangler CLI installed on your local machine.
  • A server running Docker (this can be a local machine or a cloud VPS).
  • A PostgreSQL instance that is accessible via a public IP or through a secure tunnel.

Architecture Overview:
Cloudflare Worker $\rightarrow$ Cloudflare Hyperdrive $\rightarrow$ Network/Tunnel $\rightarrow$ Docker PostgreSQL


Step 1: Deploying PostgreSQL via Docker

The first step is to get your database up and running. For this demonstration, we will use a standard PostgreSQL Docker image.

Run the following command to launch a containerized PostgreSQL instance:

docker run --name pg-server \
  -e POSTGRES_USER=myuser \
  -e POSTGRES_PASSWORD=mypassword \
  -e POSTGRES_DB=mydb \
  -p 5432:5432 \
  -d postgres:15-alpine

Important Security Note: In this example, we are mapping port 5432 directly to the host. While this works for testing, it is not recommended for production. Exposing your database port to the public internet increases your attack surface. For production environments, you should use Cloudflare Tunnel (cloudflared) to create a secure, private connection between your Docker host and the Cloudflare network.


Step 2: Configuring Cloudflare Hyperdrive

Once your database is live, you need to tell Hyperdrive how to find it. Hyperdrive requires a standard PostgreSQL connection string to manage the pooling logic.

We will use the Wrangler CLI to create the Hyperdrive configuration. Navigate to your project root and execute:

npx wrangler hyperdrive create my-postgres-db --connection-string="postgres://myuser:mypassword@<YOUR_DOCKER_HOST_IP>:5432/mydb"

Replace <YOUR_DOCKER_HOST_IP> with the actual IP address of your Docker host.

After the command completes, the terminal will output a unique Hyperdrive ID. You must bind this ID to your Cloudflare Worker so it can be accessed in your code. Open your wrangler.toml file and add the following configuration:

[hyperdrive]
"MY_DB" = { id = "<YOUR_HYPERDRIVE_ID>" }

In this setup, MY_DB serves as the environment variable name that your Worker will use to interact with the Hyperdrive connection pool.


Step 3: Implementing the Connection in a Cloudflare Worker

Now that the infrastructure is configured, it is time to write the application logic. Since Cloudflare Workers run on the V8 engine (not Node.js), you must use a PostgreSQL client that is compatible with edge environments. The postgres library is an excellent choice for this.

First, install the necessary driver in your project:

npm install postgres

Next, implement the database logic in your Worker entry point (e.g., src/index.ts). The key advantage here is that instead of using a direct database URL, you use the connectionString provided by the Hyperdrive binding.

import { Client } from 'postgres';

export interface Env {
  // This matches the key defined in wrangler.toml
  MY_DB: Hyperdrive;
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    try {
      // Initialize the client using the Hyperdrive connection string
      // Hyperdrive handles the pooling and connection management behind the scenes
      const sql = new Client({ 
        connectionString: env.MY_DB.connectionString 
      });
      
      await sql.connect();

      // Execute a test query to verify the connection
      const { rows } = await sql.query('SELECT NOW() as current_time;');
      
      // Close the connection (Hyperdrive will manage the actual pool)
      await sql.end();

      return new Response(JSON.stringify({
        success: true,
        serverTime: rows[0].current_time
      }), {
        headers: { 'Content-Type': 'application/json' }
      });

    } catch (err: any) {
      return new Response(JSON.stringify({
        success: false,
        error: err.message
      }), {
        status: 500,
        headers: { 'Content-Type': 'application/json' }
      });
    }
  },
};

Step 4: Local Testing and Deployment

Before pushing your code to the global edge, you should validate the setup locally.

Local Development

Wrangler provides a local simulation environment. Run the following command:

npx wrangler dev

Wrangler will attempt to connect to your remote Hyperdrive instance, which in turn connects to your Dockerized PostgreSQL. Open your browser and navigate to http://localhost:8787. If you see a JSON response containing the current database time, your connection is successful.

Production Deployment

Once you have verified that everything works as expected, deploy your Worker to Cloudflare's global network:

npx wrangler deploy

Your application is now live at the edge, benefiting from Hyperdrive's connection pooling and reduced latency.


Summary

By integrating Cloudflare Hyperdrive with a Dockerized PostgreSQL instance, you effectively eliminate the two biggest hurdles of edge-to-database communication: TCP connection overhead and high latency.

Hyperdrive allows your ephemeral Workers to behave as if they are connected to a local, high-performance database, while your actual data remains securely hosted on your own infrastructure. For a production-ready setup, always pair this architecture with Cloudflare Tunnel to ensure that your database remains invisible to the public internet while staying highly accessible to your edge functions.