搭建使用traefik
1. 创建文件夹和文件
mkdir ~/traefik
cd ~/traefik
mkdir -p data/configurations
touch docker-compose.yml
touch data/traefik.yml
touch data/acme.json
touch data/configurations/dynamic.yml
chmod 600 data/acme.json
2. 配置 docker-compose.yml
文件路径为 ~/traefik/docker-compose.yml
version: '3.7'
services:
traefik:
image: traefik:v2.4
container_name: traefik
restart: always
security_opt:
- no-new-privileges:true
ports:
- 80:80
- 443:443
volumes:
# 如果宿主机是标准 linux 系统,可以设置一下localtime
- /etc/localtime:/etc/localtime:ro
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./data/traefik.yml:/traefik.yml:ro # 映射静态配置文件
- ./data/acme.json:/acme.json # 映射证书文件,SSL 证书申请成功后,就会存在这个文件中
- ./data/configurations:/configurations # 映射动态配置文件
networks:
- traefik
labels:
# 下面这些标签,可以帮助 traefik 正确处理该服务
- 'traefik.enable=true'
- 'traefik.docker.network=traefik' # 指定 docker network
# 指定服务入口为 websecure,websecure 会在静态配置文件traefik.yml中定义
- 'traefik.http.routers.traefik-secure.entrypoints=websecure'
# 定义访问域名,需要做 DNS 解析
- 'traefik.http.routers.traefik-secure.rule=Host(`traefik.yourdomain.com`)'
- 'traefik.http.routers.traefik-secure.middlewares=user-auth@file'
- 'traefik.http.routers.traefik-secure.service=api@internal'
networks:
traefik:
external: true
创建 docker-compose.yml
内需要的 network
docker network create traefik
3. 修改静态配置文件
文件路径为 ~/traefik/data/traefik.yml
api:
dashboard: true
entryPoints:
web:
address: :80
http:
redirections:
entryPoint:
to: websecure
websecure:
address: :443
http:
middlewares:
- secureHeaders@file
- nofloc@file
tls:
certResolver: lets-encr
pilot:
dashboard: false
providers:
docker:
endpoint: 'unix:///var/run/docker.sock'
exposedByDefault: false
file:
filename: /configurations/dynamic.yml # 动态配置文件位置
certificatesResolvers:
lets-encr:
acme:
#caServer: https://acme-staging-v02.api.letsencrypt.org/directory
storage: acme.json
email: xxxxxx
httpChallenge:
entryPoint: web
4. 修改动态配置文件
文件路径为 ~/traefik/data/configurations/dynamic.yml
# Dynamic configuration
http:
middlewares:
nofloc:
headers:
customResponseHeaders:
Permissions-Policy: 'interest-cohort=()'
secureHeaders:
headers:
sslRedirect: true
forceSTSHeader: true
stsIncludeSubdomains: true
stsPreload: true
stsSeconds: 31536000
# UserName : admin
# Password : qwer1234
user-auth:
basicAuth:
# users 选项是认证用户的列表
# 使用 echo $(htpasswd -nb user password) | sed -e s/\\$/\\$\\$/g
# 来创建 user:password 键值对
users:
- 'admin:$apr1$tm53ra6x$FntXd6jcvxYM/YH0P2hcc1'
tls:
options:
default:
cipherSuites:
- TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
- TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
- TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305
- TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
minVersion: VersionTLS12
5. 解析域名
在 docker-compose.yml
中,我们指定了使用 traefik.yourdomain.com
作为访问域名。因此,我们需要将 traefik.yourdomain.com
解析至 traefik 服务入口 IP 地址。