DEV Community

Cover image for Hướng Dẫn Sử Dụng DigitalOcean API: Cloud Infrastructure Cho Lập Trình Viên
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

Hướng Dẫn Sử Dụng DigitalOcean API: Cloud Infrastructure Cho Lập Trình Viên

TL;DR

Các API của DigitalOcean quản lý Droplet, Volume, Tường lửa, Bộ cân bằng tải, cụm Kubernetes và nhiều tài nguyên khác. Xác thực bằng mã thông báo truy cập cá nhân, gọi api.digitalocean.com/v2, và chú ý đến giới hạn tốc độ. Để kiểm thử và tự động hóa hạ tầng, hãy sử dụng Apidog để cấu hình xác thực, kiểm tra việc cung cấp tài nguyên và lưu trữ các quy trình mẫu.

Dùng thử Apidog ngay hôm nay

Giới thiệu

DigitalOcean đơn giản hóa điện toán đám mây. So với AWS và GCP với hàng trăm dịch vụ, DigitalOcean tập trung vào các thành phần thiết yếu: điện toán (Droplets), lưu trữ (Volumes), mạng (Floating IPs, Firewalls), Kubernetes được quản lý và nền tảng ứng dụng. API của DigitalOcean cũng rất trực quan.

Các trường hợp sử dụng phổ biến của DigitalOcean API:

  • Tự động tạo môi trường phát triển
  • Quản lý cụm Kubernetes
  • Infrastructure as Code với Terraform hoặc Pulumi
  • Tích hợp vào pipeline CI/CD
  • Triển khai đa vùng

💡 Nếu bạn cần tự động hóa hạ tầng, Apidog giúp kiểm thử các API, lưu cấu hình hạ tầng thành mẫu tái sử dụng, và cộng tác với nhóm trong các quy trình cung cấp.

Xác thực

Mã thông báo truy cập cá nhân

  1. Truy cập DigitalOcean Dashboard → API → Generate New Token
  2. Đặt tên và thời hạn cho token
  3. Sao chép và lưu trữ token an toàn

Cách sử dụng mã thông báo với API:

curl -X GET "https://api.digitalocean.com/v2/account" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Định dạng phản hồi

{
  "account": {
    "droplet_limit": 25,
    "email": "you@example.com",
    "name": "Your Name",
    "uuid": "abc123xyz",
    "email_verified": true,
    "status": "active"
  }
}
Enter fullscreen mode Exit fullscreen mode

Droplet (máy ảo)

Liệt kê tất cả các Droplet

curl -X GET "https://api.digitalocean.com/v2/droplets" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Tạo một Droplet

curl -X POST "https://api.digitalocean.com/v2/droplets" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-droplet",
    "region": "nyc1",
    "size": "s-2vcpu-4gb",
    "image": "ubuntu-20-04-x64",
    "ssh_keys": ["ssh-rsa AAAA..."],
    "backups": false,
    "ipv6": true,
    "tags": ["web", "production"]
  }'
Enter fullscreen mode Exit fullscreen mode

Các kích thước phổ biến:

  • s-1vcpu-1gb — 1 vCPU, 1GB RAM (5$/tháng)
  • s-2vcpu-2gb — 2 vCPU, 2GB RAM (10$/tháng)
  • s-2vcpu-4gb — 2 vCPU, 4GB RAM (20$/tháng)
  • s-4vcpu-8gb — 4 vCPU, 8GB RAM (40$/tháng)

Các khu vực:

  • nyc1, nyc3 — New York
  • sfo3 — San Francisco
  • ams3 — Amsterdam
  • sgp1 — Singapore

Lấy chi tiết Droplet

curl -X GET "https://api.digitalocean.com/v2/droplets/DROPLET_ID" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Xóa một Droplet

curl -X DELETE "https://api.digitalocean.com/v2/droplets/DROPLET_ID" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Các hành động trên Droplet

Khởi động lại:

curl -X POST "https://api.digitalocean.com/v2/droplets/DROPLET_ID/actions" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "reboot"
  }'
Enter fullscreen mode Exit fullscreen mode

Thay đổi kích thước:

curl -X POST "https://api.digitalocean.com/v2/droplets/DROPLET_ID/actions" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "resize",
    "size": "s-4vcpu-8gb"
  }'
Enter fullscreen mode Exit fullscreen mode

Tạo ảnh chụp nhanh:

curl -X POST "https://api.digitalocean.com/v2/droplets/DROPLET_ID/actions" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "snapshot",
    "name": "my-snapshot"
  }'
Enter fullscreen mode Exit fullscreen mode

Volume (lưu trữ khối)

Tạo một Volume

curl -X POST "https://api.digitalocean.com/v2/volumes" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "size_gigabytes": 100,
    "name": "my-volume",
    "region": "nyc1",
    "description": "Data volume for web servers"
  }'
Enter fullscreen mode Exit fullscreen mode

Gắn Volume vào Droplet

curl -X POST "https://api.digitalocean.com/v2/volumes/VOLUME_ID/actions" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "attach",
    "droplet_id": DROPLET_ID
  }'
