Docker Community Forums

Share and learn in the Docker community.

Docker exec with file redirection fails if inside script


(Salvettimarc) #1

machine host OS: ubuntu 16.04
docker engine host OS : ubuntu 16.04
docker engine : 1.11
docker-machine : 0.7.0
steps to reproduce :

  • drop a sql script inside a container on a remote host that is controlled by docker-machine
  • call docker exec from within script (use shell variables to build the command string) to launch a mysql import operation from the remote fs so that the sql script doesnt need to be transfered to the docker-machine controller

Hello,

I’ve been going around in circles trying to get a script to execute a mysql command that restore a file from within the container fs to the mysql server. I’m trying this using docker-machine, but that sounds more like an issue using docker exec which is why I posted here, please correct me if I’m wrong.

In short, if I call the command like this, the docker exec command believe the file is on my local host (where docker machine is installed)

docker exec containername mysql -uUSER -pPASS -h HOST < /backupdir/script.sql

So I tried this syntax

docker exec containername sh -c ‘mysql -uUSER -pPASS -h HOST < /backupdir/script.sql’

or like this (equivalent?)

sh -c ‘mysql -uUSER -pPASS -h HOST < /backupdir/script.sql’ | docker exec containername cat

This is definitely better, as when I exec this from command line it finds the file in the container and restore it to the server.

However, my final use case needs to call this from a shell script with a few variables like hostname, username, pass, container name etc… which is where I’m struggling.

Within my script this is the closest I could come to the working syntax above :

#prep the command string
CMD=‘mysql -u’$MYSQL_USER’ -p’$MYSQL_PASS’ -h ‘$MYSQL_HOST’ -P ‘$MYSQL_PORT’ ‘$PREFIX’_db < /var/backups/’$FILEPREFIX$DATE’.sql’

#call container to exec cmd
docker exec $HOST"_phpweb" sh -c “’$CMD’”

note that $CMD is first enclosed in double quotes to expand the variables, then in single quotes to make sh -c happy

If I just echo that, it gives the expected expanded command enclosed in single quotes :

echo “’$CMD’”

‘mysql -uUSER -pPASS -h HOSTIP -P PORT PREFIX_db < /var/backups/FILEPREFIX-311.sql’

but then the script fail with a not found error, which I suppose means it’s back to look for the file on my local fs despite everything looking exactly as the working command line example

I’m really not a shell expert and still quite new to docker so I’m a bit lost here

Anyone understand what is going on ?