3

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

prob not the answer you want but the way we set env vars ...

(this is one of many containers)

api:
  image: 10.20.2.139:5000/investigation-api:${apiTag}
  container_name: "api"
  links:
    - "database"
    - "ldap"
  ports:
    - 8843:8843
  environment:
    KEYSTORE_PASSWORD: "ooooo"
    KEYSTORE: "${MYVAR}"
  volumes_from:
    - certs:rw

running compose ...

MYVAR=/etc/ssl/certs/keystoke.jks docker-compose (etcetera) 

typically the above line will be in a provision.sh script - cheers

3 Comments

That's passing an env from the host machine. I wanted a way to reused the KEYSTORE_PASSWORD: "ooooo" one. See my answer but thanks! :)
just updated answer - hopefully that works for you :) only used it on one place in my example but could be used in many
Well this is handy regardless. That's another flexibility option. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.