Reverse proxy Docker applications and applications with Let's Encrypt and Traefik @ Cédric Walter | Wednesday, Feb 28, 2024 | 7 minutes read | 1449 Words | Update at Thursday, Feb 29, 2024

Traefik, a modern reverse proxy and load balancer, has gained significant traction in recent years owing to its simplicity and versatility. Built with cloud-native environments in mind, Traefik excels in dynamically managing routing, handling SSL certificates, and integrating seamlessly with container orchestrators like Kubernetes and Docker.

Key Features of Traefik:

  • Automatic Configuration: Traefik stands out for its automatic configuration capabilities, dynamically discovering services as they are added or removed from the infrastructure.
  • Let’s Encrypt Integration: With built-in support for Let’s Encrypt, Traefik simplifies the process of securing web applications by automatically provisioning and renewing SSL certificates.
  • Load Balancing: Traefik efficiently distributes incoming traffic across multiple instances of an application, ensuring optimal performance and reliability.
  • Service Discovery: Traefik supports various service discovery mechanisms, including Docker, Kubernetes, and Consul, making it well-suited for dynamic environments.

How does Traefik compare to Nginx proxy manager?

Choosing between Traefik and Nginx Proxy Manager ultimately depends on your specific requirements and preferences. Here are some considerations to help you decide:

  • Complexity vs. Simplicity: Traefik offers robust features for dynamic environments but may have a steeper learning curve, especially for beginners. Nginx Proxy Manager, with its user-friendly interface, provides a more straightforward setup process.
  • Scalability and Performance: Traefik’s automatic configuration and support for container orchestration platforms make it well-suited for scalable and dynamic environments. However, Nginx Proxy Manager can also handle significant loads efficiently, particularly when properly configured.
  • Community and Support: Both Traefik and Nginx Proxy Manager have active communities and extensive documentation.

Ready to integrate with Authentik

One of the popular authentication providers that Traefik integrates with is Authentik. Authentik is an open-source authentication and authorization service that provides Single Sign-On (SSO) capabilities, making it easier to manage user access across multiple applications.

Here’s how Traefik can integrate with Authentik:

  • Traefik Forward Authentication Middleware: Traefik provides a Forward Authentication middleware that can be configured to delegate authentication to an external service before allowing access to protected resources. This middleware acts as a gatekeeper, intercepting incoming requests and verifying the user’s identity before forwarding the request to the backend application.
  • Authentik Configuration: To integrate Traefik with Authentik, you need to configure Traefik to use Authentik as the authentication provider. This typically involves specifying the URL of the Authentik server and configuring any required authentication parameters, such as client ID and client secret.
  • Authentication Flow: When a user attempts to access a protected resource served by Traefik, Traefik intercepts the request and redirects the user to the Authentik login page. The user then authenticates with Authentik using their credentials. Once authenticated, Authentik generates a token or session identifier, which is returned to Traefik.
  • Authorization Check: Traefik validates the token or session identifier received from Authentik to ensure that the user is authenticated. If the validation is successful, Traefik allows the request to proceed and forwards it to the backend application. If the validation fails, Traefik denies access and returns an authentication error.
  • Session Management: Traefik can also manage user sessions by storing session information and associating it with subsequent requests from the same user. This allows Traefik to maintain user authentication state and avoid prompting the user to log in repeatedly during a session.

By integrating Traefik with Authentik, you can centralize authentication and authorization for your web applications and services, streamlining the user authentication process and enhancing security. Additionally, Traefik’s flexible middleware architecture and support for various authentication providers make it easy to integrate with Authentik and other identity management solutions, allowing you to customize authentication workflows to suit your specific requirements.

Prepare Cloudflare

Securing a Docker container with Let’s Encrypt and Traefik is really easy these days.

Create as many DNS proxy as required, one for each docker container you wan to expose.

e.g of 2 Cloudflare DNS proxy:

  • plex.mydomain.com
  • homarr.mydomain.com

Pointing to your router public IP, use https://www.whatsmyip.org to find your public IP

Prepare your router

  • Your home router will have a Port Forwarding section somewhere. Log in and find it, most of the time under the menu “NAT” or “Port Forwarding”
  • Add port forwarding for port 80 and 443 to the server IP running the Traefik docker container

Insttall Traefik

traefik-architecture

Create a docker-compose.yml file similar to this one:

