Menjelajahi Traefik: Reverse Proxy untuk Docker

· 6 min read
Menjelajahi Traefik: Reverse Proxy untuk Docker
Photo by Thomas Jensen / Unsplash

Apa itu Traefik?

Ini adalah reverse proxy yang dirancang untuk bekerja dengan Docker. Ini memungkinkan Anda untuk mem-proxy layanan dalam container dengan cara yang sangat sederhana dan deklaratif. Pada awalnya, Anda mungkin terintimidasi oleh label, tetapi Anda akan terbiasa.

Mengapa Traefik dan bukan nginx, misalnya? Menurut kami Traefik lebih mudah dikelola. Ia hanya menggunakan docker=compose (bukannya ditambah nginx.conf dengan nginx), namun tetap memenuhi fungsinya.

Buat konfigurasi lalu lintas

Untuk memulai, kita harus membuat konfigurasi lalu lintas:

# traefik.yml 

 

# set log level 

log: 

  level: DEBUG 

 

# aktifkan dasbor dengan informasi berguna 

api: 

  dashboard: true 

  insecure: true 

 

# penyedia: dalam kasus kami, itulah yang kami proksi. 

# awalnya kita hanya membutuhkan Docker, 

# berikut cara mem-proxy layanan eksternal 

providers: 

  docker: 

# di sinilah Anda menentukan jaringan yang akan ditambahkan 

# layanan agar "diambil" oleh lalu lintas

    network: traefik 

    # turn off "auto-scraping" of containers by traffic 

    # otherwise it will try to proxy all containers 

    exposedByDefault: false 

 

# entry points are basically just ports that will access 

# to Traefik and therefore to the services it proxies 

entrypoints: 

  # this is the name of the entry point for regular http traffic, usually called 

  # http or web, but you can put anything in here 

  http: 

    # the number of entry port 

    address: :80 

    http: 

      # set up a redirect for all requests to the https entry point 

      redirections: 

        entryPoint: 

          to: https 

          scheme: https 

          permanent: true 

  # create a https entry point on port 443, usually called 

  # https or websecure 

  https: 

    address: :443 

 

# ssl certificate resolvers: this is used to get certificates for domains. 

# We have just one for now and later we will add another, called Wildcard Resolver 

certificatesResolvers: 

  simple-resolver: 

    acme: 

      # acme challenge type, we need it so that letsencript can understand that this is our 

      # domain we need to specify the entry point on which the challenge will run 

      # more info about challenges here https://letsencrypt.org/docs/challenge-types/ 

      httpchallenge: 

        entrypoint: http 

      # letsencript needs your email, it will send all sorts of information there, 

      # e.g. your certificate's about to go bad 

      email: [email protected] 

      # that's where Traefik will put the certificates, it's better to run volumetric 

      # that's what we'll do below 

      storage: /letsencrypt/acme.json 

 

accesslog: true 
# Dockerfile 

FROM traefik:v2.5.2 

 

WORKDIR /traefik 

 

COPY ./traefik.yml 

 

CMD ["traefik"] 

 

# docker-compose.yml 

 

version: "3.8" 

 

services: 

  traefik: 

    build: . 

    container_name: traefik 

    restart: always 

    ports: 

      # open ports for http, https, and dashboard of Traefik, 

      # the last one should not be exposed outside of your local network 

      # it will be accessible via ssh (see below) 

      - 80:80 

      - 443:443 

      - 127.0.0.1:8080:8080 

    volumes: 

      # traffic needs access to docker.sock to monitor the containers 

      - /var/run/docker.sock:/var/run/docker.sock:ro 

     # and here is the volumetric access to the certificates 

      - /data/letsencrypt:/letsencrypt 

    networks: 

      - traefik 

 

  # for the sake of example let's connect whoami, a simple service that displays 

  # information about the request in textual form 

  whoami: 

    image: "traefik/whoami" 

    restart: always 

    labels: 

      # enable Traefik for this container 

      - traefik.enable=true 

      # set Traefik network 

      - traefik.docker.network=traefik 

      # here is the fun part: adding a router and a rule for it 

      # in this case the router will be named whoami 

      # and will be available at example.com 

      # be sure to add the name of the router, it has to be 

      # be unique, in our case it is whoami (comes after 

      # traefik.http.routers.) 

      - traefik.http.routers.whoami.rule=Host(`example.com`) 

      # Set through which entry point the router will be accessible 

      - traefik.http.routers.whoami.entrypoints=https 

      # set certresolver 

      - traefik.http.routers.whoami.tls.certresolver=simple-resolver 

      # you don't actually have to specify the port explicitly 

      # traefik is able to figure out which port the service is listening on, 

      # It might happen that one container listens to several ports at the same time. 

      port listens to several # ports (e.g. rabbitMq does this), then you will 

      # to create several routers and specify explicitly several ports 

      - traefik.http.services.whoami.loadbalancer.server.port=80 

    networks: 

      - traefik 

 

