I’m trying to pass my redis password using docker-compose
via environment variable but it gives me errors.
Here is part of mine docker-compose.yml
with redis image:
redis:
image: redis
container_name: redis
# command: redis-server --requirepass mypassword <--- this works as expected
# command: redis-server --requirepass ${REDIS_PASSWORD} <-- while this does not
command: redis-server --requirepass $${REDIS_PASSWORD} <-- and this does not work either
volumes:
- redis:/var/lib/redis/data
- ./redis.conf:/usr/local/etc/redis/redis.conf
ports:
- "6379"
env_file:
- .env.prod
My .env.prod
:
REDIS_PASSWORD=mypassword
It gives me an error:
consumer: Cannot connect to redis://:**@redis:6379/0: WRONGPASS invalid username-password pair or user is disabled..
But if I specify password directly in docker-compose.yml
without env variable, then it works.
7
Answers
env_file
allows to set environment variables in the container – while you need them in the environment of docker-compose in order to perform variable substitution for${REDIS_PASSWORD}
.To achieve your goal remove the
env_file
from your yml and, either:.env.prod
file to just.env
, so that docker-compose would automatically pick it; or,--env-file
parameter:This should work:
None of the answers worked for me. Here is what I ended up doing, adjusted to
the code snippet provided by OP:
I changed the
command
field, so that the command is run through the shell —this way,
/bin/sh
can expand theREDIS_PASSWORD
variable or exit with anerror message, if the variable could not be find.
As for why the code snippet in question does not work:
command: redis-server --requirepass ${REDIS_PASSWORD}
In this case, the
${REDIS_PASSWORD}
would be expanded by Docker Compose.Docker Compose first tries to find an environment variable called
REDIS_PASSWORD
. Then, Docker Compose looks for file.env
(yes, even ifthe
env_file
field was provided). Because the variable is defined in file.env.prod
, Compose cannot find it.command: redis-server --requirepass $${REDIS_PASSWORD}
Here,
${REDIS_PASSWORD}
is passed unexpanded to theredis-server
command.This is because Docker runs the
redis-server
command directly, notthrough the shell. When one enters that command in a terminal emulator, the
shell, usually Bash, expands the variable before running the command.
Sources
${variable:?message}
syntaxThis works for me.
Similar like Cezary Drożak answer, but less code.
docker-compose.yml
redis.env
Source
You need to set the Env vars and pass them like this:
Than set it in your .env file:
if you’re trying to set the ACL user/pass instead of global –requiredpass, it can be done by creating de redis.conf file dinamically using the environment variables at the initialization command on a custom Dockerfile: