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.