version: '3.8'
services:
  traefik:
    image: "traefik:v2.11"
    container_name: traefik
    restart: unless-stopped
    environment:
      - PUID=0 # root user
      - PGID=0 # root user group
      - TZ=Europe/Zurich # change to your location
    networks:
      - traefik_proxy
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080" # dashboard, you can remove it in production
    volumes:
      - /root/docker/traefik/letsencrypt:/letsencrypt # where letsencrypt certs are saved
      - /var/run/docker.sock:/var/run/docker.sock:ro  # mandatory for docker integration
      - /root/docker/traefik/traefik.yml:/traefik.yml:ro # static configuration file
      - /root/docker/traefik/dynamic_conf.yml:/dynamic_conf.yml # dynamic configuration file
networks:
  traefik_proxy:
    external: true

Configure Traefik static file

Traefik use a static configuration file (any changes in it and you need to restart the Traefik container) Create a /root/docker/traefik/traefik.yml file similar to this one:

# Api and, additionally, a monitoring dashboard (checkout docs for more,
# disable in production if not required!).
global:
  checkNewVersion: true
  sendAnonymousUsage: true

api:
  dashboard: true
  insecure: true

log:
  level: DEBUG

# Entrypoints (ports) Traefik should listen to; here we define two: "http"
# for unencrypted traffic, and "https" for SSL-encrypted traffic (port 443).
entryPoints:
  http:
    address: ":80"
  https:
    address: ":443"

# We define two providers
providers:
  # First, a docker provider, which allows us to enable routing to any Docker
  # container by setting some specific labels on the container. Example will
  # follow below ;).
  docker:
    endpoint: "unix:///var/run/docker.sock"
    # This ensures, that we manually have to request containers to be "added"
    # to Traefik.
    exposedByDefault: false
    network = "traefik_proxy"
  # Second, a dynamic configuration file - we'll come back to that file below.
  file:
    filename: "/dynamic_conf.yml" # this is mapped in traefik volume

# For automatic Let's Encrypt certificate generation, we define a "letsencrypt"
# resolver. It may store the certificates in the defined file/storage and should
# use the http endpoint (defined above) for the http challenge (i.e., for
# generating/ requesting the certificates).
certificatesResolvers:
  letsencrypt:
    acme:
      email: [email protected] # use a valid email for letsencrypt!
      storage: "/letsencrypt/acme.json"
      httpChallenge:
        entryPoint: http

experimental:
  plugins:
    fail2ban:
      moduleName: "github.com/tomMoulard/fail2ban"
      version: "v0.7.1"

Configure Traefik dynamic file

Traefik use a dynamic configuration file (any changes in it and you DON’T need to restart the Traefik container) Create a /root/docker/traefik/dynamic_conf.yml file similar to this one:

tls:
  options:
    default: # minimum TLS version 1.2
      minVersion: VersionTLS12
      cipherSuites:
        - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
        - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
        - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305
        - TLS_AES_128_GCM_SHA256
        - TLS_AES_256_GCM_SHA384
        - TLS_CHACHA20_POLY1305_SHA256
      curvePreferences:
        - CurveP521
        - CurveP384
      sniStrict: true

http:
  middlewares:
    secureHeaders:
      headers:
        browserXssFilter: true
        contentTypeNosniff: true
        frameDeny: true
        sslRedirect: true
        # HSTS Configuration
        stsIncludeSubdomains: true
        stsPreload: true
        stsSeconds: 31536000
        customFrameOptionsValue: "SAMEORIGIN"
    my-fail2ban:
      plugin:
        fail2ban:
          rules:
            bantime: 3h
            enabled: "true"
            findtime: 10m
            maxretry: "4"
          whitelist:
            ip: ::1,127.0.0.1

Access Dashboard

Start Traefik container now by running

docker-compose up -d

# If using docker-compose-plugin
docker compose up -d

You can now accss this Traefik container under http://docker-server-ip:8080

Reverse proxy calibre-web with Traefik

We just need to annotate with labels all container that we want to reverse proxy.

Create a docker-compose.yml file similar to this one:

  • Change subdomain.domain.com to your cloudflare DNS
  • Note that service name calibre-web and container name calibre-web must match in labels
