Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using docker environment variables in docker-compose run commands

This works:

$ docker-compose run web psql -U dbuser -h db something_development

My docker-compose.yml file has environment variables all over the place. If I run docker-compose run web env I see all kinds of tasty things I'd like to reuse in these one off commands (scripts and one-time shells).

docker-compose run env
...
DATABASE_USER=dbuser
DATABASE_HOST=db
DATABASE_NAME=something_development
DB_ENV_POSTGRES_USER=dbuser
... many more

This won't work because my current shell evals it.

docker-compose run web psql -U ${DATABASE_USER} -h ${DATABASE_HOST} ${DATABASE_NAME} ``` psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? ````

These environment variables are coming from an env file like .app.env as referenced by docker-compose.yml but docker-compose itself can set environment variables. Seems a shame to even type dbuser when they are right there. I've tried my normal escaping tricks.

docker-compose run web psql -U \$\{DATABASE_USER\} -h \$\{DATABASE_HOST\} \$\{DATABASE_NAME\}
... many other attempts

I totally rubber ducked on SO so I'm going to answer my own question.

like image 398
squarism Avatar asked Apr 29 '26 11:04

squarism


1 Answers

The answer (and there may be many ways to do it) is to run bash with -c and use single quotes so that your local shell doesn't interpolate the string.

docker-compose run web bash -c 'psql -U ${DATABASE_USER} \ -h ${DATABASE_HOST} ${DATABASE_NAME}'

Fantastic. DRY shell commands in docker-compose.

like image 104
squarism Avatar answered May 04 '26 19:05

squarism