You might not need the hosts file hack if your DNS supports *.localhost as a wildcard. I think most GNU/Linux distros (in particular the systemd ones) and Mac OS do. You can test it by seeing if `host test.localhost` already resolves to 127.0.0.1 (or ::1).
If you are using other systems then you can set this up fairly easily in your network DNS resolver. If you use dnsmasq (used by pihole) then the following config works:
address=/localhost/127.0.0.1
address=/localhost/::1
There are similar configs for unbound or whatever you use.I have a ready to go docker-compose setup using Traefik here: https://github.com/georgek/traefik-local
Rather than do all this manually each time and worry about port numbers you just add labels to docker containers. No ports, just names (at least for http stuff).