Enter fullscreen mode Exit fullscreen mode

Liệt kê các Volume

curl -X GET "https://api.digitalocean.com/v2/volumes" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Mạng

Liệt kê các IP Floating

curl -X GET "https://api.digitalocean.com/v2/floating_ips" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Gán IP Floating

curl -X POST "https://api.digitalocean.com/v2/floating_ips" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "droplet_id": DROPLET_ID,
    "region": "nyc1"
  }'
Enter fullscreen mode Exit fullscreen mode

Tạo tường lửa

curl -X POST "https://api.digitalocean.com/v2/firewalls" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "web-firewall",
    "inbound_rules": [
      {
        "protocol": "tcp",
        "ports": "80",
        "sources": {
          "addresses": ["0.0.0.0/0"]
        }
      },
      {
        "protocol": "tcp",
        "ports": "443",
        "sources": {
          "addresses": ["0.0.0.0/0"]
        }
      },
      {
        "protocol": "tcp",
        "ports": "22",
        "sources": {
          "addresses": ["your-ip/32"]
        }
      }
    ],
    "outbound_rules": [
      {
        "protocol": "tcp",
        "ports": "80",
        "destinations": {
          "addresses": ["0.0.0.0/0"]
        }
      }
    ],
    "droplet_ids": [DROPLET_ID]
  }'
Enter fullscreen mode Exit fullscreen mode

Bộ cân bằng tải

Tạo bộ cân bằng tải

curl -X POST "https://api.digitalocean.com/v2/load_balancers" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-lb",
    "region": "nyc1",
    "algorithm": "round_robin",
    "health_check": {
      "protocol": "http",
      "port": 80,
      "path": "/",
      "check_interval_seconds": 10,
      "response_timeout_seconds": 5,
      "healthy_threshold": 3,
      "unhealthy_threshold": 3
    },
    "forwarding_rules": [
      {
        "entry_protocol": "http",
        "entry_port": 80,
        "target_protocol": "http",
        "target_port": 80
      },
      {
        "entry_protocol": "https",
        "entry_port": 443,
        "target_protocol": "https",
        "target_port": 443,
        "tls_passthrough": true
      }
    ],
    "droplet_ids": [DROPLET_ID_1, DROPLET_ID_2]
  }'
Enter fullscreen mode Exit fullscreen mode

Cụm Kubernetes

Tạo một cụm Kubernetes

curl -X POST "https://api.digitalocean.com/v2/kubernetes/clusters" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-cluster",
    "region": "nyc1",
    "version": "1.28",
    "node_pools": [
      {
        "name": "worker-pool",
        "size": "s-2vcpu-4gb",
        "count": 3,
        "auto_scale": true,
        "min_nodes": 2,
        "max_nodes": 6
      }
    ]
  }'
Enter fullscreen mode Exit fullscreen mode

Liệt kê các nhóm node

curl -X GET "https://api.digitalocean.com/v2/kubernetes/clusters/CLUSTER_ID/node_pools" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Mở rộng nhóm node

curl -X PUT "https://api.digitalocean.com/v2/kubernetes/clusters/CLUSTER_ID/node_pools/POOL_ID" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "count": 5
  }'
Enter fullscreen mode Exit fullscreen mode

Xóa cụm Kubernetes

curl -X DELETE "https://api.digitalocean.com/v2/kubernetes/clusters/CLUSTER_ID" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Kiểm thử với Apidog

Việc cung cấp hạ tầng có thể tốn kém. Luôn kiểm tra kỹ trước khi tạo tài nguyên mới.

Apidog testing infrastructure

1. Thiết lập môi trường

DIGITALOCEAN_TOKEN: your_token
BASE_URL: https://api.digitalocean.com/v2
DEFAULT_REGION: nyc1
DEFAULT_SIZE: s-2vcpu-4gb
Enter fullscreen mode Exit fullscreen mode

2. Xác thực phản hồi

pm.test('Droplet created successfully', () => {
  const response = pm.response.json()
  pm.expect(response.droplet).to.have.property('id')
  pm.expect(response.droplet.status).to.eql('new')
})

pm.test('Token is valid', () => {
  const response = pm.response.json()
  pm.expect(response.account).to.exist
  pm.expect(response.account.status).to.eql('active')
})
Enter fullscreen mode Exit fullscreen mode

3. Kiểm tra đầu vào (Dry run)

DigitalOcean chưa hỗ trợ chạy thử thực sự, nhưng nên xác thực đầu vào trước khi gọi API:

const validRegions = ['nyc1', 'sfo3', 'ams3', 'sgp1']
const validSizes = ['s-1vcpu-1gb', 's-2vcpu-2gb', 's-2vcpu-4gb']

pm.test('Region is valid', () => {
  const requestBody = JSON.parse(pm.request.body.raw)
  pm.expect(validRegions).to.include(requestBody.region)
})

pm.test('Size is valid', () => {
  const requestBody = JSON.parse(pm.request.body.raw)
  pm.expect(validSizes).to.include(requestBody.size)
})
Enter fullscreen mode Exit fullscreen mode

