Home > front end >  Do not normalize docker container names in traefik rules
Do not normalize docker container names in traefik rules

Time:02-12

I want to use Traefik v2.5 as a local reverse proxy to access all docker containers of my local daemon using a domain of pattern http://container_name.localhost in my browser.

This is my docker-compose.yml file:

version: "3.7"
services:
  traefik:
    image: traefik:v2.5
    restart: always
    network_mode: "host"
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--providers.docker.exposedbydefault=true"
      - "--providers.docker.defaultrule=Host(`{{ .Name }}.localhost `)"
      - "--entrypoints.web.address=:80"

Then I started the container and a simple web server to see if it worked:

docker-compose up -d
docker run -d --name my_nginx nginx

Then, I was able to access the web server at http://my-nginx.docker.localhost/. However, the name of the docker container uses underscores and not hyphens. This makes it very confusing if you just want to access one of your containers in the browser. Therefore, I want to access the container using http://my_nginx.localhost/. Is there a way to disable the normalization of the traefik rule?

I am aware that one normally uses hyphens in URLs, but docker just wants to have it's underscores, and this is just my local dev environment. I also do not want to add a traefik label manually, e.g.

traefik.http.routers.my_nginx.rule==Host(`my_nginx.localhost`)

whenever I start a simple dev container.

CodePudding user response:

I just checked the docs, and it's written that you have sprig functions available in the go template snippets.

Therefore, you can leverage go template sprigs string functions to replace the hyphen with underscores.

Host(`{{ .Name | replace "-" "_" }}.localhost `)
  • Related