# and the networks 

networks: 

  traefik: 

    external: 

      name: traefik 

Itu saja, sekarang Anda dapat menjalankannya dan berbahagia karena telah melakukannya.

Jika Anda ingin menyodok dashboard, Anda dapat melakukannya dengan meneruskan port melalui ssh

ssh -L 8080:localhost:8080 [email protected]

dan buka localhost:8080 di browser

dasbor traefik
dasbor traefik

Memproksi layanan eksternal

Anda tahu apa kekurangan tutorial Traefik ini? Informasi tentang layanan eksternal!

Traefik dapat digunakan tidak hanya untuk layanan di Docker, tetapi juga untuk layanan eksternal. Ini mendukung penyeimbangan beban, yaitu jika Anda memiliki layanan yang direplikasi, Anda cukup menentukan semua host dan Traefik akan melakukan sisanya.

Untuk mem-proxy layanan eksternal (di luar jaringan Docker), Anda perlu menambahkan penyedia di traefik.yml

# traefik.yml 

 

# ... 

 

providers: 

  docker: 

    network: traefik 

    exposedbydefault: false 

 

  # add a file provider that will pull in data from 

  # directory external 

  file: 

    directory: ./external 

Untuk layanan proxy di jaringan lokal, Anda harus menambahkan layanan docker-host, karena localhost di dalam container akan menunjuk ke jaringan container itu sendiri, bukan ke jaringan lokal mesin

# docker-compose.yml 

 

version: "3.8" 

 

services: 

  # ... 

  traefik: 

    # ... 

    networks: 

      - traefik 

      # add a shared network for the dockerhost and Traefik 

      - local 

 

 

  docker-host: 

    image: qoomon/docker-host 

    cap_add: [ "NET_ADMIN", "NET_RAW" ] 

    restart: always 

    networks: 

      - local 

 

# ... 

 

networks: 

  traefik: 

    external: 

      name: traefik 

  local: 

# Dockerfile 

 

FROM traefik:v2.5.2 

 

WORKDIR /traefik 

 

COPY ./traefik.yml 

# copy the folder with the external service configs 

COPY ./external 

 

CMD ["traefik"] 

Dan juga konfigurasi layanan eksternal itu sendiri (tempatkan semua konfigurasi di direktori eksternal).

# external/example.yml 

http: 

  services: 

    example-api: 

      loadBalancer: 

        servers: 

         # if the service is on an external host, 

         # we simply write ip or domain 

          - url: "http://123.456.789.123:4716" 

    example-web-client: 

      loadBalancer: 

        servers: 

         # if it’s on localhost, then type in docker-host 

          - url: "http://docker-host:8132" 

 

  routers: 

    example-web-client: 

      entryPoints: 

        - https 

      # the web client will be accessible via any paths on the domain 

      # web.example.com 

      rule: "Host(`site.example.com`)" 

      service: example-web-client 

      tls: 

        certResolver: simple-resolver 

    example-api: 

      entryPoints: 

        - https 

      # the api will only be available at site.example.com/api(.*) 

      # no need to add any additional rules for the webserver 

      # Traefik will route requests to /api, 

      # this works just like a css specificity 

      rule: "Host(`site.example.com`) && PathPrefix(`/api`)" 

      service: example-api 

      tls: 

        certResolver: simple-resolver 

 

Sertifikat Wildcard

Traefik juga bisa melakukan ini! Mari kita tulis ulang docker-compose.yml sehingga whoami dapat diakses oleh *.example.com.

Pertama, kita harus menambahkan wildcard-resolver ke konfigurasi lalu lintas.

# traefik.yml 

 

certificatesResolvers: 

  # ... 

  wildcard-resolver: 

    acme: 

      dnschallenge: 

        # specify the dns provider, in this example it would be godaddy, 

        # but Traefik knows how to work with others: 

        # https://doc.traefik.io/traefik/https/acme/#dnschallenge 

        provider: godaddy 

      email: [email protected] 

      storage: /letsencrypt/acme.jso 
# docker-compose.yml 

 

version: "3.8" 

 

