Himanshu
Himanshu

Reputation: 336

How to execute query using script in MySQL Docker image?

I am trying to give user a web interface in which , user can write a query and then i will be executing that query on my server.

I am using the following MySQL docker image with the latest tag i.e. mysql:latest

https://hub.docker.com/_/mysql/

So i am runnig the docker image using this command

 docker run -it --name some-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw -v /root/ServerCode/:/usercode  mysql /bin/bash

My root/ServerCode directory contains a script which i want to use for running mysql server and user's query.

My script is

#!/bin/bash
set -e
/etc/init.d/mysqld start

It gives me error

bash: /etc/init.d/mysqld: No such file or directory

I have also tried using this

service mysqld start

It is also giving error

mysqld: unrecognized service

Edit:

 #!/bin/bash
set -e  
exec  1> $"/usercode/logfile.txt"
exec  2> $"/usercode/errors"
# These output and error files are in mounted folder which i check after running script
/etc/init.d/mysqld start // run sql server here 
#here i want to run that query and then get out of conatiner `

Upvotes: 0

Views: 2495

Answers (2)

Jinna Baalu
Jinna Baalu

Reputation: 7809

The entyrypoint scipt only does the initdb if mysqld is the argument; in your case it sees bash and so skips the initdb and just runs bash with its arguments.

If you are just trying to run some setup scripts once mysql is running have you looked at /docker-entrypoint-initdb.d/?

Create a docker-compose.yml

version: '2'
services:

    db:
      image: mysql
      container_name: mysql
      restart: always
      volumes:
        - /var/db/startuphry/mysql:/var/lib/mysql
        - ./conf/my.cnf:/etc/mysql/conf.d/settings.cnf
        - ./conf/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
      environment:
        - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
        - MYSQL_DATABASE=${MYSQL_DATABASE}
        - MYSQL_USER=${MYSQL_USER}
        - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      ports:
        - "${MYSQL_PORT}:3306"

Create a conf folder add the my.cnf file to it

[mysqld]
local-infile=0

Create folder docker-entrypoint-initdb.d inside conf folder and all sql files inside this folder

Tree looks likes this

|____docker-compose.yml
|____conf
      |___my.cnf
      |___docker-entrypoint-initdb.d
                       |___one.sql
                       |___two.sql

You can put any .sh files or .sql files in there and they will be run/imported before the mysql service is available outside the container.

Upvotes: 2

mahes wari
mahes wari

Reputation: 91

Try running the "/etc/init.d/mysqld start" inside the mysql docker container. /root/server is a host machine path . Mysql has been installed in container not in the host machine. Please run the "/etc/init.d/mysqld start " not in the host machine.

Upvotes: 0

Related Questions