• 利用Caddy实现http反向代理


    利用Caddy实现http反向代理

    1 Caddy是什么

    Caddy是一个开源的,使用Golang编写的,支持HTTP/2的Web服务端。它的一个显著特征就是默认启用HTTPS。

    nginx类似。

    2 多个后端服务

    假如现在有3个后端http服务:分别在启动在

    app1

    http://10.0.0.1:8080
    
    GET /
    GET /ping
    
    • 1
    • 2
    • 3
    • 4

    app2

    http://10.0.0.2:8080
    
    GET /
    GET /ping
    
    • 1
    • 2
    • 3
    • 4

    app3

    http://10.0.0.3:8080
    
    GET /
    GET /ping
    
    • 1
    • 2
    • 3
    • 4

    3 Caddyfile

    localhost {
        # localhost/app1/ping -> http://10.0.0.1:8080/ping
        route /app1/* {
            uri strip_prefix /app1
            reverse_proxy http://10.0.0.1:8080
        }
        route /app2/* {
            uri strip_prefix /app2
            reverse_proxy http://10.0.0.2:8080
        }
        route /app3/* {
            uri strip_prefix /app3
            reverse_proxy http://10.0.0.3:8080
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Tips

    uri strip_prefix /app1的作用是将url中的/app1给去掉然后转发到reverse_proxy上去。

    启动caddy

    $> caddy run
    
    • 1

    此时使用curl或者浏览器访问

    $> curl -v http://localhost/app1/ping
    $> curl -v http://localhost/app2/ping
    $> curl -v http://localhost/app3/ping
    
    • 1
    • 2
    • 3

    则caddy会分别反向代理到app1、app2、app3上。

    4 启用HTTPS

    自签证书

    本地测试的时候需要安装本地信任机构CA并且自签证书,需要借助mkcert工具

    $> brew install mkcert
    
    • 1

    安装CA到本机

    $> mkcert -install
    
    • 1

    为主机自签证书

    $> mkcert example.org
    
    • 1

    会在当前目录生成example.org.pemexample.org-key.pem这两个文件

    配置Hosts

    在hosts文件里添加

    127.0.0.1 		example.org
    
    • 1

    此时访问example.org就会访问到本机的127.0.0.1

    在Caddyfile中添加tls

    example.org {
    		tls /Users/example.org.pem  /Users/example.org-key.pem
        # example.org/app1/ping -> http://10.0.0.1:8080/ping
        route /app1/* {
            uri strip_prefix /app1
            reverse_proxy http://10.0.0.1:8080
        }
        route /app2/* {
            uri strip_prefix /app2
            reverse_proxy http://10.0.0.2:8080
        }
        route /app3/* {
            uri strip_prefix /app3
            reverse_proxy http://10.0.0.3:8080
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    需要注意的是tls配置的 xx.pemxx-key.pem文件是绝对路径。

    重启caddy

  • 相关阅读:
    软考 - 系统架构设计师 - 数据架构真题
    神经网络算法的具体流程,神经网络算法难不难
    网络协议 — syslog 协议与 rsyslog 日志服务
    SSM-XML整合
    DBCO-PEG-Lentinan;Lentinan-PEG-DBCO;二苯并环辛炔聚乙二醇修饰香菇多糖
    Meta的画质让我震惊
    巧妙利用unbuffer实时写入
    常见的MySQL语句类型及其基础用法
    P2072 宗教问题
    三个线程依次顺序执行
  • 原文地址:https://blog.csdn.net/weixin_45747080/article/details/134270971