Cart

    Sorry, we could not find any results for your search querry.

    Installing and using Traefik in Kubernetes

    Helm Charts are updated regularly, which means that the names and positions of variables may change. Therefore, we cannot guarantee that every article is always completely up to date. If you notice that certain information is no longer correct, please let us know. 

    Official Traefik Helm Repository

     

    Traefik is a popular open-source reverse proxy and load balancer, designed for microservices and containerized applications. Traefik can automatically discover the services running in a Kubernetes cluster and route traffic to these services using various load balancing algorithms.

    Traefik operates on behalf of other services within your cluster. With Traefik, you can host multiple applications on a Kubernetes cluster where the traffic is routed through Traefik. Traefik can then function as a single load balancer for all these applications and additionally provide Let's Encrypt SSL certificates.

    In this guide, we will show you how to install and use Traefik. We optionally use your own (sub)domain to connect Traefik and secure it with an SSL certificate. To log in to the Traefik dashboard, we set up a username and password.

    For this guide, you will need:

     

     

    Installing Traefik

     

    Step 1

    Add the official Traefik repository and update your Helm repositories so that you can use them:

    helm repo add traefik https://helm.traefik.io/traefik 
    helm repo update

     

    Step 2

    Traefik can generate Let's Encrypt certificates for applications that communicate via Traefik. In this guide, we assume that you want to use this for your use case as well. For this, you use an ACME DNS challenge provider. We support this option via our API. Please note that the provider you choose must support this functionality and that the domains you use are registered with that provider in the account you use for this guide.

    Create a directory where you will store your TransIP API key, for example:

    mkdir transip

    Then, create a file in the newly created directory containing a private key for your TransIP API account, for example:

    cat << EOF > transip/transip.key
    -----BEGIN PRIVATE KEY-----
    MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQDKoaYJtbVnJw58
    PYGH8WIJ7ZjWd2lke0IbMV+dNGs=
    -----END PRIVATE KEY-----
    EOF

    In this example, only a small fragment of a private key is included. Your private key will be much longer.


     

    Step 3

    Create a namespace for Traefik within your cluster:

    kubectl create ns traefik

     

    Step 4

    Generate a secret based on your API Private Key that Traefik can use to communicate with the TransIP API. Replace the following details if necessary:

    • -n traefik: Use the name of the namespace you created in step 3.
    • transip/transip.key: Change to the directory and filename you created in step 2.
    kubectl create -n traefik secret generic transip-key --from-file transip/transip.key

     

    Step 5

    Speaking of secrets: if you configure Traefik to be accessible via the public internet, it will by default have no password and/or username. For this, we create another secret containing a username and password to log in to the Traefik dashboard. 

    Generate a username and password with htpasswd:

    htpasswd -nb <username> <password> >> htpasswd.txt

    The contents of the htpasswd.txt file will look roughly as follows:

    demouser:$2a$13$2QBmxHS5a1hWU9aeyJ.DPNWRFjXcNRNTjcu56QTLhZS.y

    Using Windows to follow these steps? Then use our htpasswd tool to generate an htpasswd username and password. Save the output in a file in the folder where you are executing the commands in this guide, for example c:\Users\Administrator\kubernetes\htpasswd.txt

    Then generate the secret based on the contents of the file you just created:

    kubectl create secret generic traefik-dashboard-basicauth --from-file=users=htpasswd.txt -n traefik

     

    Step 6

    For the installation of Traefik, in the next step you use the official Helm Chart. In an additional .yaml file, make a few adjustments; create a .yaml file, for example:

    nano traefik.yaml

    Give the file the following content, adjusting a few values:

    • example@transip.nl: Change to your email address
    • jouwaccount: Change "jouwaccount" to the name of your TransIP account.
    • /transip/transip.key: Change (if necessary) to the directory and filename you created in step 2.
    • traefik.transip.nl: Change to the (sub)domain where you want to attach Traefik.
    deployment:
      initContainers:
        - name: volume-permissions
          image: busybox:latest
          command: ["sh", "-c", "touch /data/acme.json; chmod -v 600 /data/acme.json"]
          volumeMounts:
          - mountPath: /data
            name: data
    podSecurityContext:
      fsGroup: 65532
      fsGroupChangePolicy: "OnRootMismatch"
    additionalArguments:
      - "--certificatesresolvers.myresolver.acme.email=example@transip.nl"
      - "--certificatesresolvers.myresolver.acme.dnschallenge.provider=transip"
      - "--certificatesresolvers.myresolver.acme.dnschallenge.delaybeforecheck=120"
      - "--certificatesresolvers.myresolver.acme.storage=/data/acme.json"
      - "--providers.kubernetescrd.namespaces="
    env:
      - name: TRANSIP_ACCOUNT_NAME
        value: jouwaccount
      - name: TRANSIP_PRIVATE_KEY_PATH
        value: /transip/transip.key
    volumes:
      - name: transip-key
        mountPath: "/transip"
        type: secret
    persistence:
      enabled: true
      size: 128Mi
    ports:
      websecure:
        tls:
          enabled: true
        expose:
          default: true
        exposedPort: 443
    ingressRoute:
      dashboard:
        enabled: true
        entryPoints:
          - websecure
        matchRule: Host(`traefik.transip.nl`) && (PathPrefix(`/api`) || PathPrefix(`/dashboard`))
        tls:
          certResolver: myresolver
        middlewares:
          - name: "dashboard-auth"
            namespace: "traefik"
    extraObjects:
      - apiVersion: traefik.io/v1alpha1
        kind: Middleware
        metadata:
          name: dashboard-auth
          namespace: traefik
        spec:
          basicAuth:
            secret: "traefik-dashboard-basicauth"
    podAnnotations:
      prometheus.io/port: "8082"
      prometheus.io/scrape: "true"
    providers:
      kubernetesIngress:
        publishedService:
          enabled: true
    priorityClassName: "system-cluster-critical"
    image:
      registry: docker.io
      repository: traefik
    tolerations:
      - key: "CriticalAddonsOnly"
        operator: "Exists"
      - key: "node-role.kubernetes.io/control-plane"
        operator: "Exists"
        effect: "NoSchedule"
      - key: "node-role.kubernetes.io/master"
        operator: "Exists"
        effect: "NoSchedule"

    Explanation of the Code

    For a complete overview of the available options, see the official Helm chart. In a nutshell, the different parts are as follows:

    • deployment.initcontainers: Out of the box, Traefik is configured not to have permissions to write SSL certificates to the default file /data/acme.json. This section ensures that Traefik gains read and write permissions by adjusting the permissions with a chmod command.
    • podsecuritycontext: Ensures that every volume has the correct owner (65532).
    • additionalArguments: The specified values indicate which email address notifications regarding the generation of SSL certificates are sent to, that you are using TransIP’s systems (via our API) to generate Let's Encrypt certificates, how often they are renewed, where they are stored, and that Traefik monitors and can use all namespaces.
    • env: Information regarding your TransIP API credentials (from steps 2 and 4).
    • volumes: This is where you configure additional volumes (a type of disk); in this case, the /transip volume to store your API credentials.
    • persistence: Ensures that the volume used to store the SSL certificates (/data) is retained when you delete your Traefik installation. In this .yaml file, this option is enabled. 
    • ports:The configuration regarding the use of Traefik via SSL (whether it can be used, on which port, etc.).
    • ingressRoute: An IngressRoute ensures that incoming network requests reach the correct services. 
    • extraObjects: Adds additional components to your Traefik setup. In this setup, you add a Middleware that ensures that when you access the Traefik dashboard in your browser, you are prompted for a password as defined in the traefik-dashboard-basicauth secret (which you created in step 5).
    • podAnnotations:Additional labels to attach to the Traefik pod, in this case to enable the use of Prometheus in conjunction with Traefik.
    • providers: Enables Traefik to discover Kubernetes Ingress resources. This option is enabled by default in the official Helm Chart. We have included it here just in case Traefik decides to disable this option by default at a later date.
    • priorityClassName: Sets a priority class for Traefik. If Kubernetes, for any reason, needs to choose which Pods get priority when being scheduled, a Pod with a higher priority will take precedence.
    • image: Specifies which image is used to create the Traefik deployment.
    • tolerations: Certain pods are not allowed to be scheduled on a node with a taint unless the pod has a toleration for that specific taint, see our article on taints & tolerations.
     
     

     

    Step 7

    Install the Traefik Helm Chart using the command below.

    helm install -f traefik.yaml traefik traefik/traefik -n traefik
    • helm install: Installs the Helm Chart.
    • -f traefik.yaml: The file from step 5 that customizes the installation.
    • traefik: The name of the Helm release, which you can check with the command 'helm list'.
    • traefik/traefik: The repository name and the Helm Chart to be installed, respectively.
    • -n traefik: The namespace in which the Helm release is installed, see step 3.

    You will now see a confirmation that looks roughly as follows:

    NAME: traefik
    LAST DEPLOYED: Wed Feb 12 09:22:05 2025
    NAMESPACE: traefik
    STATUS: deployed
    REVISION: 1
    TEST SUITE: None
    NOTES:
    traefik with docker.io/traefik:v3.3.3 has been deployed successfully on traefik namespace !
    🚨 When enabling persistence for certificates, permissions on acme.json can be
    lost when Traefik restarts. You can ensure correct permissions with an
    initContainer. See https://github.com/traefik/traefik-helm-chart/blob/master/EXAMPLES.md#use-traefik-native-lets-encrypt-integration-without-cert-manager

    You can ignore the warning: you have addressed this issue at the beginning of the traefik.yaml file that you created in the previous step. 

    Traefik has now been successfully deployed, but... what next? That brings us to the Traefik dashboard, as explained in the following section.


     

    The Traefik Dashboard

     

    Traefik comes with a web interface that gives you insight into the status of your Kubernetes cluster and the traffic processed by your cluster. It displays information about the routers and services used to process traffic and the load balancing algorithms in use. The dashboard also allows you to view logs and metrics generated by Traefik. In short, the dashboard is a handy tool for monitoring and troubleshooting Traefik.

     

    Step 1

    To use the Traefik dashboard, first determine the external IP address of your Traefik LoadBalancer (automatically created):

    kubectl get svc -n traefik

    In the output, under ‘external-IP’ you will see an address that looks like: 86-105-245-108.haip.transip.net. Note the numbers and replace the hyphens with dots, i.e.: 86.105.245.108. 


     

    Step 2

    Would you like to attach Traefik to a (sub)domain? Then first create an A record for your domain name, see this guide, for example with the name ‘traefik’ and set its value to the IP address from the previous step.


     

    Step 3

    At the beginning of this article, we mentioned that you are using the TransIP API and need a key for it. When creating the API key, you had the option to restrict the key to whitelisted IP addresses only. If you chose this option, add the IP address from step 1 to your API whitelist, see our API guide again.

     

    It may take some time for the DNS and API changes to propagate. Once they are processed, you can view the Traefik dashboard in a browser via your subdomain, for example https://traefik.example.com/dashboard/ or directly via the IP address at https://<ip-address>:/dashboard/. When prompted for a username and password, use the ones from step 5 of the previous section.


     

    Modifying Your Configuration

     

    It is desirable to retain the public IP address of your load balancer when making changes to the Traefik configuration. Therefore, when making changes, do not delete your entire Traefik installation if possible; instead, make any necessary changes in traefik.yaml and update your Helm installation with:

    helm upgrade -f traefik.yaml traefik traefik/traefik -n traefik

     

    Example of Using Traefik

     

    You can now use Traefik for other deployments and, for example, automatically generate SSL certificates. Below we show the contents of three .yaml files as an example of how such a setup might look. Please note that you should not copy these verbatim and adjust the configuration as necessary for your use case (for example, the domain nginx.example.com)

     

    Nginx Deployment and Service:

    In the example below, you configure a simple Nginx setup that is exposed on port 80 (see the middleware further down).

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: nginx
      namespace: nginx
      labels:
        app: nginx
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: nginx
      template:
        metadata:
          labels:
            app: nginx
        spec:
          containers:
            - name: nginx
              image: nginx:stable-alpine
              ports:
                - containerPort: 80
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: nginx
      namespace: nginx
    spec:
      selector:
        app: nginx
      ports:
        - name: http
          port: 80
          targetPort: 80

     

    Middleware:

    Traefik supports a so-called ‘redirectScheme’ that allows you to easily redirect traffic to HTTPS. 

    apiVersion: traefik.io/v1alpha1
    kind: Middleware
    metadata:
      name: redirect-to-https
      namespace: nginx
    spec:
      redirectScheme:
        scheme: https
        permanent: true

     

    IngressRoute:

    In this demo setup, you need two IngressRoutes. The first route listens on the websecure entry point (i.e. HTTPS traffic) and uses the ACME resolver named ‘myresolver’ (from the first part of this guide) to obtain a certificate (if necessary) and route traffic to the Nginx service.

    apiVersion: traefik.io/v1alpha1
    kind: IngressRoute
    metadata:
      name: nginx-secure
      namespace: nginx
    spec:
      entryPoints:
        - websecure
      routes:
        - match: Host(`nginx.voorbeeld.nl`)
          kind: Rule
          services:
            - name: nginx
              port: 80
      tls:
        certResolver: myresolver

    The second route listens for traffic on port 80 and redirects it to HTTPS via the previously defined redirect-to-https middleware. 

    apiVersion: traefik.io/v1alpha1
    kind: IngressRoute
    metadata:
      name: nginx-redirect
      namespace: nginx
    spec:
      entryPoints:
        - web
      routes:
        - match: Host(`nginx.voorbeeld.nl`)
          kind: Rule
          middlewares:
            - name: redirect-to-https
          services:
            - name: nginx
              port: 80

     

    With that, we have reached the end of our guide on installing and using Traefik in Kubernetes.

    Need help?

    Receive personal support from our supporters

    Contact us