Executing SQL scripts on docker container

2020-05-31 04:20发布

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?

标签: mysql docker
3条回答
Animai°情兽
2楼-- · 2020-05-31 04:27

Try:

docker exec <container_id> 'mysql -u root -ppassword </dummy.sql'
查看更多
The star\"
3楼-- · 2020-05-31 04:31

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'
查看更多
\"骚年 ilove
4楼-- · 2020-05-31 04:40

One does not need to copy the script first. After struggling to run my own script I managed to execute it on linux using:

docker exec -it <container_name> mysql -u root -ppassword -e "Use mydb; $(cat /path/to/script.sql)"

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

docker exec -it <container_name> mysql -u root -ppassword -e "$(cat /path/to/script.sql)"

查看更多
登录 后发表回答