📑 Mục lục
Workers VPC Là Gì?
Cloudflare Workers VPC là một tính năng cho phép bạn kết nối Cloudflare Workers với các API và dịch vụ private trong các đám mây bên ngoài (AWS, Azure, GCP, on-premise...) mà không cần expose ra Internet công cộng.
📢 Lưu ý: Workers VPC hiện đang ở giai đoạn Beta. Các tính năng và API có thể thay đổi trước khi phát hành chính thức. Trong thời gian beta, Workers VPC được cung cấp miễn phí cho tất cả các gói Workers.
Vấn đề mà Workers VPC giải quyết
Thông thường, khi bạn deploy một Cloudflare Worker, nó chỉ có thể truy cập các API public trên Internet. Nhưng trong thực tế, doanh nghiệp có rất nhiều dịch vụ nội bộ:
- 🔐 Authentication services - Hệ thống xác thực nội bộ
- 📊 Internal APIs - API nội bộ không public
- 🗄️ Databases - Database trong private subnet
- 📝 CMS systems - Hệ thống quản lý nội dung
- 🏢 Legacy systems - Các hệ thống cũ on-premise
Workers VPC cho phép Workers truy cập tất cả các dịch vụ này một cách an toàn thông qua Cloudflare Tunnel.
Kiến Trúc Hoạt Động
Luồng kết nối Workers VPC
(AWS/GCP/Azure/On-prem)
Workers VPC hoạt động dựa trên 3 thành phần chính:
- Cloudflare Tunnel: Tạo kết nối an toàn từ private network của bạn đến Cloudflare mà không cần mở port hay cấu hình firewall phức tạp.
- VPC Service: Định nghĩa mỗi service trong private network mà bạn muốn Workers truy cập.
- VPC Service Binding: Gắn VPC Service vào Worker để code có thể gọi đến private service.
Các Trường Hợp Sử Dụng
🔌 Truy cập Private APIs
Deploy ứng dụng Workers kết nối với các dịch vụ xác thực, CMS, internal APIs. Workers chạy globally với optimized access đến backend services.
🚪 API Gateway
Routing requests đến các microservices nội bộ dựa trên URL path. Tập trung access control và load balancing cho nhiều private services.
📊 Internal Dashboards
Xây dựng các ứng dụng nội bộ cho nhân viên, admin panels, dashboards tổng hợp dữ liệu từ nhiều private services mà không expose backend.
🤖 MCP Servers & Agents
Xây dựng AI agents và MCP servers cần truy cập dữ liệu nội bộ công ty một cách an toàn từ edge.
Hướng Dẫn Cài Đặt
-
Cài đặt Cloudflare Tunnel
Đầu tiên, bạn cần cài đặt
cloudflaredtrên server trong private network:Terminal# Cài đặt cloudflared trên Ubuntu/Debian curl -L --output cloudflared.deb https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb sudo dpkg -i cloudflared.deb # Đăng nhập và tạo tunnel cloudflared tunnel login cloudflared tunnel create my-private-tunnel
-
Cấu hình Tunnel để route traffic
Tạo file cấu hình cho tunnel:
~/.cloudflared/config.ymltunnel: my-private-tunnel credentials-file: /root/.cloudflared/xxxxxxxx.json ingress: # Route traffic đến internal API - hostname: internal-api.company.local service: http://localhost:8080 # Route traffic đến internal database API - hostname: db-api.company.local service: http://localhost:5000 # Catch-all rule (bắt buộc) - service: http_status:404
-
Chạy Tunnel
Terminal
# Chạy tunnel cloudflared tunnel run my-private-tunnel # Hoặc chạy như service (recommended for production) sudo cloudflared service install sudo systemctl start cloudflared
-
Tạo VPC Service trong Cloudflare Dashboard
Vào Cloudflare Dashboard → Workers & Pages → VPC Services → Create Service. Nhập thông tin tunnel và hostname của service.
-
Cấu hình Worker với VPC Service Binding
Thêm binding vào file wrangler config:
wrangler.jsonc{ "$schema": "node_modules/wrangler/config-schema.json", "name": "my-worker", "main": "src/index.ts", "compatibility_date": "2025-02-04", // Cấu hình VPC Service bindings "vpc_services": [ { "binding": "PRIVATE_API", // Tên biến trong code "service_id": "YOUR_SERVICE_ID", // ID từ Dashboard "remote": true } ] }
Ví Dụ Code
Basic: Gọi Private API
export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { // Gọi đến private API thông qua VPC Service binding const response = await env.PRIVATE_API.fetch( "http://internal-api.company.local/users" ); // Xử lý response từ private network const data = await response.json(); return new Response(JSON.stringify(data), { headers: { "content-type": "application/json" }, }); }, };
Advanced: API Gateway Pattern
interface Env { USERS_API: Fetcher; ORDERS_API: Fetcher; ANALYTICS_API: Fetcher; } export default { async fetch(request: Request, env: Env, ctx: ExecutionContext) { const url = new URL(request.url); const path = url.pathname; // Route requests đến các private services khác nhau let response: Response; if (path.startsWith("/api/users")) { // Forward đến Users microservice response = await env.USERS_API.fetch( "http://users.internal:3000" + path.replace("/api/users", ""), request ); } else if (path.startsWith("/api/orders")) { // Forward đến Orders microservice response = await env.ORDERS_API.fetch( "http://orders.internal:3001" + path.replace("/api/orders", ""), request ); } else if (path.startsWith("/api/analytics")) { // Forward đến Analytics microservice response = await env.ANALYTICS_API.fetch( "http://analytics.internal:3002" + path.replace("/api/analytics", ""), request ); } else { response = new Response("Not Found", { status: 404 }); } return response; }, };
Best Practices
🔒 Bảo mật
- Không expose tunnel credentials: Luôn giữ tunnel credentials an toàn, không commit vào git.
- Sử dụng Access policies: Kết hợp với Cloudflare Access để kiểm soát ai có thể truy cập các private services.
- Audit logging: Enable logging để theo dõi tất cả requests đến private network.
⚡ Performance
- Cache responses: Sử dụng Cache API để cache responses từ private APIs khi có thể.
- Connection pooling: Tunnel tự động manage connection pooling, nhưng hãy đảm bảo backend có thể handle concurrent connections.
- Timeout handling: Luôn set timeout cho requests đến private services.
const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); try { const response = await env.PRIVATE_API.fetch(url, { signal: controller.signal }); clearTimeout(timeoutId); return response; } catch (err) { if (err.name === 'AbortError') { return new Response('Request timeout', { status: 504 }); } throw err; }
🔄 High Availability
- Multiple tunnels: Chạy nhiều tunnel replicas để đảm bảo availability.
- Health checks: Configure health checks cho tunnel để auto-failover.
- Error handling: Implement retry logic và fallback mechanisms.
💡 Pro Tip: Workers VPC đặc biệt hữu ích khi bạn cần build các ứng dụng edge nhưng backend nằm trong private cloud. Thay vì expose APIs ra public internet, bạn giữ mọi thứ trong private network và chỉ cho Workers truy cập thông qua secure tunnel.
So Sánh Với Các Giải Pháp Khác
| Tiêu chí | Workers VPC | VPN | Public API + Auth |
|---|---|---|---|
| Setup complexity | Thấp | Cao | Trung bình |
| Security | ✅ Zero Trust | ✅ Encrypted | ⚠️ Exposed |
| Cần open port | ❌ Không | ✅ Có | ✅ Có |
| Global edge access | ✅ Có | ❌ Không | ✅ Có |
Kết Luận
Cloudflare Workers VPC là giải pháp mạnh mẽ cho các doanh nghiệp muốn leverage edge computing của Workers mà vẫn giữ backend services an toàn trong private network. Với kiến trúc Zero Trust và không cần mở port, đây là lựa chọn lý tưởng cho các use cases như:
- API Gateway cho microservices nội bộ
- Edge applications truy cập legacy systems
- Internal dashboards và admin tools
- AI agents cần access dữ liệu công ty