Skip to content

基础教程

在 Docker Swarm 上使用 Traefik 暴露服务 — 基础

本指南将帮助你开始使用 Traefik Proxy 在 Docker Swarm 上暴露服务。你将学习 HTTP 流量路由的基础、设置基于路径的路由,以及使用 TLS 保护服务。

前置条件

暴露你的第一个 HTTP 服务

让我们使用 whoami 应用程序暴露一个简单的 HTTP 服务。

更新你的 docker-compose.yml

yaml
services:
  whoami:
    image: traefik/whoami
    networks:
      - traefik_proxy
    deploy:
      replicas: 3
      labels:
        - "traefik.enable=true"
        - "traefik.http.routers.whoami.rule=Host(`whoami.swarm.localhost`)"
        - "traefik.http.routers.whoami.entrypoints=web,websecure"

部署栈:

bash
docker stack deploy -c docker-compose.yml traefik

验证你的服务

你的服务现在在 http://whoami.swarm.localhost/ 上可用。测试它是否工作:

bash
curl -H "Host: whoami.swarm.localhost" http://localhost/

你应该看到类似下面的输出:

Hostname: 1f2b3c4d5e6f
IP: 127.0.0.1
IP: ::1
IP: 10.0.0.5
...

这确认了 Traefik 正在成功地将请求路由到你的 whoami 应用程序(Swarm 中的多个副本之一)。

添加路由规则

部署第二个服务:

yaml
services:
  whoami-api:
    image: traefik/whoami
    networks:
      - traefik_proxy
    deploy:
      replicas: 2
      labels:
        - "traefik.enable=true"
        - "traefik.http.routers.whoami-api.rule=Host(`whoami.swarm.localhost`) && PathPrefix(`/api`)"
        - "traefik.http.routers.whoami-api.entrypoints=web,websecure"

部署更改:

bash
docker stack deploy -c docker-compose.yml traefik

测试基于路径的路由

验证不同路径是否路由到不同服务:

bash
# 根路径应转到主 whoami 服务
curl -H "Host: whoami.swarm.localhost" http://localhost/

# /api 路径应转到 whoami-api 服务
curl -H "Host: whoami.swarm.localhost" http://localhost/api

启用 TLS

让我们通过添加 TLS 来保护我们的服务。

创建自签名证书

生成自签名证书:

bash
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout certs/local.key -out certs/local.crt \
  -subj "/CN=*.swarm.localhost"

将证书作为 Docker Config 部署到 Swarm:

bash
docker config create whoami-tls-cert certs/local.crt
docker config create whoami-tls-key certs/local.key

更新 docker-compose.yml

yaml
services:
  whoami:
    image: traefik/whoami
    networks:
      - traefik_proxy
    deploy:
      labels:
        - "traefik.enable=true"
        - "traefik.http.routers.whoami.rule=Host(`whoami.swarm.localhost`)"
        - "traefik.http.routers.whoami.entrypoints=websecure"
        - "traefik.http.routers.whoami.tls=true"
    configs:
      - source: whoami-tls-cert
        target: /certs/local.crt
      - source: whoami-tls-key
        target: /certs/local.key
configs:
  whoami-tls-cert:
    external: true
  whoami-tls-key:
    external: true

部署更改:

bash
docker stack deploy -c docker-compose.yml traefik

适用场景

  • 多节点 Docker 集群:使用 Docker Swarm 部署应用
  • 多副本服务:自动处理多个副本的负载均衡
  • 高可用:通过 Swarm 的服务副本实现高可用

下一步

继续阅读 Swarm 高级指南 了解:

  • 添加中间件以增强安全性
  • 使用粘性会话
  • 多层路由
  • 服务中间件

在生产环境使用 Traefik OSS?

如果你在工作中使用 Traefik,可以考虑为其添加企业级 API 网关能力或获取 Traefik OSS 的商业支持。

基于 MIT 协议发布