Environment variables show up in docker inspect, in crash dumps and in every child process. Compose secrets give the container the value as a file that only the services you name can read.
services:
db:
image: mariadb:10.11
environment:
MARIADB_ROOT_PASSWORD_FILE: /run/secrets/db_password
secrets:
- db_password
secrets:
db_password:
file: ./db_password.txt
Inside the container the secret appears at /run/secrets/db_password. Many official images, MariaDB and Postgres among them, accept a _FILE variant of their password variables, so the app reads the file and the password never sits in the environment.
Only services that list the secret under secrets: get it, which is a nice extra: the web container does not need to see the database root password.
I’d keep db_password.txt out of git and give it tight permissions on the host. A file secret in plain Compose is a bind mount, nothing encrypted, so anyone who can read that file on the host can read the secret. And the _FILE trick only works when the image supports it; if it does not, you need a small entrypoint script that reads the file, or you are back to a variable.
Further reading: Secrets in Compose, Compose file reference: secrets