August 16, 2022

Dockerised Matomo behind Nginx Reserve Proxy

Dockerised Matomo behind Nginx Reserve Proxy

I've been migrating my bare metal services into containers and I ran into a few issues getting this one going. So I've documented the issues and fixes here in the hopes that someone else will benefit.

There were two issues I found. The first was a long-standing bug documented here:
https://github.com/matomo-org/matomo/issues/9549
where Matomo wouldn't add the trusted hosts properly leaving you unable to login.

Once that was solved the second issue was it complaining about the proxy headers not being correct, despite following their docs:
https://matomo.org/faq/how-to-install/faq_98/

So here's what I did in the end to resolve both:

docker ps -a

1690090ce5a2. Using our container ID we can now login to the container and edit the file we need to change for our solution.

docker exec -u 0 -it 1690090ce5a2 /bin/bash

Now we're in but we need a text editor to make our changes, so a quick update and installation of nano and we can get down to business. (NOTE: I'm using the official image
https://hub.docker.com/_/matomo
if you're not, substitute your images package manager for 'apt' here)

apt update
apt install nano

Edit our file config/config.ini.php

nano config/config.ini.php

We just need to add a few things under the [General] section.
Substitute your IP/port if you're not binding to localhost and using port 8000.

trusted_hosts[] = "127.0.0.1:8000"
force_ssl = 1
proxy_client_headers[] = "HTTP_X_FORWARDED_FOR"
proxy_client_headers[] = "HTTP_X_REAL_IP"
proxy_host_headers[] = "HTTP_X_FORWARDED_HOST"

Now that those changes are saved, just ensure that you are setting the same client and host headers in the location block of your Nginx site file. Mine looks like this:

        location / {
            proxy_pass http://127.0.0.1:8000;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-Host $host;
        }

All that's left now is to stop and start your container and you will be able to login to Matomo :)