The other day, I wanted to try using Traefik in real world scenario where I’ll have a docker instance running and Traefik will do the routing/proxying based on the domain name that I will provide, sadly this was not so easy, so after few hours of searching I found the solution.

You may ask, why it didnt work, it should work with no problem, and I agree so am going to list the problem I faced and the solution I found. To work with swarm, I created three servers and joined them in one swarm network, where I had one manager and two workers, then I used this simple docker-compose.yml file to create the app

simple docker-compose.yml file

YAML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

version: "3.1"

services:

api:

image: emilevauge/whoamI:latest

labels:

-"traefik.backend=api"

-"traefik.frontend.rule=Host:api.app.zah.me"

-"traefik.enable=true"

-"traefik.port=80"

-"traefik.backend.loadbalancer.method=drr"

-"traefik.docker.network=traefik"

deploy:

replicas: 1

update_config:

parallelism: 2

delay: 10s

restart_policy:

condition: on-failure

networks:

-traefik

proxy:

image: traefik:latest

command: --web --docker --docker.domain=app.zah.me --logLevel=DEBUG

ports:

-"80:80"

-"8080:8080"

volumes:

-/var/run/docker.sock:/var/run/docker.sock

networks:

-traefik

labels:

-"traefik.backend=proxy"

-"traefik.frontend.rule=Host:proxy.app.zah.me"

-"traefik.enable=true"

-"traefik.port=8080"

-"traefik.docker.network=traefik"

deploy:

placement:

constraints:

-node.role==manager

replicas: 1

restart_policy:

condition: on-failure

networks:

traefik:

driver: overlay

But sadly didnt work, after a small search I found out that I need to activate the swarm mode within traefik, either via the command section or via the config file, I chose the command, so the command is now :

now it worked, the proxy will response but the api was unreliable, I checked the labels section and I can confirm it works nice in my local machine (yes, it works on my machine 😉 ), after a small search I found out that the labels sections which is so important for traefik to work and communicate with the other services should be within the deploy section not outside as I use, as a result of my above code, traefik only communicates with the services which are on the same machine, which mean that my request will not always routed correctly, so the new improved code is: