3

Despues de aprender docker-compose, me veo en la necesidad de usar Docker Swarm para desplegar Traefik.

docker-compose permite sustituir ciertas variables del docker-compose.yml desde un .env como en este caso:

.env

ACME_EMAIL=email.yourdomain.com
URL_TRAEFIK_DASHBOARD=traefik.yourdomain.com
HTTPD_AUTH=test:(hash)

docker-compose.yml (version docker-compose)

version: "3.3"

services:
  traefik:
    container_name: ${TRAEFIK_CONTAINER_NAME:-traefik}
    image: "traefik:${TRAEFIK_IMAGE_TAG:-latest}"
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - "/var/run/docker.sock:/var/run/docker.sock:ro" 
      - ".letsencrypt:/letsencrypt" # Create a letsencrypt dir within the folder where the docker-compose file is
    command:
      - "--log.level=DEBUG" # Verbose debug
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=false" # Do not expose containers by default
      # Define entrypoints
      - "--entryPoints.web.address=:80"
      - "--entrypoints.websecure.address=:443"
      # Letsencrypt for https
      # - "--certificatesresolvers.le.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory"
      - "--certificatesresolvers.le.acme.email=${ACME_EMAIL}"
      - "--certificatesresolvers.le.acme.httpchallenge.entryPoint=web"
      #- "--certificatesResolvers.le.acme.tlschallenge=true" # Enable a tls challenge named "le"
      - "--certificatesresolvers.le.acme.httpchallenge=true" # Enable a http challenge named "le"
      - "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json" # Tell to store the certificate on a path under our volume
    labels:
      # Redirect 80 to 443 (force https everywhere)
      - "traefik.http.routers.https-redirect.entrypoints=web"
      - "traefik.http.routers.https-redirect.rule=hostregexp(`{any:.*}`)" 
      - "traefik.http.routers.https-redirect.middlewares=redirect-to-https"
      - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https"
      
      # Traefic dashboard
      - "traefik.enable=true"
      - "traefik.http.routers.traefik.rule=Host(`${URL_TRAEFIK_DASHBOARD}`)"
      - "traefik.http.routers.traefik.service=api@internal"
      - "traefik.http.routers.traefik.tls.certresolver=le"
      - "traefik.http.routers.traefik.entrypoints=websecure"
      - "traefik.http.routers.traefik.middlewares=authtraefik"
      - "traefik.http.middlewares.authtraefik.basicauth.users=${HTTPD_AUTH}"

networks:
  default:
    external:
      name: ${NETWORK:-reverse-proxy}

Esto funciona bien en este docker-compose.

Sin embargo ésto no es posible en Docker Swarm y cuando haces un depliegue con:

docker stack deploy -c docker-compose.yml traefik

las variables de entorno del .env no se leen y por lo tanto el stack falla o se despliega sin la configuracion.

He leido sobre configs y secrets y no concibo la forma de utilizarlos correctamente en la siguiente configuracion para Docker Swarm de Traefik:

docker-compose.yml (version swarm)

version: '3.3'

