1

completely new to the shell script. I want to run the sql image (image is just there to take a db dump) and take a dump of the db and copy file to the host using shell script.

how i do manually is

1) docker run -it <image_name> bash (this takes in image bash)
2) mysqldump -h <ip> -u <user> -p db > filename.sql
3) docker cp <containerId>:/file/path/within/container /host/path/target (running this in host machine)

doing this i get the dump from container to host manually.

but while making shell script, i am having problem with the point 1) docker run -it <image_name> bash (this takes in image bash) since this takes me to the bash and i have to manually type the command.

how can i do it in the shell script.

any help will be greatly appreciated!

young_minds1
  • 1,181
  • 3
  • 10
  • 25

3 Answers3

1

If I understand this correctly, you don't want to type those command manually and instead shell script should execute your command as and when you container is up and running. Now if you can modify sql related Dockerfile and can re-create image then use ENTRYPOINT [and if needed CMD] to execute shell script at startup. Check this link for details on ENTRYPOINT shell script. Else, if you cannot recreate image then check this post i.e. how to run bash script from run command.

NOTE in both these cases you will have to mount your directory/volume and your sqldump command should copy dump this map volume/directory

codinnvrends
  • 264
  • 2
  • 8
0

Ignore the Docker steps, and just run mysqldump on your host. The -h option is the IP address or DNS name of the host running the database (can be 127.0.0.1 if the container is running on the same host, but not localhost because MySQL misinterprets that); if you mapped the database external port to a non-default port, you also need a -P (capital P) option to specify that port.

For example, if you started the container with

docker run -p 5433:5432 ... mysql:8

then you can take the dump from the host with

mysqldump -h 127.0.0.1 -P 5433 -p db > dump.sql

and not worry about the Docker details at all.

David Maze
  • 130,717
  • 29
  • 175
  • 215
0

You can pass the command to Bash as a parameter:

docker run -it <image_name> --name sqldump bash -c "mysqldump -h <ip> -u <user> -p db > /tmp/filename.sql"
docker cp sqldump:/tmp/filename.sql /path/on/host/filename.sql
Konrad Botor
  • 4,765
  • 1
  • 16
  • 26