Traefik is a simple-to-use reverse-proxy and perfect for docker projects. If you want to run secured web-services, the first simple approach is to use basic authentication. In this article we will add basic authentication to traefik using
Traefik is a simple-to-use reverse-proxy and perfect for docker projects. If you want to run secured web-services, the first simple approach is to use basic authentication. In this article we will add basic authentication to traefik using docker-compose.yml . At the end of this article, you will find a bash script to generate the basic authentication string.
First we are going to generate a user/password combination for basic authentication using
htpasswd . If you don’t have it installed, you need to do it first (example for Ubuntu server):
sudo apt-get install apache2-utils
Now we will generate the content which would usually reside in
.htpasswd file and referenced in
.htaccess . For traefik we will add it instead to our
docker-compose.yml for our dynamic domain as a label. There are different options to hash the password (md5, sha1, bcrypt). Bcrypt would be to most secure, but in my experience it doesn’t work with traefik (yet) even tough it’s written in the documentation:
Passwords can be encoded in MD5, SHA1 and BCrypt: you can use htpasswd to generate them.
UPDATE: with traefik version 1.7 BCrypt is working.
Instead of using
htpasswd -nb you should use
htpasswd -nbB to generate your password (see below).
We need to escape each
$ in our resulting password string with
$$ ) if you use it directly in
echo $(htpasswd -nbB <USER> "<PASS>") | sed -e s/\\$/\\$\\$/g
The output will be for example (it will be a different result for each time you run the command above):
This output needs to be placed in our
docker-compose.yml now as a (traefik) label and replace
<USER-PASSWORD-OUTPUT> in the following example:
version: '3' services: myservice: image: myimage labels: - "traefik.frontend.rule=Host:mydomain.com" - ... - "traefik.frontend.auth.basic=<USER-PASSWORD-OUTPUT>"
After a hard restart of our docker containers (
docker-compose stop +
docker-compose up -d ) we will see a basic authentication password prompt when navigating to our domain mydomain.com .
NOTE: If you are using an environment variable (e.g. via
.envfile) in your
docker-compose.ymlinstead of placing the
<USER-PASSWORD-OUTPUT>directly, you must not escape the
$. Remove the
| sed -e s/\\$/\\$\\$/gfor the string generation then.
If you want it easy…: