Load Balancing

Load balancing multiple Echo servers using a reverse proxy server like Nginx, Armor

This recipe demonstrates how you can use Nginx or Armor as a reverse proxy server and load balance between multiple Echo servers.

How to setup Nginx proxy server with Echo?

Step 1: Install Nginx

https://www.nginx.com/resources/wiki/start/topics/tutorials/install

Step 2: Configure Nginx

Create a file /etc/nginx/sites-enabled/localhost with the following content:

  1. upstream localhost {
  2. server localhost:8081;
  3. server localhost:8082;
  4. }
  5. server {
  6. listen 8080;
  7. server_name localhost;
  8. access_log /var/log/nginx/localhost.access.log combined;
  9. location / {
  10. proxy_pass http://localhost;
  11. }
  12. }

Change listen, server_name, access_log per your need.

Step 3: Restart Nginx

service nginx restart

Step 4: Start upstream servers

  • cd upstream
  • go run server.go server1 :8081
  • go run server.go server2 :8082

Step 5: Browse to https://localhost:8080

You should see a webpage being served from “server 1” or “server 2”.

  1. Hello from upstream server server1

How to setup Armor proxy server with Echo?

Step 1: Install Armor

https://armor.labstack.com/guide

Step 2: Configure Armor

Create a file /etc/armor/config.yaml with the following content:

  1. address: ":8080"
  2. plugins:
  3. - name: logger
  4. hosts:
  5. localhost:1323:
  6. paths:
  7. "/":
  8. plugins:
  9. - name: proxy
  10. targets:
  11. - url: http://localhost:8081
  12. - url: http://localhost:8082

Step 3: Start Armor

armor -c /etc/armor/config.yaml

Change address and hosts per your need.

Step 4 & 5: Follow Nginx recipe

Source Code

upstream/server.go

  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "github.com/labstack/echo"
  7. "github.com/labstack/echo/middleware"
  8. )
  9. var index = `
  10. <!DOCTYPE html>
  11. <html lang="en">
  12. <head>
  13. <meta charset="UTF-8">
  14. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  15. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  16. <title>Upstream Server</title>
  17. <style>
  18. h1, p {
  19. font-weight: 300;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <p>
  25. Hello from upstream server %s
  26. </p>
  27. </body>
  28. </html
  29. `
  30. func main() {
  31. name := os.Args[1]
  32. port := os.Args[2]
  33. e := echo.New()
  34. e.Use(middleware.Recover())
  35. e.Use(middleware.Logger())
  36. e.GET("/", func(c echo.Context) error {
  37. return c.HTML(http.StatusOK, fmt.Sprintf(index, name))
  38. })
  39. e.Logger.Fatal(e.Start(port))
  40. }

Maintainers