services:

  traefik:
    # Use the latest Traefik image
    image: traefik:v2.2
    ports:
      # Listen on port 80, default for HTTP, necessary to redirect to HTTPS
      - 80:80
      # Listen on port 443, default for HTTPS
      - 443:443
    deploy:
      placement:
        constraints:
          # Make the traefik service run only on the node with this label
          # as the node with it has the volume for the certificates
          - node.labels.traefik-public.traefik-public-certificates == true
      labels:
        # Enable Traefik for this service, to make it available in the public network
        - traefik.enable=true

        # Use the traefik-public network (declared below)
        - traefik.docker.network=traefik-public

        # Use the custom label "traefik.constraint-label=traefik-public"
        # This public Traefik will only use services with this label
        # That way you can add other internal Traefik instances per stack if needed
        - traefik.constraint-label=traefik-public

        # admin-auth middleware with HTTP Basic auth
        # Using the environment variables USERNAME and HASHED_PASSWORD
        - traefik.http.middlewares.admin-auth.basicauth.users=${HTTPD_AUTH}

        # https-redirect middleware to redirect HTTP to HTTPS
        # It can be re-used by other stacks in other Docker Compose files
        - traefik.http.middlewares.https-redirect.redirectscheme.scheme=https
        - traefik.http.middlewares.https-redirect.redirectscheme.permanent=true
        

        # traefik-http set up only to use the middleware to redirect to https
        # Uses the environment variable DOMAIN
        - traefik.http.routers.traefik-public-http.rule=Host(`${URL_TRAEFIK_DASHBOARD}`)
        - traefik.http.routers.traefik-public-http.entrypoints=http
        - traefik.http.routers.traefik-public-http.middlewares=https-redirect

        # traefik-https the actual router using HTTPS
        # Uses the environment variable DOMAIN
        - traefik.http.routers.traefik-public-https.rule=Host(`${URL_TRAEFIK_DASHBOARD}`)
        - traefik.http.routers.traefik-public-https.entrypoints=https
        - traefik.http.routers.traefik-public-https.tls=true

        # Use the special Traefik service api@internal with the web UI/Dashboard
        - traefik.http.routers.traefik-public-https.service=api@internal

        # Use the "le" (Let's Encrypt) resolver created below
        - traefik.http.routers.traefik-public-https.tls.certresolver=le

        # Enable HTTP Basic auth, using the middleware created above
        - traefik.http.routers.traefik-public-https.middlewares=admin-auth
        
        # Define the port inside of the Docker service to use
        - traefik.http.services.traefik-public.loadbalancer.server.port=8080
    volumes:
      # Add Docker as a mounted volume, so that Traefik can read the labels of other services
      - /var/run/docker.sock:/var/run/docker.sock:ro
      # Mount the volume to store the certificates
      - traefik-public-certificates:/certificates

    command:
      # Enable Docker in Traefik, so that it reads labels from Docker services
      - --providers.docker
      # Add a constraint to only use services with the label "traefik.constraint-label=traefik-public"
      - --providers.docker.constraints=Label(`traefik.constraint-label`, `traefik-public`)
      # Do not expose all Docker services, only the ones explicitly exposed
      - --providers.docker.exposedbydefault=false
      # Enable Docker Swarm mode
      - --providers.docker.swarmmode
      # Create an entrypoint "http" listening on address 80
      - --entrypoints.http.address=:80
      # Create an entrypoint "https" listening on address 443
      - --entrypoints.https.address=:443
      # Create the certificate resolver "le" for Let's Encrypt, uses the environment variable EMAIL
      - --certificatesresolvers.le.acme.email=${ACME_EMAIL}
      # Store the Let's Encrypt certificates in the mounted volume
      - --certificatesresolvers.le.acme.storage=/certificates/acme.json
      # Use the TLS Challenge for Let's Encrypt
      - --certificatesresolvers.le.acme.tlschallenge=true
      # Enable the access log, with HTTP requests
      - --accesslog
      # Enable the Traefik log, for configurations and errors
      - --log
      # Enable the Dashboard and API
      - --api
    networks:
      # Use the public network created to be shared between Traefik and
      # any other service that needs to be publicly available with HTTPS
      - traefik-public

volumes:
  # Create a volume to store the certificates, there is a constraint to make sure
  # Traefik is always deployed to the same Docker node with the same volume containing
  # the HTTPS certificates
  traefik-public-certificates:

networks:
  # Use the previously created public network "traefik-public", shared with other
  # services that need to be publicly available via this Traefik
  traefik-public:
    external: true

Un workarround es utilizar docker-compose config y pasarlo a un archivo o leer el stdin desde docker stack deploy:

docker-compose config | docker stack deploy -c - traefik

Esto en la mayoria de los casos funciona sin problemas, en el mio se produce un error:

networks.traefik-public Additional property name is not allowed

El docker-compose.yml tiene una red externa definida como:

traefik-public:
    external: true

Y la salida de docker-compose config produce el siguiente resultado indeseado:

 . . .
networks:
      traefik-public: null
. . .

¿Cómo puedo configurar este docker compose de forma dinámica utilizando docker config o secrets? ya que desde un archivo .env no esposible.

No deberia tener que "hardcodear" mi configuracion en el docker-compose.

La unica solucion que he encontrado es hacer export de todas las variables de entorno que necesito antes de desplegar el stack.

0

1 respuesta 1

1

SOLUCION:

  1. por preferencia personal sustituir el label que contiene el passwd en plaintext por un label que apunta a un archivo y pasarle un docker secret.
  • Sustituimos:

traefik.http.middlewares.admin-auth.basicauth.users=${HTTPD_AUTH}

por

traefik.http.middlewares.admin-auth.basicauth.usersfile=/run/secrets/USERS

  • Añadimos los USERS.secret (archivo que contiene lo mismo que HTTPD_AUTH) desde una ruta conveniente ej.: .secrets/USERS.secret

IMPORTANTE añadir .secrets a .gitignore para no preservarlo en nuestro control de versiones.

  • En nuestro docker-compose.yml debemos definir los secrets, hay mas formas pero en mi caso es conveniente desde un archivo:
version: '3.3'

secrets:
  # secret name also used to name the file exposed within the container
  USERS:
     # path on the host
    file: "./.secrets/USERS.secret"
  • añadimos los secrets que necesitamos a los servicios que queremos:
. . .
services:
  traefik:
    image: traefik:v2.2
    ports:
      - 80:80
      - 443:443
    secrets: 
        - USERS
    deploy:
. . .
  1. Crea un archivo auxiliar deploy.sh para facilitar la ejecucion del siguiente script:
#!/bin/sh
export $(cat .env) > /dev/null 2>&1; 
docker stack deploy -c docker-compose.yml ${1:-STACK_NAME}
  • el .env se parsea sin excepciones extrañas sin expresiones regulares o casos especiales.
  • los errores que producen los #comentarios del .env en cat .env se canalizan desde stderr a stdin (2>&1) y no llenamos la consola de flood.
  • podemos definir STACK_NAME en nuestro .env
  • podemos pasarle el stack_name manualmente.
  1. . deploy.sh <stack_name> (stack_name opcional)

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.