traefik是一個使你把微服務暴露出來變的更容易的http反向代理和負載均衡軟件。traefik支持K8S、docker swarm、mesos、consul、etcd、zookeeper等基礎設施組件,個人認爲更適合容器化的微服務,traefik的配置會自動的、動態的配置更新自己。
假如你在基礎架構組件中部署了大量的微服務,你一般通過服務發現或者資源管理框架來管理這些服務,這時候你想訪問微服務,你需要一個反向代理。傳統的反向代理需要你配置每一個訪問到的微服務,在環境中當你增加、刪除、升級、橫向擴展服務的時候,你都需要調整反向代理配置,而傳統的反向代理是不支持動態配置的。爲了適應容器化微服務的這種場景,traefik就誕生了,traefik可以監聽你的服務發現/基礎架構組件的管理API,並且每當你的微服務被添加、移除、殺死或更新都會被感知,並且可以自動生成它們的配置文件。 這樣指向到你服務的路由將會被直接創建出來。
官方針對traefik吹了一大堆,在我看來有用的就一個支持K8S、docker swarm等,和容器結合比較緊密。所以一般情況下大家都是以容器的方式運行traefik。traefik的主程序就是一個二進制文件,你可以在非容器環境下使用。
普通青年快速入門
製作traefik image
git clone https://github.com/containous/traefik.git
docker build -t traefik .
啓動traefik
配置compose文件
version: '3'
services:
reverse-proxy:
image: traefik # The official Traefik docker image
command: --api --docker # Enables the web UI and tells Træfik to listen to docker
ports:
- "80:80" # The HTTP port
- "8080:8080" # The Web UI (enabled by --api)
volumes:
- /var/run/docker.sock:/var/run/docker.sock # So that Traefik can listen to the Docker events
啓動traefik
docker-compose up -d reverse-proxy
或者直接以容器啓動
docker run -d -p 8080:8080 -p 80:80 -v $PWD/traefik.toml:/etc/traefik/traefik.toml traefik
非普通青年入門
traefik並非只能在container裏面運行,也可以使用二進制文件直接啓動
下載二進制文件
https://github.com/containous/traefik/releases
簡單的配置文件
https://raw.githubusercontent.com/containous/traefik/master/traefik.sample.toml
ps:默認traefik會尋找/etc/traefik/traefik.toml下的配置文件,當然也可以通過-c參數指定配置文件
啓動應用
創建服務compose文件
version: '3'
services:
whoami:
image: emilevauge/whoami
networks:
- web
labels:
- "traefik.backend=whoami"
- "traefik.frontend.rule=Host:whoami.docker.localhost"
networks:
web:
external:
name: traefik_webgateway
ps:其中最關鍵的是labels的設置
測試
curl -H Host:whoami.docker.localhost http://127.0.0.1
下面開始仔細講解traefik的點點滴滴
entrypoints
進來的請求在entrypoints處結束,entrypoint是traefik的網絡入口,entrypoint監聽端口,SSL,做流量redirect。在經過entrypoint後,流量會被轉發到一個匹配的frontend上,frontend定義了從entrypoint到backends的路由,路由是通過Host、Path、Headers來決定的,可以匹配或者拒絕一個請求。frontend把請求傳送到backend,backend是由一個或者多個servers組成的,servers主要是設置負載均衡策略。最後server會把請求轉發到私網內真正的微服務上去
entrypoints是traefik的網絡入口,可以通過如下方式定義:
- 一個端口 (80, 443...)
- SSL (證書, 密鑰, 由受信任的CA簽名的客戶端證書的身份驗證...)
- 重定向到其他的入口點 (重定向 HTTP 到 HTTPS)
顯示一個entrypoint定義的例子:
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[[entryPoints.https.tls.certificates]]
certFile = "tests/traefik.crt"
keyFile = "tests/traefik.key"
- 定義了兩個entrypoints,一個是http,一個是https
- http監聽在80端口,https監聽在443端口
- 當啓用ssl的時候,需要提供CA證書
- 把http entrypoint的請求都重定向到https entrypoint上
frontends
frontends由一組規則組成,這些規則確定傳入請求如何從entrypoint轉發到backend。規則可以分爲兩種類型:修飾符和匹配器。
Modifiers
Modifier規則只修改請求,它們對正在做出的路由決策沒有任何影響,下列是已經存在的modifier規則:
AddPrefix: /products:爲請求URL路徑添加前綴
ReplacePath: /serverless-path:替換path,並把老的path添加到X-Replaced-Path頭
ReplacePathRegex: ^/api/v2/(.*) /api/$1:
Matchers
Matcher規則確定一個特定的請求應該被轉發到哪個backend,用逗號分隔的規則值之間是'或'的關係,用分號分隔的規則值是必須全部滿足的關係。下面是一些已經存在的matcher 規則:
Headers: Content-Type, application/json: 通過 Headers 可以添加一個匹配規則來匹配請求頭部包含的值。它接受要匹配的鍵/值對序列。
HeadersRegexp: Content-Type, application/(text|json): 也可以在 Headers 中使用正則表達式。它接受要匹配的鍵/值對序列,序列內容解析是通過正則匹配的
Host: traefik.io, www.traefik.io: 匹配請求 Host 必需在給定域名列表內。
HostRegexp: traefik.io, {subdomain:[a-z]+}.traefik.io: 添加匹配請求 Host 的正則表達式。 它接受一個以{}包括起來的爲空或更多url變量的模版。變量的值可以以一個可選的正則表達式來匹配。
Method: GET, POST, PUT: Method 可以添加一個HTTP請求方法的匹配。它接受要匹配的一個或多個請求方法序列。
Path: /products/, /articles/{category}/{id:[0-9]+}: Path 可以添加一個URL路徑的匹配。它接受一個以{}包括起來的爲空或更多url變量的模版。
PathStrip: /products/ 和 Path 相同,但從請求的URL路徑中去掉的給定的前綴。
PathStripRegex: /articles/{category}/{id:[0-9]+} Match exact path and strip off the path prior to forwarding the request to the backend. It accepts a sequence of literal and regular expression paths.
PathPrefix: /products/, /articles/{category}/{id:[0-9]+} PathPrefix 可以添加一個URL路徑前綴的匹配。它匹配給定模版中的完整URL路徑前綴。
PathPrefixStrip: /products/ 和 PathPrefix 相同,但從請求的URL路徑中去掉的給定的前綴。
PathPrefixStripRegex: /articles/{category}/{id:[0-9]+} Match request prefix path and strip off the path prefix prior to forwarding the request to the backend. It accepts a sequence of literal and regular expression prefix paths. Starting with Traefik 1.3, the stripped prefix path will be available in the X-Forwarded-Prefix header.
Query: foo=bar, bar=baz 匹配查詢對象,接受k=v的格式
ps:爲了在Host和Path matchers規則中使用正則,你必須使用命名捕獲,例如:/posts/{id:[0-9]+},你可以選擇啓用 passHostHeader 來轉發客戶端請求Header中的 Host 字段到後端
顯示一個frontends定義的例子:
[frontends]
[frontends.frontend1]
backend = "backend2"
[frontends.frontend1.routes.test_1]
rule = "Host:test.localhost,test2.localhost"
[frontends.frontend2]
backend = "backend1"
passHostHeader = true
passTLSCert = true
priority = 10
entrypoints = ["https"] # overrides defaultEntryPoints
[frontends.frontend2.routes.test_1]
rule = "HostRegexp:localhost,{subdomain:[a-z]+}.localhost"
[frontends.frontend3]
backend = "backend2"
[frontends.frontend3.routes.test_1]
rule = "Host:test3.localhost;Path:/test"
- 定義了frontend1, frontend2 和 frontend3三個frontends
- 如果匹配Host:test.localhost,test2.localhost規則,則frontend1轉發請求到backend2
- 如果匹配HostRegexp:localhost,{subdomain:[a-z]+}.localhost規則,則frontend2轉發請求到backend1
- 如果Host:test3.localhost和Path:/test同時匹配,則frontend3轉發請求到backend2
合併多條規則的例子:
[frontends.frontend3]
backend = "backend2"
[frontends.frontend3.routes.test_1]
rule = "Host:test3.localhost"
[frontends.frontend3.routes.test_2]
rule = "Path:/test"
可以使用分號把多個規則合併在一起,如下:
[frontends.frontend3]
backend = "backend2"
[frontends.frontend3.routes.test_1]
rule = "Host:test3.localhost;Path:/test"
你可以使用 , 符號分隔規則,爲一個frontend創建一個規則來綁定多個域名或路徑:
[frontends.frontend2]
[frontends.frontend2.routes.test_1]
rule = "Host:test1.localhost,test2.localhost"
[frontends.frontend3]
backend = "backend2"
[frontends.frontend3.routes.test_1]
rule = "Path:/test1,/test2"
ps:規則的優先級:當結合Modifier和Matcher規則一起使用的時候,要記住,Modifier規則始終在Matcher規則之後起作用。
下面的規則在Matchers和Modifiers都有,所以Matcher先執行,然後纔是Modifier:
- PathStrip
- PathStripRegex
- PathPrefixStrip
- PathPrefixStripRegex
無論規則的順序如何寫,Modifiers都是按照一定的順序執行,如下:
- PathStrip
- PathPrefixStrip
- PathStripRegex
- PathPrefixStripRegex
- AddPrefix
- ReplacePath
優先級:默認情況下,路由會以規則長度(爲了防止部分重疊情況)被排序(倒序)。
你也可以在frontend上自定義優先級:
[frontends]
[frontends.frontend1]
backend = "backend1"
priority = 20
passHostHeader = true
[frontends.frontend1.routes.test_1]
rule = "PathPrefix:/to"
[frontends.frontend2]
backend = "backend2"
passHostHeader = true
[frontends.frontend2.routes.test_1]
rule = "PathPrefix:/toto"
自定義headers:可以在frontends中配置自定義的headers,可以在requests或者responses中匹配frontends的規則,
[frontends]
[frontends.frontend1]
backend = "backend1"
[frontends.frontend1.headers.customresponseheaders]
X-Custom-Response-Header = "True"
[frontends.frontend1.headers.customrequestheaders]
X-Script-Name = "test"
[frontends.frontend1.routes.test_1]
rule = "PathPrefixStrip:/cheese"
- 給所有匹配/cheese的請求添加X-Script-Name頭,給響應添加X-Custom-Response-Header頭
安全headers:是關於HSTS headers, SSL redirection, Browser XSS filter的一些設置,
[frontends]
[frontends.frontend1]
backend = "backend1"
[frontends.frontend1.headers]
FrameDeny = true
[frontends.frontend1.routes.test_1]
rule = "PathPrefixStrip:/cheddar"
[frontends.frontend2]
backend = "backend2"
[frontends.frontend2.headers]
SSLRedirect = true
[frontends.frontend2.routes.test_1]
rule = "PathPrefixStrip:/stilton"
backends
backends負責將來自一個或者多個frontends的流量負載均衡到一組http servers上。Servers是通過一個url來定義的,也可以給每個server設置weight。
下面是backend和server的定義:
[backends]
[backends.backend1]
# ...
[backends.backend1.servers.server1]
url = "http://172.17.0.2:80"
weight = 10
[backends.backend1.servers.server2]
url = "http://172.17.0.3:80"
weight = 1
[backends.backend2]
# ...
[backends.backend2.servers.server1]
url = "http://172.17.0.4:80"
weight = 1
[backends.backend2.servers.server2]
url = "http://172.17.0.5:80"
weight = 2
- 定義了兩個backends:backend1和backend2
負載均衡:支持兩種負載均衡模式,默認是wrr
- wrr: 加權輪詢
- drr: 動態輪詢: 這會爲表現比其他服務器好的服務器增加權重。當服務器表現有變化的時,它也會會退到正常權重。
斷路器:也可以應用到後端,用於防止故障服務器上的高負載。 初始化狀態是Standby。斷路器只觀察統計信息但並不修改請求。 當斷路條件匹配時,斷路器進入Tripped狀態,它會返回與定義的http狀態碼或轉發到其他前端。 一旦Tripped狀態計時器超時,斷路器會進入Recovering狀態並重置所有統計數據。 當短路條件不匹配並且Recovery狀態計時器超時時,斷路器進入Standby狀態。
斷路器可以使用如下配置:
- 方法: LatencyAtQuantileMS, NetworkErrorRatio, ResponseCodeRatio
- 操作符: AND, OR, EQ, NEQ, LT, LE, GT, GE
例如:
NetworkErrorRatio() > 0.5: 監控網絡故障率大於0.5超過10秒後,爲這個前端平滑切換,斷路條件匹配
LatencyAtQuantileMS(50.0) > 50: 監控延遲超過50ms時斷路條件匹配
ResponseCodeRatio(500, 600, 0, 600) > 0.5: 監控返回 HTTP狀態碼在[500-600]之間的數量/HTTP狀態碼在[0-600]之間的數量 的比例大於0.5時,斷路條件匹配
下面是包含斷路器的backends和servers的定義:
[backends]
[backends.backend1]
[backends.backend1.circuitbreaker]
expression = "NetworkErrorRatio() > 0.5"
[backends.backend1.servers.server1]
url = "http://172.17.0.2:80"
weight = 10
[backends.backend1.servers.server2]
url = "http://172.17.0.3:80"
weight = 1
最大連接數:爲了主動防治後端被高負載壓垮,可以爲每個後端設置最大連接數限制。最大連接數限制可以通過爲maxconn.amount配置一個整型值,同時 maxconn.extractorfunc 是用來配置通過什麼樣的維度來統計最大連接數。
例如:
[backends]
[backends.backend1]
[backends.backend1.maxconn]
amount = 10
extractorfunc = "request.host"
會話保持:所有的負載平衡器都支持會話保持。當會話保持被開啓時,在初始請求上設置cookie,默認cookie名稱是sha1的縮寫。在隨後的請求中,客戶端會被直接轉發到這個cookie中存儲的後端(當然它要是健康可用的),如果這個後端不可用,將會指定一個新的後端。
例如:
[backends]
[backends.backend1]
# Enable sticky session
[backends.backend1.loadbalancer.stickiness]
健康監測:服務器健康檢查也是可配置的,Traefik定期執行HTTP GET請求到backend時,backend返回的HTTP狀態碼不是200 OK,那麼這個後端將被從負載均衡輪詢列表中移除。
健康檢查可以以一個在後端URL後附加路徑的路徑地址與一個時間間隔 (以 time.ParseDuration 所識別的格式給出) specifying how 配置多久健康檢查應該執行一次 (默認30秒). 每個後端必需在5秒內迴應健康檢查。當一個後端重新返回HTTP狀態碼200 OK時,將被重新添加回負載均衡輪詢列表。
例如:
[backends]
[backends.backend1]
[backends.backend1.healthcheck]
path = "/health"
interval = "10s"
port = 8080
配置
Træfik's的配置分爲兩部分:
- Static Træfik configuration:僅在啓動時被加載
- Dynamic Træfik configuration:被熱更新(無需重啓進程)
Static Træfik configuration:靜態配置是一種全局配置,用來設置entrypoints和backends的連接,traefik可以試驗多種配置源,以下是配置生效的優先級,
- Key-value store
- Arguments
- Configuration file
- Default
配置文件:traefik會在以下幾個地方尋找traefik.toml配置文件
- /etc/traefik/
- $HOME/.traefik/
不過也可以在命令行改變配置文件路徑:traefik --configFile=foo/bar/myconfigfile.toml
前面說過traefik的配置可以是kv對的形式,這些kv對可以存儲在以下後端存儲中:
- Consul
- etcd
- ZooKeeper
- boltdb
Dynamic Træfik configuration:動態配置關注的是frontends、backends、servers、https ca等。
Global Configuration
Main Section:
# graceTimeOut = "10s"
# debug = true
# checkNewVersion = false
# providersThrottleDuration = "2s"
# maxIdleConnsPerHost = 200
# insecureSkipVerify = true
# rootCAs = [ "/mycert.cert" ]
# defaultEntryPoints = ["http", "https"]
# AllowMinWeightZero = true
Constraints:
在一個以中央服務發現的微服務架構中,配置文件會將Træfɪk的發現範圍約束到一小部分路由上。Træfɪk 根據你在配置後端時爲服務設置的屬性/標籤來過濾服務。traefik支持通過tag來過濾
支持的後端類型:
Docker
Consul K/V
BoltDB
Zookeeper
Etcd
Consul Catalog
Rancher
Marathon
Kubernetes
tag配置樣例:
# 簡單約束匹配的條件
# constraints = ["tag==api"]
#
# 簡單約束不匹配的條件
# constraints = ["tag!=api"]
#
# 約束全局匹配條件
# constraints = ["tag==us-*"]
#
# 多個約束條件
# constraints = ["tag!=us-*", "tag!=asia-*"]
Custom Error pages:
可以在frontend上自定義錯誤狀態碼的返回頁面
例如:
[frontends]
[frontends.website]
backend = "website"
[frontends.website.errors]
[frontends.website.errors.network]
status = ["500-599"]
backend = "error"
query = "/{status}.html"
[frontends.website.routes.website]
rule = "Host: website.mydomain.com"
[backends]
[backends.website]
[backends.website.servers.website]
url = "https://1.2.3.4"
[backends.error]
[backends.error.servers.error]
url = "http://2.3.4.5"
Rate limiting:
可以在每個frontend上配置限速
例如:
[frontends]
[frontends.frontend1]
# ...
[frontends.frontend1.ratelimit]
extractorfunc = "client.ip"
[frontends.frontend1.ratelimit.rateset.rateset1]
period = "10s"
average = 100
burst = 200
[frontends.frontend1.ratelimit.rateset.rateset2]
period = "3s"
average = 5
burst = 10
Buffering:
可以在每個backend上開啓請求的buffer
例如:
[backends]
[backends.backend1]
[backends.backend1.buffering]
maxRequestBodyBytes = 10485760
memRequestBodyBytes = 2097152
maxResponseBodyBytes = 10485760
memResponseBodyBytes = 2097152
retryExpression = "IsNetworkError() && Attempts() <= 2"
Retry Configuration:
當網絡有異常時的請求重試次數
例如:
[retry]
# Number of attempts
# Optional
# Default: (number servers in backend) -1
#
# attempts = 3
Health Check Configuration:
可以自定義監控檢測時間
例如:
[healthcheck]
# Set the default health check interval.
#
# Optional
# Default: "30s"
#
# interval = "30s"
Life Cycle:
在Traefik停機的時間內,控制Traefik的行爲
例如:
[lifeCycle]
# Optional
# Default: 0
#
# requestAcceptGraceTimeout = "10s"
#
# Optional
# Default: "10s"
#
# graceTimeOut = "10s"
Timeouts:
各種超時時間的設置
例如
[respondingTimeouts]
# readTimeout is the maximum duration for reading the entire request, including the body.
#
# Optional
# Default: "0s"
#
# readTimeout = "5s"
# writeTimeout is the maximum duration before timing out writes of the response.
#
# Optional
# Default: "0s"
#
# writeTimeout = "5s"
# idleTimeout is the maximum duration an idle (keep-alive) connection will remain idle before closing itself.
#
# Optional
# Default: "180s"
#
# idleTimeout = "360s"
[forwardingTimeouts]
# dialTimeout is the amount of time to wait until a connection to a backend server can be established.
#
# Optional
# Default: "30s"
#
# dialTimeout = "30s"
# responseHeaderTimeout is the amount of time to wait for a server's response headers after fully writing the request (including its body, if any).
#
# Optional
# Default: "0s"
#
# responseHeaderTimeout = "0s"
# idleTimeout
#
# DEPRECATED - see [respondingTimeouts] section.
#
# Optional
# Default: "180s"
#
idleTimeout = "360s"
provider_name:
就是後端存儲的類型
例如
[provider_name]
# Override default provider configuration template. For advanced users :)
#
# Optional
# Default: ""
#
filename = "custom_config_template.tpml"
# Enable debug logging of generated configuration template.
#
# Optional
# Default: false
#
debugLogGeneratedTemplate = true
Logs Definition
TOML
logLevel = "INFO"
[traefikLog]
filePath = "/path/to/traefik.log"
format = "json"
[accessLog]
filePath = "/path/to/access.log"
format = "json"
[accessLog.filters]
statusCodes = ["200", "300-302"]
retryAttempts = true
minDuration = "10ms"
[accessLog.fields]
defaultMode = "keep"
[accessLog.fields.names]
"ClientUsername" = "drop"
# ...
[accessLog.fields.headers]
defaultMode = "keep"
[accessLog.fields.headers.names]
"User-Agent" = "redact"
"Authorization" = "drop"
"Content-Type" = "keep"
CLI
--logLevel="DEBUG"
--traefikLog.filePath="/path/to/traefik.log"
--traefikLog.format="json"
--accessLog.filePath="/path/to/access.log"
--accessLog.format="json"
--accessLog.filters.statusCodes="200,300-302"
--accessLog.filters.retryAttempts="true"
--accessLog.filters.minDuration="10ms"
--accessLog.fields.defaultMode="keep"
--accessLog.fields.names="Username=drop Hostname=drop"
--accessLog.fields.headers.defaultMode="keep"
--accessLog.fields.headers.names="User-Agent=redact Authorization=drop Content-Type=keep"
Entry Points Definition
TOML
defaultEntryPoints = ["http", "https"]
[entryPoints]
[entryPoints.http]
address = ":80"
compress = true
[entryPoints.http.whitelist]
sourceRange = ["10.42.0.0/16", "152.89.1.33/32", "afed:be44::/16"]
useXForwardedFor = true
[entryPoints.http.tls]
minVersion = "VersionTLS12"
cipherSuites = [
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_RSA_WITH_AES_256_GCM_SHA384"
]
[[entryPoints.http.tls.certificates]]
certFile = "path/to/my.cert"
keyFile = "path/to/my.key"
[[entryPoints.http.tls.certificates]]
certFile = "path/to/other.cert"
keyFile = "path/to/other.key"
# ...
[entryPoints.http.tls.clientCA]
files = ["path/to/ca1.crt", "path/to/ca2.crt"]
optional = false
[entryPoints.http.redirect]
entryPoint = "https"
regex = "^http://localhost/(.*)"
replacement = "http://mydomain/$1"
permanent = true
[entryPoints.http.auth]
headerField = "X-WebAuth-User"
[entryPoints.http.auth.basic]
removeHeader = true
users = [
"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/",
"test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0",
]
usersFile = "/path/to/.htpasswd"
[entryPoints.http.auth.digest]
removeHeader = true
users = [
"test:traefik:a2688e031edb4be6a3797f3882655c05",
"test2:traefik:518845800f9e2bfb1f1f740ec24f074e",
]
usersFile = "/path/to/.htdigest"
[entryPoints.http.auth.forward]
address = "https://authserver.com/auth"
trustForwardHeader = true
authResponseHeaders = ["X-Auth-User"]
[entryPoints.http.auth.forward.tls]
ca = "path/to/local.crt"
caOptional = true
cert = "path/to/foo.cert"
key = "path/to/foo.key"
insecureSkipVerify = true
[entryPoints.http.proxyProtocol]
insecure = true
trustedIPs = ["10.10.10.1", "10.10.10.2"]
[entryPoints.http.forwardedHeaders]
trustedIPs = ["10.10.10.1", "10.10.10.2"]
[entryPoints.https]
# ...
CLI
--entryPoints='Name:http Address::80'
--entryPoints='Name:https Address::443 TLS'
Basic:
# Entrypoints definition
#
# Default:
# [entryPoints]
# [entryPoints.http]
# address = ":80"
#
[entryPoints]
[entryPoints.http]
address = ":80"
Redirect HTTP to HTTPS:
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
entryPoint = "https"
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[[entryPoints.https.tls.certificates]]
certFile = "integration/fixtures/https/snitest.com.cert"
keyFile = "integration/fixtures/https/snitest.com.key"
[[entryPoints.https.tls.certificates]]
certFile = "integration/fixtures/https/snitest.org.cert"
keyFile = "integration/fixtures/https/snitest.org.key"
Rewriting URL:
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.redirect]
regex = "^http://localhost/(.*)"
replacement = "http://mydomain/$1"
TLS:
[entryPoints]
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
[[entryPoints.https.tls.certificates]]
certFile = "integration/fixtures/https/snitest.com.cert"
keyFile = "integration/fixtures/https/snitest.com.key"
Authentication
Basic Authentication
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.auth.basic]
users = ["test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/", "test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0"]
usersFile = "/path/to/.htpasswd"
Digest Authentication
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.auth.digest]
users = ["test:traefik:a2688e031edb4be6a3797f3882655c05", "test2:traefik:518845800f9e2bfb1f1f740ec24f074e"]
usersFile = "/path/to/.htdigest"
Forward Authentication
[entryPoints]
[entryPoints.http]
# ...
# To enable forward auth on an entrypoint
[entryPoints.http.auth.forward]
address = "https://authserver.com/auth"
# Trust existing X-Forwarded-* headers.
# Useful with another reverse proxy in front of Traefik.
#
# Optional
# Default: false
#
trustForwardHeader = true
# Copy headers from the authentication server to the request.
#
# Optional
#
authResponseHeaders = ["X-Auth-User", "X-Secret"]
# Enable forward auth TLS connection.
#
# Optional
#
[entryPoints.http.auth.forward.tls]
ca = "path/to/local.crt"
caOptional = true
cert = "path/to/foo.cert"
key = "path/to/foo.key"
Specify Minimum TLS Version:
[entryPoints]
[entryPoints.https]
address = ":443"
[entryPoints.https.tls]
minVersion = "VersionTLS12"
cipherSuites = [
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_RSA_WITH_AES_256_GCM_SHA384"
]
[[entryPoints.https.tls.certificates]]
certFile = "integration/fixtures/https/snitest.com.cert"
keyFile = "integration/fixtures/https/snitest.com.key"
[[entryPoints.https.tls.certificates]]
certFile = "integration/fixtures/https/snitest.org.cert"
keyFile = "integration/fixtures/https/snitest.org.key"
Compression:
[entryPoints]
[entryPoints.http]
address = ":80"
compress = true
White Listing:
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.http.whiteList]
sourceRange = ["127.0.0.1/32", "192.168.1.7"]
# useXForwardedFor = true
Forwarded Header:
[entryPoints]
[entryPoints.http]
address = ":80"
# Enable Forwarded Headers
[entryPoints.http.forwardedHeaders]
# List of trusted IPs
#
# Required
# Default: []
#
trustedIPs = ["127.0.0.1/32", "192.168.1.7"]
API Definition
Configuration:
# API definition
# Warning: Enabling API will expose Træfik's configuration.
# It is not recommended in production,
# unless secured by authentication and authorizations
[api]
# Name of the related entry point
#
# Optional
# Default: "traefik"
#
entryPoint = "traefik"
# Enable Dashboard
#
# Optional
# Default: true
#
dashboard = true
# Enable debug mode.
# This will install HTTP handlers to expose Go expvars under /debug/vars and
# pprof profiling data under /debug/pprof/.
# Additionally, the log level will be set to DEBUG.
#
# Optional
# Default: false
#
debug = true
Security:
API:
defaultEntryPoints = ["http"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.foo]
address = ":8082"
[entryPoints.bar]
address = ":8083"
[ping]
entryPoint = "foo"
[api]
entryPoint = "bar"
Custom Path
defaultEntryPoints = ["http"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.foo]
address = ":8080"
[entryPoints.bar]
address = ":8081"
# Activate API and Dashboard
[api]
entryPoint = "bar"
dashboard = true
[file]
[backends]
[backends.backend1]
[backends.backend1.servers.server1]
url = "http://127.0.0.1:8081"
[frontends]
[frontends.frontend1]
entryPoints = ["foo"]
backend = "backend1"
[frontends.frontend1.routes.test_1]
rule = "PathPrefixStrip:/yourprefix;PathPrefix:/yourprefix"
Authentication
defaultEntryPoints = ["http"]
[entryPoints]
[entryPoints.http]
address = ":80"
[entryPoints.foo]
address=":8080"
[entryPoints.foo.auth]
[entryPoints.foo.auth.basic]
users = [
"test:$apr1$H6uskkkW$IgXLP6ewTrSuBkTrqE8wj/",
"test2:$apr1$d9hr9HBB$4HxwgUir3HP4EsggP/QNo0",
]
[api]
entrypoint="foo"
Metrics:
[api]
# ...
# Enable more detailed statistics.
[api.statistics]
# Number of recent errors logged.
#
# Default: 10
#
recentErrors = 10
# ...
Docker Provider
Docker Swarm Mode:
################################################################
# Docker Swarm Mode Provider
################################################################
# Enable Docker Provider.
[docker]
# Docker server endpoint.
# Can be a tcp or a unix socket endpoint.
#
# Required
# Default: "unix:///var/run/docker.sock"
#
endpoint = "tcp://127.0.0.1:2375"
# Default base domain used for the frontend rules.
# Can be overridden by setting the "traefik.domain" label on a services.
#
# Optional
# Default: ""
#
domain = "docker.localhost"
# Enable watch docker changes.
#
# Optional
# Default: true
#
watch = true
# Use Docker Swarm Mode as data provider.
#
# Optional
# Default: false
#
swarmMode = true
# Define a default docker network to use for connections to all containers.
# Can be overridden by the traefik.docker.network label.
#
# Optional
#
network = "web"
# Override default configuration template.
# For advanced users :)
#
# Optional
#
# filename = "docker.tmpl"
# Override template version
# For advanced users :)
#
# Optional
# - "1": previous template version (must be used only with older custom templates, see "filename")
# - "2": current template version (must be used to force template version when "filename" is used)
#
# templateVersion = 2
# Expose services by default in Traefik.
#
# Optional
# Default: true
#
exposedByDefault = false
# Enable docker TLS connection.
#
# Optional
#
# [docker.tls]
# ca = "/etc/ssl/ca.crt"
# cert = "/etc/ssl/docker.crt"
# key = "/etc/ssl/docker.key"
# insecureSkipVerify = true
Labels:
overriding default behavior:
Using Docker with Swarm Mode:
version: "3"
services:
whoami:
deploy:
labels:
traefik.docker.network: traefik