traefik代理给nginx加ssl证书

traefik开启https,请求进入后跳转:80–>443,通过traefik后,是以http方式请求后端服务

运行

docker-compose文件如下:

version: "2"
services:
  proxy:
    image: traefik
    command: --web --docker --logLevel=DEBUG
    networks:
      - webgateway
    ports:
      - "80:80"
      - "8080:8080"
      - "443:443"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - ./traefik.toml:/etc/traefik/traefik.toml
      - ./ssl/nginx.crt:/ssl/nginx.crt
      - ./ssl/nginx.key:/ssl/nginx.key
    labels:
      - "traefik.enable=false"
  nginx:
    image: nginx:1.14.2-alpine
    networks:
      - webgateway
    volumes:
      - ./http.conf:/etc/nginx/conf.d/default.conf
      - ./index.html:/code/backend/web/index.html
      - ./index.php:/code/backend/web/index.php
    labels:
      - "traefik.backend=php"
      - "traefik.frontend.rule=Host:test.example.com"
      - "traefik.port=80"
  admin_fpm:
    image: php:7.2-fpm-alpine
    volumes:
      - ./index.php:/code/backend/web/index.php
    networks:
      - webgateway
    labels:
      - "traefik.enable=false"
networks:
  webgateway:
    driver: bridge

traefik.toml

# 入口开启http https
defaultEntryPoints = ["http","https"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      entryPoint = "https"
  [entryPoints.https]
  address = ":443"
    [entryPoints.https.tls]
      [[entryPoints.https.tls.Certificates]]
        certFile = '/ssl/nginx.crt'
        keyFile = '/ssl/nginx.key'

http.conf

server {
    listen 80;

    root /code/backend/web;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
        try_files $uri = 404;
    }
    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass admin_fpm:9000;
        try_files $uri =404;
    }
}

测试

打开浏览器访问 test.example.com,看证书是否生效

要点

  • 关键是traefik入口要开启https
  • traefik.enable=false" # 不让不相关容器在UI上显示

你可能感兴趣的:(nginx,docker,traefik)