43

I have a docker container running mysql and I want to push a .sql file to the container and then have mysql execute the commands in it. The first step is fairly straightforward:

docker cp ./dummy.sql <container_id>:/

From there I am trying to run mysql from the command line and point it to the file that I just pushed to the container.

docker exec <container_id> mysql -u root -ppassword < /dummy.sql

This command appears to be trying to use /sample.sql as stdin locally rather than on the container. I also tried wrapping quotes around everything after the container ID which also seems to not work.

I also tried pushing a .sh file with the command in it to the docker container and then just executing that, but that is less ideal and also not working. Any advice?

Akron
  • 1,413
  • 2
  • 13
  • 28

3 Answers3

37

If you are going to do pipe redirections in your command, pass it as a string to /bin/sh:

docker exec <container_id> /bin/sh -c 'mysql -u root -ppassword </dummy.sql'
Thomasleveil
  • 95,867
  • 15
  • 119
  • 113
30

One does not need to copy the script first. If the script is on the host then:

docker exec -i <container_name> mysql -u root -ppassword <mydb> < /path/to/script.sql

Or if the Use db directive is contained inside the script:

docker exec -i <container_name> mysql -u root -ppassword < /path/to/script.sql
PuzzledVacuum
  • 453
  • 4
  • 9
  • 1
    You don't need to use `-e` or `cat`. You can simply use `docker exec -i mysql -u root -ppassword < /path/to/script.sql`, assuming that the script is on the host. – Keenan May 09 '21 at 14:55
1

Try:

docker exec <container_id> 'mysql -u root -ppassword </dummy.sql'
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • I mentioned trying that except I used double quotes rather than single. I'll try single quotes when I can. When I did that, it seems like docker was trying to execute the entire string as one literal command for some reason. – Akron Jan 14 '16 at 01:24
  • @Akron if there are no quotes, bash will interpret string first (and pass dummy to stdio) before calling docker. – Andrey Jan 14 '16 at 01:28