Search code examples
pythonmysqlpython-2.7dockerdockerpy

python docker client does not execute mysql command in a right way


I'm using MySQL docker image and a docker python client in such a code

import docker

client = docker.from_env()
container_name = 'local-mysql'

path_to_current_dir = '/home/user/workspace'

container = client.containers.run(
    'mysql',
    name=container_name,
    auto_remove=True,
    environment={
        'MYSQL_ALLOW_EMPTY_PASSWORD': True,
    },
    detach=True,
    volumes={
        path_to_current_dir: {'bind': '/data/', 'mode': 'ro'},
    }
)

er = container.exec_run('mysql -h localhost < /data/init.sql')

Basically I just want to execute mounted *.sql file within a container but receive nothing than mysql --help output in er.output and exit code is 1. Running with docker exec -it local-mysql bash and manually executing mysql -h localhost < /data/init.sql works perfectly. Providing tty=True parameter doesn't help too.

This is content of my init.sql file

CREATE DATABASE my_test;


CREATE TABLE `test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `text` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

I suspect something wrong with my command (formed not in the way docker client accepts?). This is my env for more details: Python 2.7.12, Docker version 17.12.1-ce, build 7390fc6, client docker==3.1.1, mysql within container mysql Ver 14.14 Distrib 5.7.21, for Linux (x86_64) using EditLine wrapper.

What might be wrong here?


Solution

  • if you are on host and want to feed some script with <, use pipe | or just multiple commands with && you have to do it with this bash trick /bin/bash -c "some command so it will pass the whole command as a whole to the container.

    docker exec -it local-mysql /bin/bash -c "mysql -h localhost < /data/init.sql"