Add New Setup Guides to the Documentation

This commit is contained in:
Sheddy 2025-06-30 08:28:04 +01:00 committed by GitHub
parent b0e246cea9
commit c69a8b5cdb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 1031 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 731 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 715 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 733 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 KiB

View File

@ -0,0 +1,299 @@
---
title: Setup Traefik Proxy in Docker Standalone
description: "Learn how to Setup Traefik on Docker with HTTP/HTTPS entrypoints, redirects, secure dashboard, basic TLS, metrics, tracing, accesslogs."
---
This guide provides an in-depth walkthrough for installing and configuring Traefik Proxy within a Docker container using the official Traefik Docker image & Docker Compose. In this guide, we'll cover the following:
- Enable the [Docker provider](../reference/install-configuration/providers/docker.md)
- Expose **web** (HTTP :80) and **websecure** (HTTPS :443) entrypoints
- Redirect all HTTP traffic to HTTPS
- Secure the Traefik dashboard with **basicauth**
- Terminate TLS with a selfsigned certificate for `*.docker.localhost`
- Deploy the **whoami** demo service
- Enable accesslogs and Prometheus metrics
## Prerequisites
- Docker Desktop / Engine
- Docker Compose
- `openssl`
- `htpasswd` from `apache2-utils`
## Create a selfsigned certificate
Before Traefik can serve HTTPS locally it needs a certificate. In production youd use one from a trusted CA, but for a singlemachine stack a quick selfsigned cert is enough. We can create one with openssl by running the following commands:
```bash
mkdir -p certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout certs/local.key -out certs/local.crt \
-subj "/CN=*.docker.localhost"
```
The `certs` folder now holds `local.crt` and `local.key`, which will be mounted readonly into Traefik.
## Create the Traefik Dashboard Credentials
In production, it is advisable to have some form of authentication/security for the Traefik dashboard. Traefik can be secured with the [basicauth middleware](../reference/routing-configuration/http/middlewares/basicauth.md). To do this, generate a hashed username/password pair that Traefiks middleware will validate:
```bash
htpasswd -nb admin "P@ssw0rd" | sed -e 's/\$/\$\$/g'
```
Copy the full output (e.g., admin:$$apr1$$…) — we'll need this for the middleware configuration.
## Create a docker-compose.yaml
Now define the whole stack in a Compose file. This file declares Traefik, mounts the certificate, sets up a dedicated network, and later hosts the whoami demo service.
!!! note
You can also choose to use the Docker CLI and a configuration file to run Traefik, but for this tutorial, we'll be using Docker Compose.
First, create a folder named `dynamic` and create a file named `tls.yaml` for dynamic configuration. Paste the TLS certificate configuration into the file:
```yaml
tls:
certificates:
- certFile: /certs/local.crt
keyFile: /certs/local.key
```
In the same folder as the `dynamic/tls.yaml` file, create a `docker-compose.yaml` file and include the following:
```yaml
services:
traefik:
image: traefik:v3.4
container_name: traefik
restart: unless-stopped
security_opt:
- no-new-privileges:true
networks:
# Connect to the 'traefik_proxy' overlay network for inter-container communication across nodes
- proxy
ports:
- "80:80"
- "443:443"
- "8080:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./certs:/certs:ro
- ./dynamic:/dynamic:ro
command:
# EntryPoints
- "--entrypoints.web.address=:80"
- "--entrypoints.web.http.redirections.entrypoint.to=websecure"
- "--entrypoints.web.http.redirections.entrypoint.scheme=https"
- "--entrypoints.web.http.redirections.entrypoint.permanent=true"
- "--entrypoints.websecure.address=:443"
- "--entrypoints.websecure.http.tls=true"
# Attach the static configuration tls.yaml file that contains the tls configuration settings
- "--providers.file.filename=/dynamic/tls.yaml"
# Providers
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--providers.docker.network=proxy"
# API & Dashboard
- "--api.dashboard=true"
- "--api.insecure=false"
# Observability
- "--log.level=INFO"
- "--accesslog=true"
- "--metrics.prometheus=true"
# Traefik Dynamic configuration via Docker labels
labels:
# Enable selfrouting
- "traefik.enable=true"
# Dashboard router
- "traefik.http.routers.dashboard.rule=Host(`dashboard.docker.localhost`)"
- "traefik.http.routers.dashboard.entrypoints=websecure"
- "traefik.http.routers.dashboard.service=api@internal"
- "traefik.http.routers.dashboard.tls=true"
# Basicauth middleware
- "traefik.http.middlewares.dashboard-auth.basicauth.users=<PASTE_HASH_HERE>"
- "traefik.http.routers.dashboard.middlewares=dashboard-auth@docker"
# Whoami application
whoami:
image: traefik/whoami
container_name: whoami
restart: unless-stopped
networks:
- proxy
labels:
- "traefik.enable=true"
- "traefik.http.routers.whoami.rule=Host(`whoami.docker.localhost`)"
- "traefik.http.routers.whoami.entrypoints=websecure"
- "traefik.http.routers.whoami.tls=true"
networks:
proxy:
name: proxy
```
!!! info
- Remember to replace `<PASTE_HASH_HERE>` with the hash generated earlier.
- The `--api.insecure=false` flag is used to secure the API and prevent the dashboard from being exposed on port 8080. This is done because we are exposing the dashboard with a HTTPS router.
## Launch the stack
With the Compose file and supporting assets in place, start the containers and let Docker wire up networking behind the scenes:
```bash
docker compose up -d
```
Traefik will start, read its static configuration from the `command` arguments, connect to the Docker socket, detect its own labels for dynamic configuration (dashboard routing and auth), and begin listening on ports 80 and 443. HTTP requests will be redirected to HTTPS.
## Access the Dashboard
Now that Traefik is deployed, you can access the dashboard at [https://dashboard.docker.localhost](https://dashboard.docker.localhost) and it should prompt for the Basic Authentication credentials you configured:
![Traefik Dashboard](../assets/img/setup/traefik-dashboard-docker.png)
## Test the whoami Application
You can test the application using curl:
```bash
curl -k https://whoami.docker.localhost/
```
```bash
Hostname: whoami-76c9859cfc-k7jzs
IP: 127.0.0.1
IP: ::1
IP: 10.42.0.59
IP: fe80::50d7:a2ff:fed5:2530
RemoteAddr: 10.42.0.60:54148
GET / HTTP/1.1
Host: whoami.docker.localhost
User-Agent: curl/8.7.1
Accept: */*
Accept-Encoding: gzip
X-Forwarded-For: 10.42.0.1
X-Forwarded-Host: whoami.docker.localhost
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Forwarded-Server: traefik-644b7c67d9-f2tn9
X-Real-Ip: 10.42.0.1
```
Making the same request to the HTTP entrypoint will return the following:
```bash
curl -k http://whoami.docker.localhost
Moved Permanently
```
The above confirms that a redirection has taken place which means our setup works correctly.
You can also open a browser and navigate to [https://whoami.docker.localhost](https://whoami.docker.localhost) to see a JSON dump from the service:
![Whoami](../assets/img/setup/whoami-json-dump.png)
!!! info
You can also navigate to the Traefik Dashboard at [https://dashboard.docker.localhost](https://dashboard.docker.localhost) to see that the route has been created.
### Other Key Configuration Areas
Beyond this initial setup, Traefik offers extensive configuration possibilities. Here are brief introductions and minimal examples using Docker Compose `command` arguments or `labels`. Consult the main documentation linked for comprehensive details.
### TLS Certificate Management (Let's Encrypt)
To make the `websecure` entry point serve valid HTTPS certificates automatically, enable Let's Encrypt (ACME).
*Example `command` additions:*
```yaml
command:
# ... other command arguments ...
- "--certificatesresolvers.le.acme.email=your-email@example.com"
- "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json" # Path inside container volume
- "--certificatesresolvers.le.acme.httpchallenge.entrypoint=web"
# - "--certificatesresolvers.le.acme.dnschallenge.provider=your-dns-provider" # Needs provider setup
# Optionally make 'le' the default resolver for TLS-enabled routers
- "--entrypoints.websecure.http.tls.certresolver=le"
```
This defines a resolver named `le`, sets the required email and storage path (within the mounted `/letsencrypt` volume), and enables the HTTP challenge. Refer to the [HTTPS/TLS Documentation](../reference/install-configuration/tls/certificate-resolvers/overview.md) and [Let's Encrypt Documentation](../reference/install-configuration/tls/certificate-resolvers/acme.md) for details on challenges and DNS provider configuration.
### Metrics (Prometheus)
You can expose Traefik's internal metrics for monitoring with Prometheus. We already enabled prometheus in our setup but we can further configure it.
*Example `command` additions:*
```yaml
command:
# If using a dedicated metrics entry point, define it:
- "--entrypoints.metrics.address=:8082"
# ... other command arguments ...
- "--metrics.prometheus=true"
# Optionally change the entry point metrics are exposed on (defaults to 'traefik')
- "--metrics.prometheus.entrypoint=metrics"
# Add labels to metrics for routers/services (can increase cardinality)
- "--metrics.prometheus.addrouterslabels=true"
- "--metrics.prometheus.addserviceslabels=true"
```
This enables the `/metrics` endpoint (typically accessed via the internal API port, often 8080 by default if not secured, or via a dedicated entry point). See the [Metrics Documentation](../reference/install-configuration/observability/metrics.md) for options.
### Tracing (OTel):
You can enable distributed tracing to follow requests through Traefik.
*Example `command` additions:*
```yaml
command:
# ... other command arguments ...
- "--tracing.otel=true"
- "--tracing.otel.grpcendpoint=otel-collector:4317" # Adjust endpoint as needed
- "--tracing.otel.httpendpoint=otel-collector.observability:4318" # Adjust endpoint as needed
```
!!! note
This option requires a running OTEL collector accessible by Traefik. Consult the [Tracing Documentation](../reference/install-configuration/observability/tracing.md).
### Access Logs
You can configure Traefik to log incoming requests for debugging and analysis.
*Example `command` additions:*
```yaml
command:
# ... other command arguments ...
- "--accesslog=true" # Enable access logs to stdout
# Optionally change format or output file (requires volume)
- "--accesslog.format=json"
- "--accesslog.filepath=/path/to/access.log"
# Optionally filter logs
- "--accesslog.filters.statuscodes=400-599"
```
This enables access logs to the container's standard output (viewable via `docker compose logs <traefik-container-id>`). See the [Access Logs Documentation](../reference/install-configuration/observability/logs-and-accesslogs.md).
### Conclusion
You now have a basic Traefik setup in Docker with secure dashboard access and HTTP-to-HTTPS redirection.
{!traefik-for-business-applications.md!}

View File

@ -0,0 +1,398 @@
---
title: "Setup Traefik on Kubernetes"
description: "Learn how to Setup Traefik on Kubernetes with HTTP/HTTPS entrypoints, redirects, secure dashboard, basic TLS, metrics, tracing, accesslogs."
---
This guide provides an in-depth walkthrough for installing and configuring Traefik Proxy within a Kubernetes cluster using the official Helm chart. In this guide, we'll cover the following:
- Configure standard HTTP (`web`) and HTTPS (`websecure`) entry points,
- Implement automatic redirection from HTTP to HTTPS
- Secure the Traefik Dashboard using Basic Authentication.
- Deploy a demo application to test the setup
- Explore some other key configuration options
## Prerequisites
- A Kubernetes cluster
- Helm v3,
- Kubectl
## Create the Cluster
If you do not have a Kubernetes cluster already, you can spin up one with K3d:
```bash
k3d cluster create traefik \
--port 80:80@loadbalancer \
--port 443:443@loadbalancer \
--port 8000:8000@loadbalancer \
--k3s-arg "--disable=traefik@server:0"
```
Ports `80` and `443` reach Traefik from the host, while port `8000` remains free for later demos. The built-in Traefik shipped with k3s is disabled to avoid conflicts.
Check the context:
```bash
kubectl cluster-info --context k3d-traefik
```
You should see something like this:
```bash
Kubernetes control plane is running at https://0.0.0.0:56049
CoreDNS is running at https://0.0.0.0:56049/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
Metrics-server is running at https://0.0.0.0:56049/api/v1/namespaces/kube-system/services/https:metrics-server:https/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
```
## Add the chart repo and namespace
Using Helm streamlines Kubernetes application deployment. Helm packages applications into "charts," which are collections of template files describing Kubernetes resources. We use the official Traefik Helm chart for a managed and customizable installation.
```bash
helm repo add traefik https://traefik.github.io/charts
helm repo update
kubectl create namespace traefik
```
The first command registers the `traefik` repository alias pointing to the official chart location. The second command refreshes your local cache to ensure you have the latest list of charts and versions available from all configured repositories.
## Create a Local SelfSigned TLS Secret
Traefik's Gateway listeners require a certificate whenever a listener uses `protocol: HTTPS`.
For local development create a throwaway selfsigned certificate and
store it in a Kubernetes Secret named **localselfsignedtls**.
The Gateway references this secret to terminate TLS on the `websecure` listener.
```bash
# 1) Generate a selfsigned certificate valid for *.docker.localhost
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout tls.key -out tls.crt \
-subj "/CN=*.docker.localhost"
# 2) Create the TLS secret in the traefik namespace
kubectl create secret tls local-selfsigned-tls \
--cert=tls.crt --key=tls.key \
--namespace traefik
```
### Why Do We Need To Do This
The Gateway's HTTPS listener references this secret via `certificateRefs`.
Without it, the helm chart validation fails and the HTTP→HTTPS redirect chain breaks.
!!! info "Production tip"
The self-signed certificate above is **only for local development**. For production, either store a certificate issued by your organization's CA in a Secret or let an automated issuer such as cert-manager or Traefik's ACME (Let's Encrypt) generate certificates on demand. Update the `certificateRefs` in the `websecure` listener—or use `traefik.io/tls.certresolver`—so clients receive a trusted certificate and no longer see browser warnings.
## Prepare Helm Chart Configuration Values
Create a `values.yaml` file with the following content:
```yaml
# Configure Network Ports and EntryPoints
# EntryPoints are the network listeners for incoming traffic.
ports:
# Defines the HTTP entry point named 'web'
web:
port: 80
nodePort: 30000
# Instructs this entry point to redirect all traffic to the 'websecure' entry point
redirections:
entryPoint:
to: websecure
scheme: https
permanent: true
# Defines the HTTPS entry point named 'websecure'
websecure:
port: 443
nodePort: 30001
# Enables the dashboard in Secure Mode
api:
dashboard: true
insecure: false
ingressRoute:
dashboard:
enabled: true
matchRule: Host(`dashboard.docker.localhost`)
entryPoints:
- websecure
middlewares:
- name: dashboard-auth
# Creates a BasiAuth Middleware and Secret for the Dashboard Security
extraObjects:
- apiVersion: v1
kind: Secret
metadata:
name: dashboard-auth-secret
type: kubernetes.io/basic-auth
stringData:
username: admin
password: "P@ssw0rd" # Replace with an Actual Password
- apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: dashboard-auth
spec:
basicAuth:
secret: dashboard-auth-secret
# We will route with Gateway API instead.
ingressClass:
enabled: false
# Enable Gateway API Provider & Disables the KubernetesIngress provider
# Providers tell Traefik where to find routing configuration.
providers:
kubernetesIngress:
enabled: false
kubernetesGateway:
enabled: true
## Gateway Listeners
gateway:
listeners:
web: # HTTP listener that matches entryPoint `web`
port: 80
protocol: HTTP
namespacePolicy: All
websecure: # HTTPS listener that matches entryPoint `websecure`
port: 443
protocol: HTTPS # TLS terminates inside Traefik
namespacePolicy: All
mode: Terminate
certificateRefs:
- kind: Secret
name: local-selfsigned-tls # the Secret we created before the installation
group: ""
# Enable Observability
logs:
general:
level: INFO
# This enables access logs, outputting them to Traefik's standard output by default. The [Access Logs Documentation](https://doc.traefik.io/traefik/observability/access-logs/) covers formatting, filtering, and output options.
access:
enabled: true
# Enables Prometheus for Metrics
metrics:
prometheus:
enabled: true
```
## Install the Traefik Using the Helm Values
Now, apply the configuration using the Helm client.
```bash
# Install the chart into the 'traefik' namespace
helm install traefik traefik/traefik \
--namespace traefik \
--values values.yaml
```
**Command Breakdown:**
- `helm install traefik`: Instructs Helm to install a new release named `traefik`.
- `traefik/traefik`: Specifies the chart to use (`traefik` chart from the `traefik` repository added earlier).
- `--namespace traefik`: Specifies the Kubernetes namespace to install into. Using a dedicated namespace is recommended practice.
- `--values values.yaml`: Applies the custom configuration from your `values.yaml` file.
## Accessing the Dashboard
Now that Traefik is deployed, you can access its dashboard at [https://dashboard.docker.localhost/](https://dashboard.docker.localhost/). When you access this link, your browser will prompt for the username and password. Ensure you use the credentials set in the `values.yaml` file to log in. Upon successful login, the dashboard will be displayed as shown below:
![Traefik Dashboard](../assets/img/setup/traefik-dashboard.png)
## Deploy a Demo Application
To test the setup, deploy the [Traefik whoami](https://github.com/traefik/whoami) application in the Kubernetes cluster. Create a file named `whoami.yaml` and paste the following:
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: whoami
namespace: traefik
spec:
replicas: 2
selector:
matchLabels:
app: whoami
template:
metadata:
labels:
app: whoami
spec:
containers:
- name: whoami
image: traefik/whoami
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: whoami
namespace: traefik
spec:
selector:
app: whoami
ports:
- port: 80
```
Apply the manifest:
```bash
kubectl apply -f whoami.yaml
```
After deploying the application, you can expose the application by creating a [Gateway API HTTPRoute](https://gateway-api.sigs.k8s.io/api-types/httproute/). To do this, create a file named `whoami-route.yaml` and paste the following:
```yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: whoami
namespace: traefik
spec:
parentRefs:
- name: traefik-gateway # Name of the Gateway that Traefik creates when you enable the Gateway API provider
hostnames:
- "whoami.docker.localhost"
rules:
- matches:
- path:
type: PathPrefix
value: /
backendRefs:
- name: whoami
port: 80
```
Apply the manifest:
```bash
kubectl apply -f whoami-route.yaml
```
After you apply the manifest, navigate tothe Routes in the Traefik Dashboard; youll see that the[https://whoami.docker.localhost](https://whoami.docker.localhost)route has been created.
![Route](../assets/img/setup/route-in-dashboard.png)
You can test the application using curl:
```bash
curl -k https://whoami.docker.localhost/
```
```bash
Hostname: whoami-76c9859cfc-k7jzs
IP: 127.0.0.1
IP: ::1
IP: 10.42.0.59
IP: fe80::50d7:a2ff:fed5:2530
RemoteAddr: 10.42.0.60:54148
GET / HTTP/1.1
Host: whoami.docker.localhost
User-Agent: curl/8.7.1
Accept: */*
Accept-Encoding: gzip
X-Forwarded-For: 10.42.0.1
X-Forwarded-Host: whoami.docker.localhost
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Forwarded-Server: traefik-644b7c67d9-f2tn9
X-Real-Ip: 10.42.0.1
```
You can also open a browser and navigate to [https://whoami.docker.localhost](https://whoami.docker.localhost) to see a JSON dump from the service.
![Whoami](../assets/img/setup/whoami-json-dump.png)
## Other Key Configuration Areas
The above setup provides a secure base, but Traefik offers much more. Here's a brief overview of other essential configurations, with minimal examples using Helm `values.yaml` overrides.
These examples illustrate how to enable features; consult the main documentation for detailed options.
### TLS Certificate Management (Let's Encrypt)
On the `websecure` entry point TLS is enabled by default. However, it currently lacks a valid certificate. Traefik can automatically obtain and renew TLS certificates from Let's Encrypt using the ACME protocol.
*Example `values.yaml` addition:*
```yaml
additionalArguments:
- "--certificatesresolvers.le.acme.email=your-email@example.com"
- "--certificatesresolvers.le.acme.storage=/data/acme.json"
- "--certificatesresolvers.le.acme.httpchallenge.entrypoint=web"
# - "--certificatesresolvers.le.acme.dnschallenge.provider=your-dns-provider" # Requires provider-specific config, adjust if you control your DNS provider
# Enable persistence for ACME data (certificates, account) to ensure it survives pod restarts:
persistence:
enabled: true
name: data
size: 1Gi
storageClass: ""
```
This enables a certificate resolver named `le`, configures the mandatory email and storage file, and sets up the HTTP challenge (requires port 80 access). Refer to the [HTTPS/TLS Documentation](../reference/install-configuration/tls/certificate-resolvers/overview.md) and [Let's Encrypt Documentation](../reference/install-configuration/tls/certificate-resolvers/acme.md) for full details, including DNS challenge configuration.
!!!info "Let's Encrypt in Production"
Let's Encrypt can only issue certificates for hostnames that point to a public IP address reachable on ports 80 (HTTP01) or via your DNS provider's API (DNS01). Replace the `*.docker.localhost` examples with a real domain you control, create the DNS records, and keep ports 80/443 open to your cluster so the validation can succeed.
### Gateway API & ACME
Traefiks builtin ACME/LetsEncrypt integration works for IngressRoute and Ingress resources, but it does not issue certificates for GatewayAPI listeners.
If youre using the GatewayAPI, install [certmanager](https://cert-manager.io/docs/) (or another certificate controller) and reference the secret it creates in `gateway.listeners.websecure.certificateRefs`.
### Metrics (Prometheus)
Traefik can expose detailed metrics in Prometheus format, essential for monitoring its performance and the traffic it handles.
*Example `values.yaml` addition:*
```yaml
# Enable metrics endpoint
metrics:
prometheus:
# The entry point metrics will be available on (usually internal/admin)
entryPoint: metrics
# Add standard Prometheus metrics
addRoutersLabels: true
addServicesLabels: true
# ... other options available
```
This enables the Prometheus endpoint on a dedicated `metrics` entry point (port 9100). See the [Metrics Documentation](../reference/install-configuration/observability/metrics.md) for configuration details and available metrics.
### Tracing (OTel)
Distributed tracing helps understand request latency and flow through your system, including Traefik itself.
*Example `values.yaml` addition:*
```yaml
additionalArguments:
- "--tracing.otel=true"
- "--tracing.otel.grpcendpoint=otel-collector.observability:4317" # Adjust endpoint as needed
- "--tracing.otel.httpendpoint=otel-collector.observability:4318" # Adjust endpoint as needed
```
This enables OTel tracing and specifies the collector endpoint. Consult the [Tracing Documentation](../reference/install-configuration/observability/tracing.md) for details on OTel tracing.
## Conclusion
This setup establishes Traefik with secure dashboard access and HTTPS redirection, along with pointers to enable observability & TLS.
{!traefik-for-business-applications.md!}

330
docs/content/setup/swarm.md Normal file
View File

@ -0,0 +1,330 @@
---
title: Setup Traefik Proxy in Docker Swarm
description: "Learn how to run Traefik v3 in Docker Swarm with HTTP/HTTPS entrypoints, redirects, a secured dashboard, selfsigned TLS, metrics, tracing, and accesslogs."
---
This guide provides an indepth walkthrough for installing and configuring Traefik Proxy as a **Swarm service** using `docker stack deploy`. It follows the same structure as the standaloneDocker tutorial and covers:
- Enable the [Swarm provider](../reference/install-configuration/providers/swarm.md)
- Expose **web** (HTTP :80) and **websecure** (HTTPS :443) entrypoints
- Redirect all HTTP traffic to HTTPS
- Secure the Traefik dashboard with **basicauth**
- Terminate TLS with a selfsigned certificate for `*.swarm.localhost`
- Deploy the **whoami** demo service
- Enable accesslogs and Prometheus metrics
## Prerequisites
- Docker Engine with **Swarm mode** initialised (`docker swarm init`)
- Docker Compose
- `openssl`
- `htpasswd`
## Create a selfsigned certificate
Before Traefik can serve HTTPS locally it needs a certificate. In production youd use one from a trusted CA, but for a multinode dev swarm a quick selfsigned cert is enough:
```bash
mkdir -p certs
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout certs/local.key -out certs/local.crt \
-subj "/CN=*.swarm.localhost"
```
## Create the Traefik Dashboard Credentials
Generate a hashed username/password pair that Traefiks middleware will validate:
```bash
htpasswd -nb admin "P@ssw0rd" | sed -e 's/\$/\$\$/g'
```
Copy the full output (e.g., `admin:$$apr1$$…`) — well paste it into the middleware label.
## Create a dockercomposeswarm.yaml
!!! note
Swarm uses `docker stack deploy`. The compose file can be named anything; well use `dockercomposeswarm.yaml`.
First, create a folder named **dynamic** and add **tls.yaml** for dynamic TLS configuration:
```yaml
# dynamic/tls.yaml
tls:
certificates:
- certFile: /certs/local.crt
keyFile: /certs/local.key
```
In the same directory, create `dockercomposeswarm.yaml`:
```yaml
services:
traefik:
image: traefik:v3.4
networks:
# Connect to the 'traefik_proxy' overlay network for inter-container communication across nodes
- traefik_proxy
ports:
# Expose Traefik's entry points to the Swarm
# Swarm requires the long syntax for ports.
- target: 80 # Container port (Traefik web entry point)
published: 80 # Host port exposed on the nodes
protocol: tcp
# 'host' mode binds directly to the node's IP where the task runs.
# 'ingress' mode uses Swarm's Routing Mesh (load balances across nodes).
# Choose based on your load balancing strategy. 'host' is often simpler if using an external LB.
mode: host
- target: 443 # Container port ( Traefik websecure entry point)
published: 443 # Host port
protocol: tcp
mode: host
volumes:
# Mount the Docker socket for the Swarm provider
# This MUST be run from a manager node to access the Swarm API via the socket.
- /var/run/docker.sock:/var/run/docker.sock:ro # Swarm API socket
- ./certs:/certs:ro
- ./dynamic:/dynamic:ro
# Traefik Static configuration via command-line arguments
command:
# HTTP EntryPoint
- "--entrypoints.web.address=:80"
# Configure HTTP to HTTPS Redirection
- "--entrypoints.web.http.redirections.entrypoint.to=websecure"
- "--entrypoints.web.http.redirections.entrypoint.scheme=https"
- "--entrypoints.web.http.redirections.entrypoint.permanent=true"
# HTTPS EntryPoint
- "--entrypoints.websecure.address=:443"
- "--entrypoints.websecure.http.tls=true"
# Attach dynamic TLS file
- "--providers.file.filename=/dynamic/tls.yaml"
# Providers
# Enable the Docker Swarm provider (instead of Docker provider)
- "--providers.swarm.endpoint=unix:///var/run/docker.sock"
# Watch for Swarm service changes (requires socket access)
- "--providers.swarm.watch=true"
# Recommended: Don't expose services by default; require explicit labels
- "--providers.swarm.exposedbydefault=false"
# Specify the default network for Traefik to connect to services
- "--providers.swarm.network=traefik_traefik_proxy"
# API & Dashboard
- "--api.dashboard=true" # Enable the dashboard
- "--api.insecure=false" # Explicitly disable insecure API mod
# Observability
- "--log.level=INFO" # Set the Log Level e.g INFO, DEBUG
- "--accesslog=true" # Enable Access Logs
- "--metrics.prometheus=true" # Enable Prometheus
deploy:
mode: replicated
replicas: 1
placement:
# Placement constraints restrict where Traefik tasks can run.
# Running on manager nodes is common for accessing the Swarm API via the socket.
constraints:
- node.role == manager
# Traefik Dynamic configuration via labels
# In Swarm, labels on the service definition configure Traefik routing for that service.
labels:
- "traefik.enable=true"
# Dashboard router
- "traefik.http.routers.dashboard.rule=Host(`dashboard.swarm.localhost`)"
- "traefik.http.routers.dashboard.entrypoints=websecure"
- "traefik.http.routers.dashboard.service=api@internal"
- "traefik.http.routers.dashboard.tls=true"
# Basicauth middleware
- "traefik.http.middlewares.dashboard-auth.basicauth.users=<PASTE_HASH_HERE>"
- "traefik.http.routers.dashboard.middlewares=dashboard-auth@swarm"
# Service hint
- "traefik.http.services.traefik.loadbalancer.server.port=8080"
# Deploy the Whoami application
whoami:
image: traefik/whoami
networks:
- traefik_proxy
deploy:
labels:
# Enable Service discovery for Traefik
- "traefik.enable=true"
# Define the WHoami router rule
- "traefik.http.routers.whoami.rule=Host(`whoami.swarm.localhost`)"
# Expose Whoami on the HTTPS entrypoint
- "traefik.http.routers.whoami.entrypoints=websecure"
# Enable TLS
- "traefik.http.routers.whoami.tls=true"
# Expose the whoami port number to Traefik
- traefik.http.services.whoami.loadbalancer.server.port=80
# Define the overlay network for Swarm
networks:
traefik_proxy:
driver: overlay
attachable: true
```
!!! info
- Replace `<PASTE_HASH_HERE>` with the escaped hash from the previous step.
- The password hash is stored directly in a service label. This is fine for local development, but anyone with access to the Docker API can view it using `docker service inspect`. For production, use a more secure method to store secrets.
## Launch the stack
Create the overlay network once (if it doesnt exist) and deploy:
```bash
docker network create --driver overlay --attachable traefik_proxy || true
docker stack deploy -c docker-compose-swarm.yaml traefik
```
Swarm schedules the services on a manager node and binds ports 80/443.
## Access the Dashboard
Open **https://dashboard.swarm.localhost/** in your browser — the dashboard should prompt for the basicauth credentials you configured.
![Traefik Dashboard](../assets/img/setup/traefik-dashboard-swarm.png)
## Test the whoami Application
You can test the application using curl:
```bash
curl -k https://whoami.swarm.localhost/
```
```bash
Hostname: whoami-76c9859cfc-k7jzs
IP: 127.0.0.1
IP: ::1
IP: 10.42.0.59
IP: fe80::50d7:a2ff:fed5:2530
RemoteAddr: 10.42.0.60:54148
GET / HTTP/1.1
Host: whoami.swarm.localhost
User-Agent: curl/8.7.1
Accept: */*
Accept-Encoding: gzip
X-Forwarded-For: 10.42.0.1
X-Forwarded-Host: whoami.swarm.localhost
X-Forwarded-Port: 443
X-Forwarded-Proto: https
X-Forwarded-Server: traefik-644b7c67d9-f2tn9
X-Real-Ip: 10.42.0.1
```
Making the same request to the HTTP entrypoint will return the following:
```bash
curl -k http://whoami.swarm.localhost
Moved Permanently
```
Requesting the HTTP endpoint redirects to HTTPS, confirming the setup works.
You can also open a browser and navigate to [https://whoami.swarm.localhost](https://whoami.swarm.localhost) to see a JSON dump from the service:
![Whoami](../assets/img/setup/whoami-json-dump.png)
### Other Key Configuration Areas
Beyond this initial setup, Traefik offers extensive configuration possibilities. Here are brief introductions and minimal examples using Docker Compose `command` arguments or `labels`. Consult the main documentation linked for comprehensive details.
#### TLS Certificate Management (Lets Encrypt)
To make the `websecure` entry point serve valid HTTPS certificates automatically, enable Let's Encrypt (ACME).
```yaml
command:
# ...
- "--certificatesresolvers.le.acme.email=you@example.com"
- "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json"
- "--certificatesresolvers.le.acme.httpchallenge.entrypoint=web"
- "--entrypoints.websecure.http.tls.certresolver=le"
```
This defines a resolver named `le`, sets the required email and storage path (within the mounted `/letsencrypt` volume), and enables the HTTP challenge. Refer to the [HTTPS/TLS Documentation](../reference/install-configuration/tls/certificate-resolvers/overview.md) and [Let's Encrypt Documentation](../reference/install-configuration/tls/certificate-resolvers/acme.md) for details on challenges and DNS provider configuration.
!!! note
- Ensure the `/letsencrypt` path is on a **shared volume** or NFS so all nodes can read certificates.
- Ensure to mount the `/letsencrypt` volume in the `traefik` service in the `docker-compose-swarm.yaml` file.
#### Metrics (Prometheus)
You can expose Traefik's internal metrics for monitoring with Prometheus. We already enabled prometheus in our setup but we can further configure it.
*Example `command` additions:*
```yaml
command:
# If using a dedicated metrics entry point, define it:
- "--entrypoints.metrics.address=:8082"
- "--metrics.prometheus=true"
# Optionally change the entry point metrics are exposed on (defaults to 'traefik')
- "--metrics.prometheus.entrypoint=metrics"
# Add labels to metrics for routers/services (can increase cardinality)
- "--metrics.prometheus.addrouterslabels=true"
```
This enables the `/metrics` endpoint (typically accessed via the internal API port, often 8080 by default if not secured, or via a dedicated entry point). See the [Metrics Documentation](../reference/install-configuration/observability/metrics.md) for options.
#### Tracing (OTel)
You can enable distributed tracing to follow requests through Traefik.
*Example `command` additions:*
```yaml
command:
# ...
- "--tracing.otel=true"
- "--tracing.otel.grpcendpoint=otel-collector:4317"
```
!!! note
This option requires a running OTEL collector accessible by Traefik. Consult the [Tracing Documentation](../reference/install-configuration/observability/tracing.md).
#### Access Logs
You can configure Traefik to log incoming requests for debugging and analysis.
*Example `command` additions:*
```yaml
command:
# ... other command arguments ...
- "--accesslog=true" # Enable access logs to stdout
# Optionally change format or output file (requires volume)
- "--accesslog.format=json"
- "--accesslog.filepath=/path/to/access.log"
# Optionally filter logs
- "--accesslog.filters.statuscodes=400-599"
```
### Conclusion
You now have Traefik running on Docker Swarm with HTTPS, a secured dashboard, automatic HTTPHTTPS redirects, and foundational observability. Expand this stack with LetsEncrypt, additional middlewares, or multiple Traefik replicas as your Swarm grows.
{!traefik-for-business-applications.md!}

View File

@ -72,6 +72,10 @@ nav:
- 'Docker': 'getting-started/docker.md'
- 'Configuration Introduction': 'getting-started/configuration-overview.md'
- 'Frequently Asked Questions': 'getting-started/faq.md'
- 'Setup':
- 'Kubernetes': 'setup/kubernetes.md'
- 'Docker': 'setup/docker.md'
- 'Swarm': 'setup/swarm.md'
- 'Observe':
- 'Overview': 'observe/overview.md'
- 'Logs & Access Logs': 'observe/logs-and-access-logs.md'