digitalocean Best Practices
This guide outlines the definitive best practices for developing and deploying applications on DigitalOcean. Adhering to these rules ensures your projects are secure, performant, scalable, and maintainable, leveraging DigitalOcean's managed services and cloud-native patterns.
1. VPC-Centric Networking (Security & Simplicity)
ALWAYS isolate your infrastructure within Virtual Private Clouds (VPCs). This is the cornerstone of secure and efficient communication between your services. Connect all compute resources (Droplets, Kubernetes nodes, Functions) and managed services (Databases) within the same VPC.
Connect Managed Databases via VPC: Use the private connection string and add the VPC's CIDR block as the only trusted source. This drastically reduces the attack surface and simplifies IP management.
❌ BAD: Public database connections, individual IP trusted sources.
-- Public connection string, exposed to the internet
psql "postgresql://doadmin:PASSWORD@db-public-endpoint.db.ondigitalocean.com:25060/defaultdb?sslmode=require"
✅ GOOD: Private VPC connection, CIDR block trusted source.
-- Private connection string, only accessible within the VPC
psql "postgresql://doadmin:PASSWORD@db-private-endpoint.db.ondigitalocean.com:25060/defaultdb?sslmode=require"
Configuration: In DigitalOcean Control Panel, for your database, add your VPC's CIDR (e.g., 10.108.0.0/20) to Trusted Sources.
All Compute in VPC: Ensure all Droplets, Kubernetes nodes, and Functions are launched within the same VPC as your managed services.
2. Microservices-First Architecture
Embrace a microservices architecture for agility, scalability, and resilience. DigitalOcean provides excellent platforms for this.
Managed Kubernetes (DOKS) for Orchestration: For complex, containerized applications requiring fine-grained control and high availability.
App Platform for Rapid CI/CD: For web apps, APIs, and static sites needing fast, automated deployments with integrated CI/CD. Ideal for AI-assisted development workflows (e.g., with Claude Code).
Premium CPU-Optimized Droplets: For high-performance, resource-intensive workloads that benefit from dedicated CPU.
❌ BAD: Monolithic application on a single Droplet.
# Dockerfile for a large, multi-service monolith
FROM node:18-alpine
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 8080 5432 # Exposing database directly from app container
CMD ["npm", "start"]
✅ GOOD: Decoupled services, deployed to appropriate platforms.
# Dockerfile for a single microservice (e.g., API)
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
RUN npm run build # If applicable
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist # Or similar for compiled assets
EXPOSE 8080
CMD ["node", "dist/index.js"] # Or your main entry point
Deployment: Deploy the API to App Platform or DOKS, use a Managed PostgreSQL database.
3. Leverage Managed Services
ALWAYS prefer DigitalOcean's managed services over self-hosting when available. They provide automated backups, failover, scaling, and security patching, reducing operational overhead.
Managed Databases: Use PostgreSQL, MySQL, Redis, or MongoDB.
Spaces (Object Storage): For static assets, backups, and media files. Integrate with CDN for performance.
Container Registry: Store private Docker images securely.
Load Balancers: Distribute traffic and provide SSL termination.
❌ BAD: Self-hosting PostgreSQL on a Droplet.
# Manual setup, no automated failover or backups
sudo apt update && sudo apt install postgresql postgresql-contrib
# ... manual configuration, backup scripts, monitoring, etc.
✅ GOOD: Provision a Managed PostgreSQL Database.
resource "digitalocean_database_cluster" "primary_db" {
name = "my-app-db"
engine = "pg"
version = "15"
size = "db-s-2vcpu-4gb"
region = "nyc3"
node_count = 1 # Start with 1, add standby nodes for HA
vpc_uuid = digitalocean_vpc.main.id # Ensure VPC is defined
}
4. Disciplined Container Builds
Follow Docker's best practices to create small, secure, and efficient container images.
Multi-stage Builds: Separate build-time dependencies from runtime dependencies.
Minimal Base Images: Use alpine variants or other minimal images.
Trusted Base Images: Prefer Docker Official Images or Verified Publisher images.
.dockerignore: Exclude unnecessary files from the build context.
Rebuild Images Often: Ensure dependencies are up-to-date with security patches.
❌ BAD: Single-stage build with development tools, no .dockerignore.
FROM node:18 # Large base image
WORKDIR /app
COPY . . # Copies everything, including .git, node_modules (if present)
RUN npm install # Installs dev dependencies too
CMD ["npm", "start"]
✅ GOOD: Multi-stage build, minimal base, .dockerignore in place.
# .dockerignore example:
# node_modules
# .git
# .env
# Dockerfile
# README.md
# Build stage
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev # Only install production dependencies
COPY . .
RUN npm run build # Compile application if needed
# Production stage
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist # Copy compiled app
EXPOSE 8080
CMD ["node", "dist/index.js"]
5. Automated Workflows (CI/CD & IaC)
Automate everything possible. This reduces human error, increases deployment speed, and ensures consistency.
CI/CD Pipelines: Use DigitalOcean App Platform's built-in CI/CD or integrate with GitHub Actions for DOKS deployments.
Infrastructure as Code (IaC): Manage all DigitalOcean resources with Terraform. This ensures your infrastructure is version-controlled, reproducible, and auditable.
❌ BAD: Manual resource creation via Control Panel.
# Click-ops in the UI
# Create Droplet -> Add Database -> Configure Load Balancer...
✅ GOOD: Define infrastructure with Terraform.
# main.tf
resource "digitalocean_project" "my_project" {
name = "My Awesome Project"
description = "Infrastructure for my awesome app."
purpose = "Web Application"
}
resource "digitalocean_vpc" "main" {
name = "my-app-vpc"
region = "nyc3"
ip_range = "10.10.0.0/20"
}
resource "digitalocean_kubernetes_cluster" "main_cluster" {
name = "my-app-cluster"
region = "nyc3"
version = "1.28.2-do.0"
vpc_uuid = digitalocean_vpc.main.id
node_pool {
name = "worker-pool"
size = "s-2vcpu-4gb"
node_count = 2
}
}
6. Performance & Cost Optimization
Continuously monitor and optimize your resources.
Autoscaling: Implement autoscaling for Droplet pools and Kubernetes node pools to match demand and save costs.
Load Balancers: Use DigitalOcean Load Balancers to distribute traffic and handle SSL.
Regular Architecture Reviews: Leverage DigitalOcean's free Solutions Engineer reviews to identify inefficiencies and security gaps.
Monitor Usage & Set Alerts: Track CPU, memory, disk I/O, network traffic, and billing.
❌ BAD: Over-provisioned Droplets running at low utilization.
# Manually scaled up to a large Droplet "just in case"
digitalocean droplet create --size s-8vcpu-16gb --image ubuntu-22-04 --region nyc3 --name my-server
✅ GOOD: Use autoscaling groups or right-sized resources.
resource "digitalocean_kubernetes_node_pool" "autoscaling_pool" {
cluster_id = digitalocean_kubernetes_cluster.main_cluster.id
name = "autoscaled-workers"
size = "s-2vcpu-4gb"
min_nodes = 1
max_nodes = 5
auto_scale = true
}
7. Testing & Observability
Integrate testing into your CI/CD and ensure robust monitoring.
Automated Testing: Include unit, integration, and end-to-end tests in your CI pipeline.
Staging Environments: Deploy to dedicated staging environments (e.g., via App Platform's branch deployments) before production.
Logging & Monitoring: Centralize logs and use DigitalOcean Monitoring for metrics and alerts.
❌ BAD: Manual testing only, no dedicated staging environment.
# Deploy directly to production after local testing
git push origin main # Triggers production deploy
✅ GOOD: Automated tests, staging environment, and feature branches.
# .github/workflows/ci-cd.yml (simplified)
name: CI/CD Pipeline
on:
push:
branches:
- main
- feature/*
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker Image
run: docker build -t my-app:${{ github.sha }} .
- name: Run Unit Tests
run: docker run my-app:${{ github.sha }} npm test
deploy-staging:
needs: build-and-test
if: startsWith(github.ref, 'refs/heads/feature/')
runs-on: ubuntu-latest
steps:
# ... deploy to App Platform staging environment
- name: Deploy to App Platform Staging
run: doctl apps create-deployment --app-id ${{ secrets.APP_PLATFORM_STAGING_ID }} --image my-app:${{ github.sha }}
deploy-production:
needs: build-and-test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
# ... deploy to App Platform production environment
- name: Deploy to App Platform Production
run: doctl apps create-deployment --app-id ${{ secrets.APP_PLATFORM_PROD_ID }} --image my-app:${{ github.sha }}
1---2name: digitalocean3description: [Applies to: **/*] Definitive guidelines for building, deploying, and managing cloud-native applications on DigitalOcean, focusing on secure, scalable, and cost-efficient practices.4---56# digitalocean Best Practices78This guide outlines the definitive best practices for developing and deploying applications on DigitalOcean. Adhering to these rules ensures your projects are secure, performant, scalable, and maintainable, leveraging DigitalOcean's managed services and cloud-native patterns.910## 1. VPC-Centric Networking (Security & Simplicity)1112**ALWAYS** isolate your infrastructure within Virtual Private Clouds (VPCs). This is the cornerstone of secure and efficient communication between your services. Connect all compute resources (Droplets, Kubernetes nodes, Functions) and managed services (Databases) within the same VPC.1314* **Connect Managed Databases via VPC**: Use the private connection string and add the VPC's CIDR block as the *only* trusted source. This drastically reduces the attack surface and simplifies IP management.1516 ❌ BAD: Public database connections, individual IP trusted sources.17 ```sql18 -- Public connection string, exposed to the internet19 psql "postgresql://doadmin:PASSWORD@db-public-endpoint.db.ondigitalocean.com:25060/defaultdb?sslmode=require"20 ```2122 ✅ GOOD: Private VPC connection, CIDR block trusted source.23 ```sql24 -- Private connection string, only accessible within the VPC25 psql "postgresql://doadmin:PASSWORD@db-private-endpoint.db.ondigitalocean.com:25060/defaultdb?sslmode=require"26 ```27 *Configuration*: In DigitalOcean Control Panel, for your database, add your VPC's CIDR (e.g., `10.108.0.0/20`) to Trusted Sources.2829* **All Compute in VPC**: Ensure all Droplets, Kubernetes nodes, and Functions are launched within the same VPC as your managed services.3031## 2. Microservices-First Architecture3233Embrace a microservices architecture for agility, scalability, and resilience. DigitalOcean provides excellent platforms for this.3435* **Managed Kubernetes (DOKS) for Orchestration**: For complex, containerized applications requiring fine-grained control and high availability.36* **App Platform for Rapid CI/CD**: For web apps, APIs, and static sites needing fast, automated deployments with integrated CI/CD. Ideal for AI-assisted development workflows (e.g., with Claude Code).37* **Premium CPU-Optimized Droplets**: For high-performance, resource-intensive workloads that benefit from dedicated CPU.3839 ❌ BAD: Monolithic application on a single Droplet.40 ```dockerfile41 # Dockerfile for a large, multi-service monolith42 FROM node:18-alpine43 WORKDIR /app44 COPY . .45 RUN npm install46 EXPOSE 8080 5432 # Exposing database directly from app container47 CMD ["npm", "start"]48 ```4950 ✅ GOOD: Decoupled services, deployed to appropriate platforms.51 ```dockerfile52 # Dockerfile for a single microservice (e.g., API)53 FROM node:20-alpine AS builder54 WORKDIR /app55 COPY package*.json ./56 RUN npm install --production57 COPY . .58 RUN npm run build # If applicable5960 FROM node:20-alpine61 WORKDIR /app62 COPY --from=builder /app/node_modules ./node_modules63 COPY --from=builder /app/dist ./dist # Or similar for compiled assets64 EXPOSE 808065 CMD ["node", "dist/index.js"] # Or your main entry point66 ```67 *Deployment*: Deploy the API to App Platform or DOKS, use a Managed PostgreSQL database.6869## 3. Leverage Managed Services7071**ALWAYS** prefer DigitalOcean's managed services over self-hosting when available. They provide automated backups, failover, scaling, and security patching, reducing operational overhead.7273* **Managed Databases**: Use PostgreSQL, MySQL, Redis, or MongoDB.74* **Spaces (Object Storage)**: For static assets, backups, and media files. Integrate with CDN for performance.75* **Container Registry**: Store private Docker images securely.76* **Load Balancers**: Distribute traffic and provide SSL termination.7778 ❌ BAD: Self-hosting PostgreSQL on a Droplet.79 ```bash80 # Manual setup, no automated failover or backups81 sudo apt update && sudo apt install postgresql postgresql-contrib82 # ... manual configuration, backup scripts, monitoring, etc.83 ```8485 ✅ GOOD: Provision a Managed PostgreSQL Database.86 ```terraform87 resource "digitalocean_database_cluster" "primary_db" {88 name = "my-app-db"89 engine = "pg"90 version = "15"91 size = "db-s-2vcpu-4gb"92 region = "nyc3"93 node_count = 1 # Start with 1, add standby nodes for HA94 vpc_uuid = digitalocean_vpc.main.id # Ensure VPC is defined95 }96 ```9798## 4. Disciplined Container Builds99100Follow Docker's best practices to create small, secure, and efficient container images.101102* **Multi-stage Builds**: Separate build-time dependencies from runtime dependencies.103* **Minimal Base Images**: Use `alpine` variants or other minimal images.104* **Trusted Base Images**: Prefer Docker Official Images or Verified Publisher images.105* **`.dockerignore`**: Exclude unnecessary files from the build context.106* **Rebuild Images Often**: Ensure dependencies are up-to-date with security patches.107108 ❌ BAD: Single-stage build with development tools, no `.dockerignore`.109 ```dockerfile110 FROM node:18 # Large base image111 WORKDIR /app112 COPY . . # Copies everything, including .git, node_modules (if present)113 RUN npm install # Installs dev dependencies too114 CMD ["npm", "start"]115 ```116117 ✅ GOOD: Multi-stage build, minimal base, `.dockerignore` in place.118 ```dockerfile119 # .dockerignore example:120 # node_modules121 # .git122 # .env123 # Dockerfile124 # README.md125126 # Build stage127 FROM node:20-alpine AS builder128 WORKDIR /app129 COPY package*.json ./130 RUN npm install --omit=dev # Only install production dependencies131 COPY . .132 RUN npm run build # Compile application if needed133134 # Production stage135 FROM node:20-alpine136 WORKDIR /app137 COPY --from=builder /app/node_modules ./node_modules138 COPY --from=builder /app/dist ./dist # Copy compiled app139 EXPOSE 8080140 CMD ["node", "dist/index.js"]141 ```142143## 5. Automated Workflows (CI/CD & IaC)144145Automate everything possible. This reduces human error, increases deployment speed, and ensures consistency.146147* **CI/CD Pipelines**: Use DigitalOcean App Platform's built-in CI/CD or integrate with GitHub Actions for DOKS deployments.148* **Infrastructure as Code (IaC)**: Manage all DigitalOcean resources with Terraform. This ensures your infrastructure is version-controlled, reproducible, and auditable.149150 ❌ BAD: Manual resource creation via Control Panel.151 ```bash152 # Click-ops in the UI153 # Create Droplet -> Add Database -> Configure Load Balancer...154 ```155156 ✅ GOOD: Define infrastructure with Terraform.157 ```terraform158 # main.tf159 resource "digitalocean_project" "my_project" {160 name = "My Awesome Project"161 description = "Infrastructure for my awesome app."162 purpose = "Web Application"163 }164165 resource "digitalocean_vpc" "main" {166 name = "my-app-vpc"167 region = "nyc3"168 ip_range = "10.10.0.0/20"169 }170171 resource "digitalocean_kubernetes_cluster" "main_cluster" {172 name = "my-app-cluster"173 region = "nyc3"174 version = "1.28.2-do.0"175 vpc_uuid = digitalocean_vpc.main.id176 node_pool {177 name = "worker-pool"178 size = "s-2vcpu-4gb"179 node_count = 2180 }181 }182 ```183184## 6. Performance & Cost Optimization185186Continuously monitor and optimize your resources.187188* **Autoscaling**: Implement autoscaling for Droplet pools and Kubernetes node pools to match demand and save costs.189* **Load Balancers**: Use DigitalOcean Load Balancers to distribute traffic and handle SSL.190* **Regular Architecture Reviews**: Leverage DigitalOcean's free Solutions Engineer reviews to identify inefficiencies and security gaps.191* **Monitor Usage & Set Alerts**: Track CPU, memory, disk I/O, network traffic, and billing.192193 ❌ BAD: Over-provisioned Droplets running at low utilization.194 ```bash195 # Manually scaled up to a large Droplet "just in case"196 digitalocean droplet create --size s-8vcpu-16gb --image ubuntu-22-04 --region nyc3 --name my-server197 ```198199 ✅ GOOD: Use autoscaling groups or right-sized resources.200 ```terraform201 resource "digitalocean_kubernetes_node_pool" "autoscaling_pool" {202 cluster_id = digitalocean_kubernetes_cluster.main_cluster.id203 name = "autoscaled-workers"204 size = "s-2vcpu-4gb"205 min_nodes = 1206 max_nodes = 5207 auto_scale = true208 }209 ```210211## 7. Testing & Observability212213Integrate testing into your CI/CD and ensure robust monitoring.214215* **Automated Testing**: Include unit, integration, and end-to-end tests in your CI pipeline.216* **Staging Environments**: Deploy to dedicated staging environments (e.g., via App Platform's branch deployments) before production.217* **Logging & Monitoring**: Centralize logs and use DigitalOcean Monitoring for metrics and alerts.218219 ❌ BAD: Manual testing only, no dedicated staging environment.220 ```bash221 # Deploy directly to production after local testing222 git push origin main # Triggers production deploy223 ```224225 ✅ GOOD: Automated tests, staging environment, and feature branches.226 ```yaml227 # .github/workflows/ci-cd.yml (simplified)228 name: CI/CD Pipeline229230 on:231 push:232 branches:233 - main234 - feature/*235236 jobs:237 build-and-test:238 runs-on: ubuntu-latest239 steps:240 - uses: actions/checkout@v3241 - name: Build Docker Image242 run: docker build -t my-app:${{ github.sha }} .243 - name: Run Unit Tests244 run: docker run my-app:${{ github.sha }} npm test245246 deploy-staging:247 needs: build-and-test248 if: startsWith(github.ref, 'refs/heads/feature/')249 runs-on: ubuntu-latest250 steps:251 # ... deploy to App Platform staging environment252 - name: Deploy to App Platform Staging253 run: doctl apps create-deployment --app-id ${{ secrets.APP_PLATFORM_STAGING_ID }} --image my-app:${{ github.sha }}254255 deploy-production:256 needs: build-and-test257 if: github.ref == 'refs/heads/main'258 runs-on: ubuntu-latest259 steps:260 # ... deploy to App Platform production environment261 - name: Deploy to App Platform Production262 run: doctl apps create-deployment --app-id ${{ secrets.APP_PLATFORM_PROD_ID }} --image my-app:${{ github.sha }}263 ```