traefik-gateway
本文为traefik基础用法,dashboard用法请参考:traefik-gateway-dashboard
traefik 是一个优秀的反向代理软件,提供与nginx类似的功能。
与nginx对比,其优势在于,nginx需要编写配置文件后,重新启动nginx以生效。nginx不支持tcp代理(使用插件可以支持)
特性 | nginx | traefik |
---|---|---|
动态配置 | 不支持动态配置 | 外部文件、redis、json、etcd |
修改配置重启 | 需要重启 | 不需要重启 |
tcp代理 | 不支持(需要重新编译源码和插件) | 支持 |
web容器 | 支持 | 不支持 |
反向代理自动携带HOST | 支持 | 不支持,需要使用中间件 |
利用此traefik的一些特性,可以将其当做入口网关使用
官方网站
- [官方网站]:https://doc.traefik.io/traefik/
主要概念
- entryPoints: 入口点,监听地址,支持http、https、tcp、udp
- routers:路由(路径)
- services:后端服务
- middlewares:中间件,在执行反向代理前、后可以执行一些操作 插件参考网址
- 静态配置文件:traefik启动时需要的配置,入口点,服务发现驱动等
- 动态配置:路由、服务、中间件、ssl证书
静态配置示例
# 静态配置
global:
checkNewVersion: true
sendAnonymousUsage: true
entryPoints:
http:
address: :80
# http:
# redirections: # http 自动跳转到 https
# entryPoint:
# to: https
# scheme: https
# tcp:
# address: :9095/tcp
https:
address: :443
http:
tls: {} # 开启 https
log:
level: DEBUG
format: json
# accessLog:
# format: json
api:
insecure: true # 开启dashboard
dashboard: true
debug: true
providers:
file:
# filename: /etc/traefik/conf.d/conf.yaml 单个文件
directory: /etc/traefik/conf.d/ # 监视文件夹
watch: true
# http:
# endpoint: "http://192.168.64.1:3000/api"
# 插件支持
# experimental:
# localPlugins:
# rewritebody:
# modulename: "github.com/traefik/plugin-rewritebody"
# version: "v0.3.1"
动态配置示例
# 动态配置
http:
routers:
# 首页
web-site:
rule: "PathPrefix(`/`)"
service: web-site
middlewares:
- stripprefix-common
iovhm-api:
rule: "PathPrefix(`/iovhm-api/`)"
service: iovhm-api
# middlewares:
# - testHeader
############################################################################
services:
web-site:
loadBalancer:
servers:
- url: http://web-site:80
iovhm-api:
loadBalancer:
servers:
- url: http://iovhm-web-api.gxzszs.cn/
############################################################################
middlewares:
stripprefix-common:
stripPrefix:
prefixes:
- "/foo"
- "/home-admin"
testHeader:
headers:
customRequestHeaders:
host: "iovhm-web-api.gxzszs.cn"
#tcp:
# routers:
# abc:
# entryPoints:
# - "tcp"
# rule: "HostSNI(`*`)"
# service: my-service
# services:
# my-service:
# loadBalancer:
# servers:
# - address: 139.9.93.117:80
# 证书列表,会根据域名自动匹配
tls:
certificates:
- certFile: /home/ssl/qq829cn.cer
keyFile: /home/ssl/qq829cn.key
# 默认证书
# tls:
# stores:
# default:
# defaultCertificate:
# certFile: "/home/ssl/qq829cn.cer"
# keyFile: "/home/ssl/qq829cn.key"
docker-compose.yaml配置文件
# docker-compose
version: "3"
services:
mobile-office-web:
image: swr.cn-south-1.myhuaweicloud.com/vp-whdev/digital-base/traefik:latest
restart: always # 自动重启
privileged: true
ports:
# - 8080:80
# - 8443:443
- 80:80
- 443:443
- 8081:8080
# - 9095:9095
volumes:
- ./traefik.yml:/etc/traefik/traefik.yml
- ./conf.d/:/etc/traefik/conf.d/
- ./ssl:/home/ssl
# - ./plugins:/plugins-local
environment:
- TZ=Asia/Shanghai