本地服务HTTP转化为HTTPS本文使用Traefik:v2.3.4+Docker 搭建测试环境。

创建traefik 目录进行测试,以下创建目录处均在traefik的工作目录下运行;

halobug.cn为本机测试域名,可自行更换

目录结构 Center

1,traefik 配置文件

#新建traefik.toml 文件,(配置文件如下traefik.toml,traefik目录下)

# traefik.toml
[global]
  checkNewVersion = false
  sendAnonymousUsage = false

[log]
  level = "INFO"
  format = "common"
  filePath = "/data/basic/traefik/logs/traefik.log"

[api]
  dashboard = true
  insecure = true
  debug = false

[ping]

[accessLog]
  filePath = "/data/basic/traefik/logs/access.log"
  bufferingSize = 100

[providers]
  [providers.docker]
    watch = true
    exposedByDefault = false
    endpoint = "unix:///var/run/docker.sock"
    swarmMode = false
    useBindPortIP = false
    network = "traefik"
  [providers.file]
    watch = true
    directory = "/data/basic/traefik/confing"
    debugLogGeneratedTemplate = true

[entryPoints]
  [entryPoints.http]
    address = ":80"
  [entryPoints.https]
    address = ":443"

2,创建 config 配置目录

1.创建 config 目录;
2.进入config目录,新建default.toml文件,配置如下(default.toml);
default.toml
#default.toml
# 提供 Gzip 压缩
[http.middlewares.gzip.compress]

# tricks 实现,提供 HTTP 默认转发 HTTPS
# https://github.com/containous/traefik/issues/4863#issuecomment-491093096
[http.services]
  [http.services.noop.LoadBalancer]
     [[http.services.noop.LoadBalancer.servers]]
        url = "" # or url = "localhost"

[http.routers]
  [http.routers.https-redirect]
    entryPoints = ["http"]
    rule = "HostRegexp(`{any:.*}`)"
    middlewares = ["https-redirect"]
    service = "noop"

[http.middlewares.https-redirect.redirectScheme]
  scheme = "https"

2-1,创建 tls.toml 文件

#config 目录下
2-1.1.新建 tls.toml 文件 ,配置如下(tls.toml);
tls.toml
[tls]
  [tls.options]
    [tls.options.default]
      minVersion = "VersionTLS12"
      maxVersion = "VersionTLS12"
    [tls.options.test-tls13]
      minVersion = "VersionTLS13"
      cipherSuites = [
        "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
        "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
        "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
        "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305",
        "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
        "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
      ]

  [[tls.certificates]]
    # 此目录为docker-compose配置中,映射宿主机目录,证书生成在下一个步骤
    certFile = "/data/ssl/halobug.cn.crt"
    keyFile = "/data/ssl/halobug.cn.key"

3,创建docker-compose.yml文件,配置文件如下(docker-compose.yml)

# traefik 目录下
#docker-compose.yml

version: '3'

services:

  traefik:
    container_name: traefik
    image: traefik:v2.3.4
    restart: always
    ports:
      - 80:80
      - 443:443
    networks:
      - traefik
    command:
      - "--global.sendanonymoususage=false"
      - "--global.checknewversion=false"
      - "--entrypoints.http.address=:80"
      - "--entrypoints.https.address=:443"
      - "--api=true"
      - "--api.insecure=true"
      - "--api.dashboard=true"
      - "--api.debug=false"
      - "--ping=true"
      - "--log.level=warn"
      - "--log.format=common"
      - "--accesslog=false"
      - "--providers.docker=true"
      - "--providers.docker.watch=true"
      - "--providers.docker.exposedbydefault=false"
      - "--providers.docker.endpoint=unix:///var/run/docker.sock"
      - "--providers.docker.swarmMode=false"
      - "--providers.docker.useBindPortIP=false"
      - "--providers.docker.network=traefik"
      - "--providers.file=true"
      - "--providers.file.watch=true"
      - "--providers.file.directory=/etc/traefik/config"
      - "--providers.file.debugloggeneratedtemplate=true"
    volumes:
      # 仅限标准的 Linux 环境
      - /etc/localtime:/etc/localtime:ro
      - /etc/timezone:/etc/timezone:ro
      - /var/run/docker.sock:/var/run/docker.sock:ro
      # 映射配置文件
      - ./config/:/etc/traefik/config/:ro
      # 映射CA证书
      - ./ssl/:/data/ssl/:ro
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=traefik"
      # 默认请求转发 https 端口
      - "traefik.http.routers.traefik-dash-default.middlewares=https-redirect@file"
      - "traefik.http.routers.traefik-dash-default.entrypoints=http"
      - "traefik.http.routers.traefik-dash-default.rule=Host(`dashboard.halobug.cn`)"
      - "traefik.http.routers.traefik-dash-default.service=dashboard@internal"
      # 处理网页
      - "traefik.http.routers.traefik-dash-web.entrypoints=https"
      - "traefik.http.routers.traefik-dash-web.rule=Host(`dashboard.halobug.cn`) && PathPrefix(`/`)"
      - "traefik.http.routers.traefik-dash-web.tls=true"
      - "traefik.http.routers.traefik-dash-web.service=dashboard@internal"
      # 处理接口
      - "traefik.http.routers.traefik-dash-api.entrypoints=https"
      - "traefik.http.routers.traefik-dash-api.rule=Host(`dashboard.halobug.cn`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))"
      - "traefik.http.routers.traefik-dash-api.tls=true"
      - "traefik.http.routers.traefik-dash-api.service=api@internal"
    healthcheck:
      test: ["CMD-SHELL", "wget -q --spider --proxy off localhost:8080/ping || exit 1"]
      interval: 3s
      retries: 12
    logging:
      driver: "json-file"
      options:
        max-size: "1m"

