Home  >  Q&A  >  body text

Pass password from command from .env to mysql inside docker

I basically know nothing about docker. Not so much about bash either. so:

There is a command in the readme file of the Laravel project I'm working on that shows how to populate some data on a local MySQL docker image by sending a query from a file located in the host machine.

docker exec -i {image} mysql -uroot -p{password} {database} < location/of/file.sql

What I want to do is "hide" the password from the README and have it read from the .env file

So, I want to do something like this:

docker exec --env-file=.env -i {image} mysql -uroot -p$DB_PASSWORD {database} < location/of/file.sql

I've tested docker ... printenv does show the variables in the file. But echo one of them outputs a blank line: docker ... echo $DB_PASSWORD and running the MySQL command using it gives me "Access is denied for user 'root'@'localhost" '"

I tried running MySQL commands "directly": docker ... mysql ... < file.sql and also tried running "indirectly": docker bash -c "mysql .. ." < file.sql.

P粉521748211P粉521748211207 days ago364

reply all(2)I'll reply

  • P粉403804844

    P粉4038048442024-03-27 00:47:43

    There may be two situations.

    1. Check the key name in the env file and the docker run command
    2. Check the path to the env file you want to map to.

    reply
    0
  • P粉464082061

    P粉4640820612024-03-27 00:15:08

    You should prevent the shell from expanding local variables (either via single quotes or escaping $)

    This should be passed to the container shell and expanded there:

    docker exec --env-file=.env -i {image} bash -c 'mysql -uroot -p$DB_PASSWORD {database}' < location/of/file.sql
    

    reply
    0
  • Cancelreply