services: 

  traefik: 

    build: ./proxy 

    container_name: traefik 

    restart: always 

    environment: 

      # specify the api keys of our provider from the environment variables 

      - GODADDY_API_KEY=${GODADDY_API_KEY} 

      - GODADDY_API_SECRET=${GODADDY_API_SECRET} 

      - GODADDY_POLLING_INTERVAL=10 

      - GODADDY_PROPAGATION_TIMEOUT=300 

    ports: 

      - 80:80 

      - 443:443 

      - 127.0.0.1:8080:8080 

    volumes: 

      - /var/run/docker.sock:/var/run/docker.sock:ro 

      - /data/letsencrypt:/letsencrypt 

    labels: 

      - traefik.enable=true 

      - traefik.http.routers.api.entrypoints=http 

    networks: 

      - local 

      - traefik 

 

  whoami: 

    image: "traefik/whoami" 

    restart: always 

    labels: 

      - traefik.enable=true 

      - traefik.docker.network=traefik 

     # change the rules for the router 

      - traefik.http.routers.whoami.rule="Host(`example.com`) || HostRegexp(`{subdomain:.+}.example.com`)" 

      - traefik.http.routers.whoami.entrypoints=https 

     # set wildcard-resolver 

      - traefik.http.routers.whoami.tls.certresolver=wildcard-resolver 

     # domains on which the resolver will receive the certificates 

      - traefik.http.routers.whoami.tls.domains[1].main=example.com 

      - traefik.http.routers.whoami.tls.domains[1].sans=*.example.com 

      - traefik.http.services.whoami.loadbalancer.server.port=80 

 

    networks: 

      - traefik 

 

    # ... 

Perangkat tengah

Traefik memungkinkan Anda membuat middleware dan menerapkannya pada router dan bahkan titik masuk!

Misalnya, jika Anda perlu menghapus beberapa layanan dari hasil pencarian, Anda selalu dapat melampirkan X-Robots-Tag: noindex, nofollow.

# docker-compose.yml 

 

# ... 

  whoami: 

    image: "traefik/whoami" 

    reboot: always 

    labels: 

      - traefik.enable=true 

      - traefik.docker.network=traefik 

      - traefik.http.routers.whoami.rule="Host(`example.com`) || HostRegexp(`{subdomain:.+}.example.com`)" 

      - traefik.http.routers.whoami.entrypoints=https 

      - traefik.http.routers.whoami.tls.certresolver=wildcard-resolver 

      - traefik.http.routers.whoami.tls.domains[1].main=example.com 

      - traefik.http.routers.whoami.tls.domains[1].sans=*.example.com 

      - traefik.http.services.whoami.loadbalancer.server.port=80 

      # Creating a middle-point software where 

      # noindex is a title 

      # headers are middleware types 

      - "traefik.http.middlewares.noindex.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow" 

      # Adding our middleware to the router. 

      - traefik.http.routers.whoami.middlewares=noindex@docker 

 

Anda dapat memiliki sejumlah middleware yang terpasang pada router Anda, dalam hal ini mereka harus ditentukan, dipisahkan dengan koma.

– “traefik.http.routers.whoami.middlewares=noindex@docker, sesuatu@docker, example@file”

Middleware juga dapat diterapkan tidak hanya pada router, tetapi juga pada seluruh titik masuk. Jika Anda tetap membuat middleware di label, Anda dapat melakukannya di Traefik sendiri.

# docker-compose.yml 

 

# ... 

 

  traefik: 

    # ... 

    labels: 

      - "traefik.enable=true" 

      - "traefik.docker.network=traefik" 

      - "traefik.http.routers.api.entrypoints=http" 

      - "traefik.http.middlewares.noindex.headers.customresponseheaders.X-Robots-Tag=noindex, nofollow" 

 

# ... 

 

And add in middleware traefik.yml to the entrypoint 

# traefik.yml 

 

# ... 

 

entrypoints: 

  http: 

    address: :80 

    http: 

      redirections: 

        entryPoint: 

          to: https 

          scheme: https 

          permanent: true 

  https: 

    address: :443 

    # add http middleware 

    http: 

      middlewares: 

        - "noindex@docker" 

 

# ... 

Kesimpulan

Ini adalah tutorial singkat kami tentang Traefik. Kami harap Anda mempelajari sesuatu yang baru atau setidaknya memahami betapa hebat dan multifungsinya Traefik. Kita bisa saja terus membahas tentang Traefik, namun akan lebih baik jika Anda membaca  🙂dokumentasi resmi

Sekian Terimakasih...