traefik

## 简介

  traefik是一款开源的反向代理与负载均衡工具。软件定位是做负载均衡器,提供好用的负载均衡服务,不要老拿它跟nginx对比。它最大的优点是能够与常见的微服务系统直接整合,可以实现自动化动态配置。           

目前支持:Docker, Swarm, Mesos/Marathon, Mesos, Kubernetes, Consul, Etcd, Zookeeper, BoltDB, Rest API等等后端模型。


#### ME为什么选择traefik?

```

Golang编写,单文件部署,与系统无关;    

热加载配置文件;    

内置Web UI,管理相对方便;  

```

功能特点:


```

It's fast

No dependency hell, single binary made with go

Rest API

Multiple backends supported: Docker, Swarm, Kubernetes, Marathon, Mesos, Consul, Etcd, and more to come

Watchers for backends, can listen for changes in backends to apply a new configuration automatically

Hot-reloading of configuration. No need to restart the process

Graceful shutdown http connections

Circuit breakers on backends

Round Robin, rebalancer load-balancers

Rest Metrics

Tiny official docker p_w_picpath included

SSL backends support

SSL frontend support (with SNI)

Clean AngularJS Web UI

Websocket support

HTTP/2 support

Retry request if network error

Let's Encrypt support (Automatic HTTPS with renewal)

High Availability with cluster mode

```


### 安装部署:

#### 规划服务路径

####  服务主路径

```

cd /etc/traefik/

```

#### ssl 证书存放路径

```

mkdir -p /etc/traefik/ssl 

```

#### 配置文件存放路径

```

mkdir -p /etc/traefik/config

```

#### 日志存放路径

```

mkdir -p /etc/traefik/log 

```

#### 源码包安装:

```

测试版本:v1.2.3

```


```

软件下载地址:https://github.com/containous/traefik/releases/tag/v1.2.3

```


软件下载到服务器后,加压,修改权限,探后启动服务;

```

chmod 755 traefik 

```

#### 启动服务

traefik go 语言编写,启动服务比较简单,指定一下配置文件即可,


```

./traefik -c ./config/traefik.toml 


```

#### 默认没有配置文件,需要自己根据官网参考文件进行整理,下面我根据官网信息,进行整理优化了一个主配置文件。

```

[root@trarfik-test config]# more traefik.toml 


##开启debug 模式,Default,false

debug = true


##日志级别, "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "PANIC"

logLevel = "INFO"


##Traefik 服务日志,如果不配置,日志将屏幕输出;

#traefikLogsFile = "/etc/traefik/log/traefik.log"


##成功访问日志

accessLogsFile = "/etc/traefik/log/access.log"


##与后端连接保持时间,避免反复与后端服务建立连接,Default,"2s"

ProvidersThrottleDuration = 5


###控制最大空闲连接数,使用net/http模块,试过设置为0 ,则不限制,如果看到'too many open files' 报错,建议修改系统层`ulimit`值

,Default: 200

maxIdleConnsPerHost = 60000


###如果设置为true,将使用后端服务SSL证书。注意:这禁用中间人***的检测只能用于后端网络安全。Default: false

#insecureSkipVerify = true


###配置默认监听端口

###配置服务默认监听端口,如果想改变监听端口,可以进行单独配置


defaultEntryPoints = ["http", "https"]

[entryPoints]

  [entryPoints.http]

  address = ":80"

  compress = true

  [entryPoints.https]

  address = ":443"

  compress = true


###ssl 证书配置

    [entryPoints.https.tls]

      `entryPoints`.`https`.`tls`.`certificates`

      certFile = "/etc/traefik/ssl/www.ptengine.cn.crt"

      keyFile = "/etc/traefik/ssl/www.ptengine.cn.key"


## 管理界面监听端口

[web]

  address = ":8800"


##设置 REST API 为只读模式

  ReadOnly = false

##启用详细信息输出,会在管理界面下方打印一些错误信息,提供参考;

  [web.statistics]

  RecentErrors = 10


## To enable Traefik to export internal metrics to Prometheus

[web.metrics.prometheus]

Buckets=[0.1,0.3,1.2,5.0]


### webui基本认证配置

### 密码可以编码在MD5、SHA1和BCrypt:您可以使用htpasswd生成

### 用户可以直接在toml指定文件,或间接通过引用一个外部文件;如果两个,两个并存,外部文件内容优先


### 测试配置实例

### 用户名/密码: 测试和test2:test2码:测试:测试和test2:test2


[web.auth.basic]

users = ["test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/", "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0"]


### 指定配置文件

usersFile = "/path/to/.htpasswd"


###配置文件扩展,可以加载监视文件内容

[file]


##不支持监听目录,监听文件名要写死

filename = "/etc/traefik/config/rules.toml"

### 监视文件变更

watch = true


##发送请求重试

[retry]

##默认只向后端请求一次,不重试,

attempts = 3

```

使用上面的配置文件启动服务,会监听3个端口, 80:http ,443:https ,8800:api ,上面的配置文件我开启了debug 模式,实际生产环境不需要。服务启动后即可访问,api 管理界面查看一下基础信息。

#### 浏览器访问地址:

```

http://localhost:8800

```

#### 使用curl 访问api 接口获取信息

