How to Create Load Balancers

DigitalOcean Load Balancers are a fully managed, highly available network load balancing service. Load balancers distribute traffic to groups of Droplets, which prevents the health of a backend service from depending on the health of a single server.


Setting up a load balancer is a two step process: creating the load balancer and then adding Droplets or Kubernetes nodes to its backend pool.

Create a Load Balancer Using the CLI

You can only add firewall rules to a load balancer using the CLI or API. To add a firewall to a load balancer during its creation, use the --allow-list and --deny-list flags to define a list of IP addresses or CIDRs that the load balancer will accept or block connections from.

The load balancer creation command requires a value for the --region flag. Use the doctl compute region list command to retrieve a list of available datacenter regions.

You can also automatically add Droplets to a load balancer during creation by providing a list of Droplet IDs for the --droplet-ids flag. Use the doctl compute droplet list command to retrieve a list of Droplets and their ID’s.

How to create a load balancer using the DigitalOcean CLI

To create a load balancer via the command-line, follow these steps:

  1. Install doctl, the DigitalOcean command-line tool.

  2. Create a personal access token, and save it for use with doctl.

  3. Use the token to grant doctl access to your DigitalOcean account.

                  doctl auth init
                
  4. Finally, create a load balancer with doctl compute load-balancer create. The basic usage looks like this, but you'll want to read the usage docs for more details:

                  doctl compute load-balancer create [flags]
                

Create a Load Balancer Using the API

You can only add firewall rules to a load balancer using the CLI or API. To add a firewall to a load balancer during its creation, use the firewall field to define a list of IP addresses and CIDRs the load balancer will accept or block connections from.

The load balancer creation call requires a value for the region field. Use the /v2/regions endpoint to retrieve a list of available datacenter regions.

You can also automatically add Droplets to a load balancer during creation by providing an array of Droplet IDs in the droplet_ids field. Use the /v2/droplets endpoint to retrieve a list of Droplets and their IDs.

How to create a load balancer using the DigitalOcean API