Kiểm thử API hạ tầng DigitalOcean miễn phí bằng Apidog.

Các lỗi phổ biến và cách khắc phục

401 Không được phép

Nguyên nhân: Token không hợp lệ hoặc đã hết hạn.

Khắc phục: Tạo lại token từ dashboard, kiểm tra định dạng header Authorization.

422 Không thể xử lý thực thể

Nguyên nhân: Tham số không hợp lệ (khu vực, kích thước, image, ...).

Khắc phục: Đối chiếu tài liệu API DigitalOcean, kiểm tra các trường hợp:

  • Khu vực không hỗ trợ kích thước
  • ID image không tồn tại
  • Đã đạt giới hạn Droplet

429 Quá nhiều yêu cầu

Nguyên nhân: Vượt quá rate limit (mặc định 2000 req/giờ).

Khắc phục: Dùng backoff tự động:

async function doRequest(url, options, retries = 3) {
  for (let i = 0; i < retries; i++) {
    const response = await fetch(url, options)
    if (response.status === 429) {
      await sleep(Math.pow(2, i) * 1000)
      continue
    }
    return response
  }
  throw new Error('Rate limited')
}
Enter fullscreen mode Exit fullscreen mode

Đã đạt đến giới hạn Droplet

Nguyên nhân: Có quá nhiều Droplet trên tài khoản.

Khắc phục: Xóa Droplet không dùng hoặc liên hệ bộ phận hỗ trợ để tăng limit.

Các lựa chọn thay thế và so sánh

Tính năng DigitalOcean AWS GCP
Kích thước Droplet Cố định Tùy chỉnh Tùy chỉnh
Kubernetes DOKS được quản lý EKS GKE
Lưu trữ đối tượng Spaces S3 Cloud Storage
Lưu trữ khối Volumes EBS Persistent Disk
Bộ cân bằng tải Tích hợp sẵn ELB Cloud Load Balancing
Gói miễn phí 200$ tín dụng Có giới hạn 300$ tín dụng
Đơn giản API ★★★★★ ★★☆☆☆ ★★★☆☆

DigitalOcean nổi bật về sự đơn giản. API dễ hiểu, các thao tác không phức tạp, không cần xử lý nhiều dịch vụ lồng nhau.

Các trường hợp sử dụng thực tế

Môi trường phát triển tự động:

Startup có thể tạo môi trường phát triển riêng biệt cho mỗi nhánh. Mỗi Pull Request sẽ gọi API tạo một Droplet với mã mới. Khi merge, Droplet được hủy. Developer kiểm thử trên môi trường giống production mà không cần cài thủ công.

Web server tự động mở rộng:

Ứng dụng web theo dõi tải. Nếu CPU > 70%, API tạo thêm Droplet và thêm vào Load Balancer. Khi tải giảm, Droplet được xóa. Đảm bảo hiệu suất mà vẫn tối ưu chi phí.

Cụm cơ sở dữ liệu:

Dùng Volume làm primary/replica ở các khu vực khác nhau, API tự động cấu hình replication, lên lịch backup và thiết lập failover.

Kết luận

Các bước chính bạn có thể triển khai:

  • Xác thực API DigitalOcean với personal access token
  • Tạo/quản lý Droplet tự động qua API
  • Làm việc với Volume để lưu trữ dữ liệu liên tục
  • Cấu hình tường lửa, load balancer cho bảo mật và mở rộng
  • Quản lý cụm Kubernetes dễ dàng
  • Kiểm thử hạ tầng trước khi cung cấp bằng Apidog

FAQ

Một Droplet có giá bao nhiêu?

Bắt đầu từ 5$/tháng cho 1 vCPU/1GB RAM. Xem trang giá để cập nhật mới nhất. Có tính theo giờ.

Có thể dùng SSH key khi tạo Droplet qua API không?

Có, đưa fingerprint của SSH key vào mảng ssh_keys khi tạo Droplet.

Phân biệt Volume và Spaces?

Volume là lưu trữ block (gắn vào Droplet). Spaces là lưu trữ object (giống S3). Volume cho database, Spaces cho file.

Lấy cấu hình Kubernetes như thế nào?

curl -X GET "https://api.digitalocean.com/v2/kubernetes/clusters/CLUSTER_ID/kubeconfig" \
  -H "Authorization: Bearer YOUR_TOKEN"
Enter fullscreen mode Exit fullscreen mode

Có thể thay đổi kích thước Droplet không?

Có, dùng API action resize. Downsize cần tắt máy, upscale thì không.

Backups vs Snapshots?

Backups là bản sao tự động hàng ngày/tuần do DigitalOcean quản lý. Snapshots là bản sao thủ công do bạn tạo.

Tạo Droplet mất bao lâu?

Khoảng 30-60 giây, tùy khu vực và kích thước.

Terraform có hỗ trợ DigitalOcean không?

Có, DigitalOcean có provider chính thức cho Terraform, rất phù hợp cho IaC (Infrastructure as Code).

Top comments (0)