本示例演示了如何使用 Workers VPC 和 Hyperdrive 从 Worker 查询私有 PostgreSQL 数据库。该 Worker 会连接到未暴露在公共互联网上的数据库,并由 Hyperdrive 提供连接池和查询加速功能。
- 在您的私有网络中运行的 PostgreSQL 数据库(例如,在端口 5432 上)
- 一个连接到运行数据库的私有网络的 Cloudflare Tunnel
- 具有 Workers VPC 访问权限的 Cloudflare 账户
如果您在数据库所在的同一网络中尚未运行隧道,请创建一个。
-
转到 Workers VPC 仪表板 ↗,选择 Tunnels(隧道) 标签页。
-
选择 Create(创建) 以创建隧道。
-
输入隧道名称并选择 Save tunnel(保存隧道)。
-
选择您的操作系统和架构。仪表板将提供安装说明。
-
按照提供的命令下载、安装并使用您的唯一令牌运行
cloudflared。
该隧道必须能够从私有网络内部访问您的数据库主机和端口。有关完整的隧道文档,请参阅 Workers VPC 的 Cloudflare Tunnel。
创建一个指向您的数据库且类型为 tcp 的 VPC Service:
npx wrangler vpc service create my-postgres-db \
--type tcp \
--tcp-port 5432 \
--app-protocol postgresql \
--tunnel-id <YOUR_TUNNEL_ID> \
--ipv4 <YOUR_DATABASE_IP>将 <YOUR_TUNNEL_ID> 替换为步骤 1 中的隧道 ID,并将 <YOUR_DATABASE_IP> 替换为您数据库的私有 IP 地址(例如 10.0.0.5)。
该命令会返回一个服务 ID。保存此值供下一步使用。
使用 --service-id 标志将 Hyperdrive 指向您创建的 VPC Service:
npx wrangler hyperdrive create my-vpc-database \
--service-id <YOUR_VPC_SERVICE_ID> \
--database <DATABASE_NAME> \
--user <DATABASE_USER> \
--password <DATABASE_PASSWORD> \
--scheme postgresql将 <YOUR_VPC_SERVICE_ID> 替换为步骤 2 中的服务 ID,并提供您的数据库名称、用户和密码。
该命令会输出一个 Hyperdrive 配置 ID。复制此值供下一步使用。
你必须在 Wrangler 配置文件 中创建绑定,Worker 才能连接 Hyperdrive 配置。绑定(binding) 使 Worker 能够访问 Cloudflare 开发者平台上的资源(如 Hyperdrive)。
要将 Hyperdrive 配置绑定到 Worker,请在 Wrangler 文件末尾添加以下内容:
{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<YOUR_DATABASE_ID>" // the ID associated with the Hyperdrive you just created
}
]
}[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<YOUR_DATABASE_ID>"具体说明:
- 为
binding(绑定名称)设置的值(字符串)将在 Worker 中引用此数据库。本教程中将绑定命名为HYPERDRIVE。 - 绑定必须是有效的 JavaScript 变量名 ↗。例如
binding = "hyperdrive"或binding = "productionDB"均为有效名称。 - 绑定在 Worker 中可通过
env.<BINDING_NAME>访问。
若开发时使用本地数据库,可在 Hyperdrive 配置中添加 localConnectionString,填入数据库连接字符串:
{
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<YOUR_DATABASE_ID>", // the ID associated with the Hyperdrive you just created
"localConnectionString": "<LOCAL_DATABASE_CONNECTION_URI>"
}
]
}[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<YOUR_DATABASE_ID>"
localConnectionString = "<LOCAL_DATABASE_CONNECTION_URI>"安装 node-postgres 驱动:
npm i pg@>8.16.3yarn add pg@>8.16.3pnpm add pg@>8.16.3bun add pg@>8.16.3若使用 TypeScript,安装类型包:
npm i -D @types/pgyarn add -D @types/pgpnpm add -D @types/pgbun add -d @types/pg在 wrangler.jsonc 中添加所需的 Node.js 兼容性标志和 Hyperdrive 绑定:
在 wrangler.jsonc 中添加 Node.js 兼容性标志和 Hyperdrive 绑定(binding):
{
// required for database drivers to function
"compatibility_flags": [
"nodejs_compat"
],
// Set this to today's date
"compatibility_date": "2026-08-17",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}compatibility_flags = [ "nodejs_compat" ]
# Set this to today's date
compatibility_date = "2026-08-17"
[[hyperdrive]]
binding = "HYPERDRIVE"
id = "<your-hyperdrive-id-here>"创建新的 Client 实例并传入 Hyperdrive connectionString:
// filepath: src/index.ts
import { Client } from "pg";
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
// Create a new client instance for each request. Hyperdrive maintains the
// underlying database connection pool, so creating a new client is fast.
const client = new Client({
connectionString: env.HYPERDRIVE.connectionString,
});
try {
// Connect to the database
await client.connect();
// Perform a simple query
const result = await client.query("SELECT * FROM pg_tables");
return Response.json({
success: true,
result: result.rows,
});
} catch (error: any) {
console.error("Database error:", error.message);
return new Response("Internal error occurred", { status: 500 });
}
},
};部署您的 Worker:
npx wrangler deploy发送请求以验证连接:
curl https://<YOUR_WORKER>.<YOUR_SUBDOMAIN>.workers.dev成功的响应将从您的数据库返回行的 JSON 数组。
- 详细了解 Hyperdrive 工作原理
- 为 Hyperdrive 配置查询缓存
- 查看 VPC Service 配置选项,包括 TLS 证书验证
- 探索其他示例