To create a load balancer using the DigitalOcean API, follow these steps:

  1. Create a personal access token, and save it for use with the API.

  2. Send a POST request to https://api.digitalocean.com/v2/load_balancers

    cURL

    To create a load balancer with cURL, call:

    
                    # Create new load balancer
    curl -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \
      -d '{"name": "example-lb-01","size_unit": 1, "region": "nyc3", "forwarding_rules":[{"entry_protocol":"http","entry_port":80,"target_protocol":"http","target_port":80,"certificate_id":"","tls_passthrough":false}, {"entry_protocol": "https","entry_port": 444,"target_protocol": "https","target_port": 443,"tls_passthrough": true}], "health_check":{"protocol":"http","port":80,"path":"/","check_interval_seconds":10,"response_timeout_seconds":5,"healthy_threshold":5,"unhealthy_threshold":3}, "sticky_sessions":{"type":"none"}, "firewall":{"deny":["ip:1.2.3.4","cidr:2.3.4.0/24"],"allow":["cidr:1.2.0.0/16","ip:2.3.4.5"]}, "droplet_ids": [3164444, 3164445]}' \
      "https://api.digitalocean.com/v2/load_balancers"
    
    # Create new load balancer with Droplet tag
    curl -X POST \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $DIGITALOCEAN_TOKEN" \
      -d '{"name": "example-lb-01", "region": "nyc3", "size_unit": 1, "forwarding_rules":[{"entry_protocol":"http","entry_port":80,"target_protocol":"http","target_port":80,"certificate_id":"","tls_passthrough":false}, {"entry_protocol": "https","entry_port": 444,"target_protocol": "https","target_port": 443,"tls_passthrough": true}], "health_check":{"protocol":"http","port":80,"path":"/","check_interval_seconds":10,"response_timeout_seconds":5,"healthy_threshold":5,"unhealthy_threshold":3}, "sticky_sessions":{"type":"none"}, "firewall":{"deny":["ip:1.2.3.4", "cidr:2.3.4.0/24"],"allow":["cidr:1.2.0.0/16","ip:2.3.4.5"]}, "tag": "web:prod"}' \
      "https://api.digitalocean.com/v2/load_balancers"

    Go

    Go developers can use Godo, the official DigitalOcean V2 API client for Go. To create a load balancer with Godo, use the following code:

    
                    import (
        "context"
        "os"
    
        "github.com/digitalocean/godo"
    )
    
    func main() {
        token := os.Getenv("DIGITALOCEAN_TOKEN")
    
        client := godo.NewFromToken(token)
        ctx := context.TODO()
    
        createRequest := &godo.LoadBalancerRequest{
            Name:      "example-01",
            SizeUnit: "1",
            Algorithm: "round_robin",
            Region:    "nyc3",
            ForwardingRules: []godo.ForwardingRule{
                {
                    EntryProtocol:  "http",
                    EntryPort:      80,
                    TargetProtocol: "http",
                    TargetPort:     80,
                },
                {
                    EntryProtocol:  "https",
                    EntryPort:      443,
                    TargetProtocol: "https",
                    TargetPort:     443,
                    TlsPassthrough: true,
                },
            },
            HealthCheck: &godo.HealthCheck{
                Protocol:               "http",
                Port:                   80,
                Path:                   "/",
                CheckIntervalSeconds:   10,
                ResponseTimeoutSeconds: 5,
                HealthyThreshold:       5,
                UnhealthyThreshold:     3,
            },
            StickySessions: &godo.StickySessions{
                Type: "none",
            },
            DropletIDs:          []int{3164444, 3164445},
            RedirectHttpToHttps: false,
            Firewall:            &godo.LBFirewall{
                Deny: []string{"ip:1.2.3.4", "cidr:2.3.4.0/24"},
                Allow: []string{"cidr:1.2.0.0/16", "ip:2.3.4.5"},
            }
      // Create new load balancer with Droplet tag
      //     Tag:                 "web:prod",
      //     RedirectHttpToHttps: false,
        }
    
        lb, _, err := client.LoadBalancers.Create(ctx, createRequest)

    Ruby

    Ruby developers can use DropletKit, the official DigitalOcean V2 API client for Ruby. To create a load balancer with DropletKit, use the following code:

    
                    require 'droplet_kit'
    token = ENV['DIGITALOCEAN_TOKEN']
    client = DropletKit::Client.new(access_token: token)
    
    load_balancer = DropletKit::LoadBalancer.new(
      name: 'example-lb-01',
      size_unit: '1',
      algorithm: 'round_robin',
    # Create new load balancer with Droplet tag
    # tag: 'web:prod',
      droplet_ids: [ 3164444, 3164445],
      redirect_http_to_https: true,
      region: 'nyc3',
      forwarding_rules: [
        DropletKit::ForwardingRule.new(
          entry_protocol: 'http',
          entry_port: 80,
          target_protocol: 'http',
          target_port: 80,
          certificate_id: '',
          tls_passthrough: false
        ),
        DropletKit::ForwardingRule.new(
          entry_protocol: 'https',
          entry_port: 443,
          target_protocol: 'https',
          target_port: 443,
          certificate_id: '',
          tls_passthrough: true
        )
      ],
      sticky_sessions: DropletKit::StickySession.new(
        type: 'cookies',
        cookie_name: 'DO-LB',
        cookie_ttl_seconds: 5
      ),
      health_check: DropletKit::HealthCheck.new(
        protocol: 'http',
        port: 80,
        path: '/',
        check_interval_seconds: 10,
        response_timeout_seconds: 5,
        healthy_threshold: 5,
        unhealthy_threshold: 3
      )
    )
    client.load_balancers.create(load_balancer)

    Python

    
                    import os
    from pydo import Client
    
    client = Client(token=os.environ.get("DIGITALOCEAN_TOKEN"))
    
    req = {
      "name": "example-lb-01",
      "region": "nyc3",
      "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": [
        3164444,
        3164445
      ],
      "project_id": "9cc10173-e9ea-4176-9dbc-a4cee4c4ff30",
      "http_idle_timeout_seconds": 60,
      "firewall": {
        "deny": [
          "cidr:1.2.0.0/16",
          "ip:2.3.4.5"
        ],
        "allow": [
          "ip:1.2.3.4",
          "cidr:2.3.4.0/24"
        ]
      }
    }
    
    resp = client.load_balancers.create(body=req)

Create a Load Balancer Using the Control Panel

Start by creating a load balancer using the Create button at the top of the control panel. Alternatively, use the Create load balancer button on the Load Balancers overview page.

Create menu

On the creation page, you will:

  1. Choose a datacenter region. Your load balancer and its backend Droplets need to be in the same datacenter, so choose the region where your Droplets are or will be located.

  2. Select a VPC Network for the load balancer. You can choose one you have created or use your default network for the datacenter region. VPC networking enables an additional networking interface that can only be accessed by other resources within the same VPC network. This keeps traffic between Droplets and other applicable resource from being routed outside the datacenter over the public internet.

  3. Choose the load balancer’s Scaling configuration.

The load balancer’s scaling configuration allows you to adjust the load balancer’s number of nodes. The number of nodes determines:

  • How many simultaneous connections it can maintain.
  • How many requests per second it can handle.
  • How many SSL connections it can decrypt per second.
  • The load balancer’s overall monthly cost.

The load balancer must have at least one node. You can add or remove nodes at any time to meet your traffic needs.

Note
The quantity and size of the load balancers you can have on your account depends on your account’s resource limits. We use dynamic resource limits to protect our platform against bad actors. Currently, you can’t check your resource limit for load balancers, but you can contact support if you reach the limit and need to increase it. We are working on features that allow you to review this limit in the control panel.
  1. Connect Droplets to the load balancer. If you are creating this load balancer for DigitalOcean Kubernetes, you can skip this step. Use the Search for Droplet or a tag search bar to add Droplets or groups of tagged Droplets to the load balancer’s backend pool upon creation. You can add or remove resources from the load balancer’s pool at anytime after creation.

  2. Add forwarding rules. Forwarding rules define how traffic is routed from the load balancer to its backend Droplets. You need at least one rule.

    The default route is HTTP port 80 on the load balancer to HTTP port 80 on the backend Droplets. You can create new rules during creation with the New Rule drop-down. After creation, you can modify a load balancer’s rules at any time on its Settings page.

    If you create a forwarding rule that requires a Let’s Encrypt certificate, you have the option to allow us to automatically create the necessary DNS record, at the apex of your domain, to support the certificate. The Create DNS records for all the new Let’s Encrypt certificates box is checked by default. If you want to manage your own DNS records for your Let’S Encrypt certificate, uncheck the box to opt out of creating any records when creating the forwarding rule.

    You can update this selection when adding or updating forwarding rules at a later time. However, the updated selection applies only to the new rules going forward, existing DNS records are not updated.

  3. Set advanced settings. Advanced settings allow you to modify additional parameters for the load balancer, sticky sessions, health checks, SSL forwarding, and PROXY protocol. You can also modify these settings after you create the load balancer.

  4. Finalize and create, which includes Choose a name and Select project. Load balancer names must be unique and contain alphanumeric characters, dashes, and periods only. You can rename load balancers at any time after creation by clicking on the existing name on the load balancer page.

After you create the load balancer, you can add Droplets or Kubernetes nodes to the load balancer on its detail page. To add Kubernetes nodes, see our guide, How to Add Load Balancers to Kubernetes Clusters. To add Droplets, click Choose Droplets to open the Add Droplets window.

Add Droplets by tag window

You can add individual Droplets or you can choose a tag. You can only choose Droplets that are in the same region as the load balancer, and if you use a tag, only tagged Droplets in the same region as the load balancer will be part of its backend. You can use one tag per load balancer.

When you’ve selected the tag or Droplets, click Add Droplets. When you add Droplets to a load balancer, the Droplets start in a DOWN state and remain in a DOWN state until they pass the load balancer’s health check. Once the backends have passed the health check the required number of times, they will be marked healthy and the load balancer will begin forwarding requests to them.

Once you have at least one load balancer, you can view and manage them on the load balancer index page.

The load balancer index page

Clicking on a load balancer from the index page takes you to its detail page. On the detail page, you can manage and customize the load balancer by modifying its backend Droplet pool, viewing its performance graphs, and changing advanced settings.