version: '3.8'
services:
  calibre-web:
    image: lscr.io/linuxserver/calibre-web:latest
    container_name: calibre-web
    logging:
      driver: "journald"
      options:
        tag: "calibre-web"
    environment:
      - PUID=1000
      - PGID=1000
      - TZ=Europe/Zurich
    volumes:
      - /root/docker/calibreweb:/config
      - /media/calibreweb:/books
    ports:
      - 8090:8083
    restart: unless-stopped
    labels:
      - "traefik.enable=true"
      - "traefik.docker.network=traefik_proxy"
      # Http (Only redirect to HTTPS)
      - "traefik.http.routers.calibre-web.entrypoints=http"
      - "traefik.http.routers.calibre-web.rule=Host(`subdomain.domain.com`)"
      - "traefik.http.middlewares.calibre-web-https-redirect.redirectscheme.scheme=https"
      - "traefik.http.routers.calibre-web.middlewares=calibre-web-https-redirect"
      # Https
      - "traefik.http.routers.calibre-web-secure.entrypoints=https"
      - "traefik.http.routers.calibre-web-secure.rule=Host(`subdomain.domain.com`)"
      - "traefik.http.routers.calibre-web-secure.tls=true"
      - "traefik.http.routers.calibre-web-secure.tls.certresolver=letsencrypt"
      - "traefik.http.routers.calibre-web-secure.service=calibre-web"
      - "traefik.http.routers.calibre-web-secure.middlewares=secureHeaders@file"
      # Service
      - "traefik.http.services.calibre-web.loadbalancer.server.port=8083" # optional, Traefik would locate the internal port
      - "traefik.http.services.calibre-web.loadbalancer.server.scheme=http"
    networks:
      - traefik_proxy
networks:
  traefik_proxy:
    external: true

Reverse proxy native jellyfin with Traefik

  • If you start Jellyfin using Docker, just add labels like we did above for Calibre-Web
  • If you start Jellyfin natively on linux, installed with RPM, Bash, or Snap.

Add at the end of /root/docker/traefik/dynamic_conf.yml file this snippet:

  • replace ipadress:8096 with Jellyfin server ip and port
  • replace subdomain.domain.com with DNS name of Cloudflare
routers:
    jellyfin:
      rule: "Host(`subdomain.domain.com`)"
      service: "jellyfin"
      entryPoints:
        - "http"
        - "https"
      tls:
        certResolver: "letsencrypt"
      middlewares:
        - "redirect-to-https@file"

  middlewares:
    redirect-to-https:
      redirectScheme:
        scheme: "https"
        permanent: true

  services:
    jellyfin:
      loadBalancer:
        servers:
          - url: "http://ipadress:8096"

You do not need to restart Traefik (we changed dynamic config), first access to Jellyfin may failed, as letsencrypt take a few second to be created on demand.

Conclusions

You can now add as many proxy host as you want, and annotate each docker container to use that DNS host name.

By following these steps, you can secure any Docker coontainer with HTTPS using Treafik and Let’s Encrypt. This setup automates the process of obtaining and renewing SSL/TLS certificates, making it easier to secure your Docker services.

Related content

Dynamic IP at home, no problem with ddclient and Cloudflare

Dynamic IP at home, no problem with ddclient and Cloudflare

Thursday, Feb 29, 2024

ddclient is an open-source Perl-based client used to update dynamic DNS entries for various DDNS service providers. It supports a wide range of protocols, including DynDNS, No-IP, DuckDNS, Cloudflare, and many others, making it a flexible choice for users with diverse needs.
3 minutes read
Securing a Docker registry with Let's Encrypt and Nginx-proxy

Securing a Docker registry with Let's Encrypt and Nginx-proxy

Tuesday, Jan 30, 2024

Securing Docker containers with Let’s Encrypt and Nginx-proxy-manager involves setting up a reverse proxy with SSL termination using nginx-proxy and obtaining SSL/TLS certificates with the help of letsencrypt
3 minutes read
Homelab - dont rely on services where YOU are the product

Homelab - dont rely on services where YOU are the product

Friday, Dec 22, 2023

A homelab, short for home laboratory, refers to a setup where individuals or hobbyists create a small-scale computing or networking environment in their homes for various purposes. The goal is typically to gain hands-on experience, test and learn about different technologies, and build skills related to IT, networking, server administration, and more. Homelabs can vary widely in complexity and purpose, depending on the interests and goals of the individual setting them up!
12 minutes read

© 1997 - 2024 Cédric Walter blog

Powered by Open Sources technologies

avatar

Cédric WalterA true selfless act always sparks another

