A dollar sign in a compose file is never just a dollar sign. Compose reads $NAME and ${NAME} as variables and swaps in a value before the container sees the text.
That gets in the way when the dollar belongs to the program inside the container, for example a shell command that should expand $HOSTNAME itself. Write it twice:
services:
app:
image: alpine:3
command: sh -c "echo $$HOSTNAME"
Compose turns $$ into a single $ and leaves the rest of the word alone, so the shell in the container does the expanding. With one dollar, Compose first tries to fill in a variable called HOSTNAME from your own shell or .env file.
A password with a dollar sign in it has the same problem. Pasted into the compose file as it is, part of it may be read as a variable name. Doubling the sign keeps it intact.
Caveat: $$ is a rule of the compose file itself. A file you load with env_file follows its own rules, and by default Compose interpolates that file too. For the raw text there, look at format: raw on the env_file entry.
Further reading: Compose file interpolation