```

/api/providers: GET providers

/api/providers/{provider}: GET or PUT provider

/api/providers/{provider}/backends: GET backends

/api/providers/{provider}/backends/{backend}: GET a backend

/api/providers/{provider}/backends/{backend}/servers: GET servers in a backend

/api/providers/{provider}/backends/{backend}/servers/{server}: GET a server in a backend

/api/providers/{provider}/frontends: GET frontends

/api/providers/{provider}/frontends/{frontend}: GET a frontend

/api/providers/{provider}/frontends/{frontend}/routes: GET routes in a frontend

/api/providers/{provider}/frontends/{frontend}/routes/{route}: GET a route in a frontend


```

#### 查看API接口 信息,可以显示,


```

[root@trarfik-test ~]# curl -s "http://localhost:8800/health"|jq 


{

  "pid": 23955,

  "uptime": "4m19.415827181s",

  "uptime_sec": 259.415827181,

  "time": "2017-04-21 10:38:44.925762492 +0800 CST",

  "unixtime": 1492742324,

  "status_code_count": {},

  "total_status_code_count": {

    "304": 3,

    "404": 2,

    "429": 6

  },


  "count": 0,

  "total_count": 11,

  "total_response_time": "11.553372ms",

  "total_response_time_sec": 0.011553372000000001,

  "average_response_time": "1.050306ms",

  "average_response_time_sec": 0.001050306,

  "recent_errors": [

  ...............


  ]

}


```

#### 查看配置信息接口:


```

[root@trarfik-test ~]# curl -s "http://localhost:8800/api"|jq        

{

  "file": {

    "backends": {

      "test1": {

        "servers": {

          "server1": {

            "url": "http://172.16.100.70:80",

            "weight": 1

          },

          "server2": {

            "url": "http://172.16.100.71:80",

            "weight": 1

          }

        },

        "circuitBreaker": {

          "expression": "NetworkErrorRatio() > 0.5"

        },

        "loadBalancer": {

          "method": "drr"

        },

        "maxConn": {

          "amount": 10,

          "extractorFunc": "request.host"

        }

      }

    },

    "frontends": {

      "test1": {

        "entryPoints": [

          "http",

          "https"

        ],

        "backend": "test1",

        "routes": {

          "service1": {

            "rule": "Host:test.ptmind.com;"

          }

        },

        "passHostHeader": true,

        "priority": 10

      }

    }

  }

}

```


### DOCKER  方式启动

Docker 启动需要先准备一下配置文件,将配置文件挂载到容器内部,另外注意下,api 管理端口。

```

docker run -d -p 8080:8080 -p 80:80 -v $PWD/traefik.toml:/etc/traefik/traefik.toml traefik

```


### 域名反向代理配置实例演示

#### 监听域名

```

test.ptmind.com  

pttest.ptmind.com

```

#### 后端轮训站点:

```

172.16.100.70:80  

172.16.100.71:80

```

#### 安全考虑:

```

显示单个客户端请求链接数;

后端不稳定停止转发轮训;

```

配置信息如下:


```

[root@trarfik-test config]# more rules.toml 


##后端配置

#[backends]

##发送请求重试

#[retry]


###默认只向后端请求一次,不重试,

attempts = 3

  [backends.testptmindcom]

    ##后端网络错误率>0.5 停止转发;

    [backends.testptmindcom.circuitbreaker]

      expression = "NetworkErrorRatio() > 0.5"

    ##轮训方式,method=drr(加权轮训调度)default:wrr(队列轮转算法)

    [backends.testptmindcom.LoadBalancer]

      method = "drr"

    ##安全限制,单个主机连接数大于指定值,会提示“max connections reached”

    [backends.testptmindcom.maxconn]

      amount = 10

      extractorfunc = "request.host"


    ##第一台后端节点

    [backends.testptmindcom.servers.server1]

      url = "http://172.16.100.70:80"

      weight = 1

    ##第二台后端节点

    [backends.testptmindcom.servers.server2]

      url = "http://172.16.100.71:80"

      weight = 1

```

## 前端配置

```

[frontends]

  #定义一个接入点的名字

  [frontends.testptmindcom]

  passHostHeader = true

  priority = 10

  ##定义调用后端名称

  backend = "testptmindcom"

    ##前端监听域名,可以监听多域名

    [frontends.testptmindcom.routes.service]

      rule = "Host:test.ptmind.com,pttest.ptmind.com;"

```

#### 验证配置信息:

[root@trarfik-test ~]# curl http://localhost:8800/api|jq


```

{

  "file": {

    "backends": {

      "testptmindcom": {

        "servers": {

          "server1": {

            "url": "http://172.16.100.70:80",

            "weight": 1

          },

          "server2": {

            "url": "http://172.16.100.71:80",

            "weight": 1

          }

        },


        "circuitBreaker": {

          "expression": "NetworkErrorRatio() > 0.5"

        },

        "loadBalancer": {

          "method": "drr"

        },


        "maxConn": {

          "amount": 10,

          "extractorFunc": "request.host"

        }

      }

    },


    "frontends": {

      "testptmindcom": {

        "entryPoints": [

          "http",

          "https"

        ],

        "backend": "testptmindcom",

        "routes": {

          "service": {

            "rule": "Host:test.ptmind.com,pttest.ptmind.com;"

          }

        },

        "passHostHeader": true,

        "priority": 10

      }

    }

  }

}


```

### 注意:


1:traefik 可以热加载配置文件,不用每次都重启服务,在修改主配置文件选项或着修改域名监听端口时,需要重启服务;

2:一组配置内, "backends":   "frontends"  名称要统一;  

3:注意观察实例中的名称配置;


### 参考文档

https://docs.traefik.io/toml/  

http://docs.traefik.io/toml/#retry-configuration