networks:
  traefik:
    external: true

4,生成CA 证书

# traefik 目录下
Linux/Mac 下通用脚本

4.1 创建 ca.sh 文件 配置文件如下(ca.sh)

4.2 创建 ssl 目录

4.3 执行 sh ca.sh 

4.4 查看目录如下

Center br Center

ca.sh
# ca.sh
#!/bin/sh

OUTPUT_FILENAME="halobug.cn"

printf "[req]
prompt                  = no
default_bits            = 4096
default_md              = sha256
encrypt_key             = no
string_mask             = utf8only

distinguished_name      = cert_distinguished_name
req_extensions          = req_x509v3_extensions
x509_extensions         = req_x509v3_extensions

[ cert_distinguished_name ]
C  = CN
ST = BJ
L  = BJ 
O  = halobug.cn
OU = halobug.cn
CN = halobug.cn

[req_x509v3_extensions]
basicConstraints        = critical,CA:true
subjectKeyIdentifier    = hash
keyUsage                = critical,digitalSignature,keyCertSign,cRLSign #,keyEncipherment
extendedKeyUsage        = critical,serverAuth #, clientAuth
subjectAltName          = @alt_names

[alt_names]
DNS.1 = halobug.cn
DNS.2 = *.halobug.cn
DNS.3 = *.local.halobug.cn
DNS.4 = *.local-test.halobug.cn

">ssl/${OUTPUT_FILENAME}.conf

openssl req -x509 -newkey rsa:2048 -keyout ssl/$OUTPUT_FILENAME.key -out ssl/$OUTPUT_FILENAME.crt -days 3600 -nodes -config ssl/${OUTPUT_FILENAME}.conf
5,启动配置
# traefik 目录下
1: 绑定 hosts

127.0.0.1 dashboard.halobug.cn

2: 启动 docker-compose

docker-compose up -d

3:不出意外的话,访问http://dashboard.halobug.cn ,如下图所示

Center

到此http 转 https 就结束了,如出现证书无法挂在先排查ssl 目录是否映射到容器内!

6,启动Nginx 测试其他域名

# traefik 目录下
6.1 新建:docker-compose-nginx.yml(配置文件如下)
6.2 绑定:hosts 127.0.0.1 local.halobug.cn
6.2 启动:docker-compose -f docker-compose-nginx.yml up
6.3 成功如下图

#docker-compose-nginx.yml

version: "3.6"

services:

  local-halobug:
    image: nginx:1.19.4-alpine
    restart: always
    expose:
      - 80
    volumes:
      #- /etc/localtime:/etc/localtime:ro
      #- /etc/timezone:/etc/timezone:ro
      - ./logs:/var/log/nginx
    networks:
      - traefik
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=traefik"
      - "traefik.http.routers.local_halobug.entrypoints=https"
      - "traefik.http.routers.local_halobug.rule=Host(`local.halobug.cn`)"
      - "traefik.http.routers.local_halobug.tls=true"
      # - "traefik.http.services.local_halobug-backend.loadbalancer.server.scheme=http"
      # - "traefik.http.services.local_halobug-backend.loadbalancer.server.port=80"
    logging:
      driver: "json-file"
      options:
        max-size: "1m"
networks:
  traefik:
    external: true

6.3预览图 Center

欢迎大家实践!多多交流