6s a1 acide-hyaluronique acma adaptability advocate-for-change ai airplane algorand alice-hlidkova-author alpine alps altruism-vs-commercialization antique-scooters antiseptic-rinse apache arcade arcade-gaming armattan art artemis artemis-viper artistic-expression atlassian authenticity-in-writing authenticity-matters avis bag bambulab bash bean bennu bernardet bestwishes betaflight betruger beware bien-vivre bien-être bien-être-physique bio bioethics bitcoin blessures-sportives blockchain blockchain-consensus-encyclopedia blockchain-systems blog book-review books bots Bought box brand-authenticity brand-integrity brand-protection breaking-barriers business-management business-milestones business-strategy business-success business-transformation businessbooks byzantine-fault-tolerance calculator calibre calibre-web camera case-studies cc2500 cgm-next challenges changement-de-vie channel-setup cheaper cherry-blossoms chirurgie-orthopédique choosing-fbl-gyro ci/cd classic-games classic-scooters classic-vespa climb climbing codefest collectible-scooters collectibles collection collector color competition consensus-algorithms consensus-mechanisms console consommation-responsable consumer-awareness containerization contest control-surfaces controller copy corticostéroïdes counterfeit-awareness counterfeit-culture counterfeit-market counterfeit-vs-authentic covid19 creating croissance-personnelle cryptocurrency cultural-experience cultural-richness curve-adjustments customer-discovery cve-issues dance-dreams death decentralization decentralized dental-hygiene dependency Design development devfest devops distributed-ledger-technology diverse-perspectives diy-dental diy-health dji docker docker-compose docker-hosting docker-networking docker-registry docker-security dont-buy dotnet Download downloading dreams-and-reality drone dynamic-ip désencombrement développement-personnel développement-spirituel ecology edgetx elrs elta emotional-challenges emotional-hurdles empowering-narrative endpoints engelberg Ensitm entrepreneurial-lessons entrepreneurial-mindset entrepreneurs entrepreneurship entrepreneurship-books Essaim essentially ethereum ethical-dilemmas evoque execution exercices-de-renforcement exercise-form facebook failure-analysis failure-stigma failure-to-success fake fake-apparel fake-brands fake-goods family family-building family-dynamics fashion-ethics fashion-fraud fbl-controllers fbl-system-compatibility fbl-system-features fbl-system-reviews fertility-struggles finance-books finances-personnelles financial-modeling financiallanning firearm firmware-customization firmware-issues fissure-horizontale fitness-routine fitness-tips flexibilité flight-controller flybarless-advantages flybarless-systems foss fpv frame France freestyle fresh-breath friendship-goals front gallery game-music gameplay-mechanics gamer-community games gaming-culture gaming-enthusiast gaming-history gaming-legacy gaming-nostalgia generative-ai genou gestion-de-ladouleur gestion-du-temps git global-impact google green-tea green-tea-mouthwash growth-hacking-books growth-mindset guide hackathon hackday hackfest health-and-wellness helicopter helicopter-community helicopter-gyro helicopter-tuning herbal-mouthwash hewlettpackard historical-scooters hobbies hobby hobbyist-blog holidays holistic-oralcare hollidays home-remedy home-workouts homelab homemade-oralcare honda honesty honey hornet how-to howTo https hugo human-connection hygiene-routine icecream iconic-scooters iflight iflightnazgulevoque immich indoor industrial-shit industry injections-intra-articulaires injury-prevention innovation innovation-books innovation-journey ios japan-travel japanese-cuisine jar java jdk11 jellyfin joint-health junit jupiter kitchen knee-rehabilitation knee-stability knockoff-alert kyoto lacoste lacoste-counterfeit lambretta landmarks leadership leadership-books lean-startup learning-from-failure leg-day leg-workouts legal-complexities legit-fashion let's-encrypt libération life-transformations link linux llm local-traditions m2evo macos magical-adventure magician-lord main make manurhin manurhin-sm75 mapping marathon market-research marketing-books maven me medical medical-advancements metakernel miami-entertainment mid-century-scooters migration mindset-shifts minimalisme minimum-viable-product minty-fresh mixer-settings mk3 mk4 mobilité model-setup modern-family modern-motherhood moon moral-encounters motherhood-dilemmas motorcycle mount mountain mountains mouth-rinse mouthwash-ingredients mouthwash-recipe Mulhouse muscle-activation music mvs mycollection ménisque NASA natural-mouthwash nature nazgul neo-geo-aes neogeo network new-bookrelease nginx-proxy north-face north-face-replica nostalgic-scooters nv14 objectifs old-school-scooters omphobby open-source open-source-rc opensource opentx openvpn oral-care oral-health organizer osaka oss overcoming-challenges p1p p1s parental-rights parenthood-reflections parts passion patella-health persistence personal-relationships photos physical-therapy physiothérapie pivot-strategy pixel-art planet plasma-riche-en-plaquettes platform plex pluto pretty-girl-complex privacy product-market-fit productivity-books proof-of-stake proof-of-work protect-your-style prusa prusa-research public-image quadcopter quadriceps-strength radio-control radio-programming radiomaster rare-scooters raspberrypi raspbian rates-configuration rc rc-community rc-configuration rc-firmware RC helicopter rc-helicopter-electronics rc-helicopter-enthusiasts rc-helicopter-setup rc-helicopter-technology rc-helicopter-tips rc-helicopters rc-modeling rc-simulator realdebrid realflight receiver reflex-xtr refreshing-breath rehabilitation-exercises relations-personnelles relationship-complexities released remote remote-control-flying reproductive-ethics resilience-in-business resilient-women restored-scooters retro-gaming retro-gaming-community retro-gaming-console retro-scooters reverse-proxy rhythms-of-life risk-management robotic router rx réadaptation rééducation sab sab-raw-420 sab-raw-580 sab-raw-700 sales-books santé-articulaire santé-mentale scooter-enthusiast scooter-memorabilia scooters security-nightmare self-leveling-helicopter server-configuration servo-config skydiving snk snk-corporation snk neo geo soap social-issues solex space spams sport ssl-termination ssl/tls startup-books startup-failure static-code-generator steam strategic-networking streaming strength-training success-stories sun support surrogacy-agency surrogacy-journey surrogacy-narratives swiftui swiss switzerland team team-building team-dynamics teeth-cleaning temples-and-shrines tendermint terrot thérapie-physique tokyo torvol traefik traitement-des-fissures transmitter transmitter-firmware travel travel-tips trouver-du-sens tunnel turning-setbacks-into-success tutorial tx unconventional-strategies vacation velosolex vespa viaferrata video video-game-review vintage vintage-scooters vintage-two-wheelers vintage-vespa vintagegaming vmo-exercises warez web-security wind winner winterthur women-supporting-women wordpress workout-progression x1c zurich zyxel zyxel-avoid zyxel-not-serious-with-security zyxel-outdated zyxel-router-not-good équilibre
Me

