I host several small apps on one server with Dokploy, each as its own Docker Compose stack. One day one of them started answering 502 Bad Gateway. Not always. Reload a few times and it would load, then fail again.
Nothing in that app had changed. The cause was in a completely different project.
What happened
In Docker Compose, services in the same stack find each other by name. My app's API talked to its web frontend simply as web, because that's what the service was called. Totally normal.
But a platform like Dokploy also has a shared network for routing: anything that gets a public domain is attached to it, so the reverse proxy can reach it. My API was on that network. So was the frontend of a different app of mine, which was also called web.
When a container is on more than one network, Docker's DNS can answer a name from any of them. web resolved to either container. When it picked the other app's, the request went to a container that wasn't listening for it, and the visitor got a 502. Which one you got depended on the lookup, which is why it was intermittent.
The fix
Give every service an alias that's unique on the whole server, and only ever use the alias:
services:
web:
networks:
default:
aliases:
- myapp-web
db:
networks:
default:
aliases:
- myapp-db
Then every address inside the stack uses myapp-web, myapp-db and so on, never the bare name. I did the same in every project on that server. Plain names like db, web and server are exactly the ones every other stack uses too.
To stop it from coming back, there's now a test that reads the compose file and fails if a service is reached by a plain name, or if it's missing its alias. It's a small test, but this kind of bug only shows up in production, and a test is the only thing that will remember the rule for me in six months.
A cousin of the same bug
A few weeks earlier, a storage service answered 502 on its public domain, while services inside the same stack could reach it fine. It only listened on the address of the first network it was attached to, and the reverse proxy came in over a different one. Telling it to listen on every interface fixed it, and that has a test now too.
What I took from it
- Service names in Compose are only private if the container is only on its own network. As soon as something is attached to a shared network, its names are shared too.
- Prefix internal hostnames with the app's name. It costs nothing.
- When an error is intermittent, think about what's being chosen: DNS answers, load balancer backends, which network a request came in on.