Cédric Walter is a French-Swiss entrepreneur, investor, and software engineer based in Zurich, Switzerland. He spent his career developing software applications for Swiss insurance companies to handle billions of dollars in premiums. He cofounded Innoveo AG and as the software architect developed the no-code platform designed to reduce the manual coding that powers many software apps. As an active participant in the European hacking community, he works on many open source projects including blockchain. Cédric is a winner of multiple hackathons. His expertise include designing back end, event-based, and blockchain systems. Cédric is also the founded Disruptr GmbH, a software development company that offers full spectrum of services for businesses of all sizes.

JAVA full-stack developer since 2000, in Blockchain since 2017, Certified Scrum Master 2012, Corda Certified Developer in 2019, Ethereum smart contract expert in the SWISS Blockchain Security working group

Hackathons

  • HackZurich 2022 – Level Up in top 25 finalist among 134 submissions
  • SBHACK21 – SwiFi winner of best Solution on Algorand, overall Winner 3rd Prize, CV Labs Fast Track Ticket
  • HackZurich 2020 Europe’s Biggest Hackathon winner in category Migros
  • SBHACK19 – LendIt winner of Swiss biggest Blockchain Hackathon. On chain insurance and ledger for agricultural land soil.
  • Member of the Bitcoin Association Switzerland and Cryptovalley association Switzerland,

PGP: DF52 ADDA C81A 08A6

Copyright information

All editorial content and graphics on our sites are protected by U.S. copyright, international treaties, and other applicable copyright laws and may not be copied without the express permission of Cedric Walter, which reserves all rights. Reuse of any of Cedric Walter editorial content and graphics for any purpose without The author ’s permission is strictly prohibited.

DO NOT copy or adapt the HTML or other code that this site creates to generate pages. It also is covered by copyright.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.

Disclaimer: The editor(s) reserve the right to edit any comments that are found to be abusive, offensive, contain profanity, serves as spam, is largely self-promotional, or displaying attempts to harbour irrelevant text links for any purpose.

Others

If you like my work or find it helpful, please consider buying me a cup of coffee ☕️. It inspires me to create and maintain more projects in the future. 🦾

It is better to attach some information or leave a message so that I can record the donation 📝 , thank you very much 🙏.

Reproduction without explicit permission is prohibited. All Rights Reserved. All photos remain copyright © their rightful owners. No copyright infringement is intended.