Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run docker exec on a docker-compose.yml

I am trying to create a mysql database schema during the docker-compose.yml file is getting executed

  version: "2"   services:   web:     build: docker     ports:       - "8080:8080"    environment:     - MYSQL_ROOT_PASSWORD=root     mysql:    image: mysql:latest     environment:      - MYSQL_ROOT_PASSWORD=root      - MYSQL_DATABASE=test       ports:       - "3306:3306"    links:     - web   onrun:  command: "docker exec -i test_mysql_1 mysql -uroot -proot test <dummy1.sql" 

I tried onrun but this is not working . i am building the first image but pulling the second image from the docker hub. kindly help in how to execute the following command after the docker-compose up

like image 303
raj19 Avatar asked Aug 19 '17 17:08

raj19


People also ask

How do I run a docker container exec?

To use the docker exec command, you will need a running Docker container. If you don't already have a container, start a test container with the following docker run command: docker run -d --name container-name alpine watch "date >> /var/log/date. log"

How do I run a docker file with yml?

To run and open . yml files you have to install Docker Compose. After the installation, go to your docker-compose. yml directory and then execute docker-compose up to create and start services in your docker-compose.

What is docker compose exec?

docker-compose exec : will run docker exec to start a new process/command inside an existing, running container. docker-compose run : starts a new container for interactively executing the specified command, i.e. executing docker run.


1 Answers

There is nothing like onrun in docker-compose. It will only bring up the containers and execute the command. Now you have few possible options

Use mysql Image Initialization

mysql:  image: mysql:latest  environment:    - MYSQL_ROOT_PASSWORD=root    - MYSQL_DATABASE=test   volumes:      - ./dummy1.sql:/docker-entrypoint-initdb.d/dummy1.sql  ports:   - "3306:3306" 

You may your sql files inside /docker-entrypoint-initdb.d inside the container

Use bash script

docker-compose up -d # Give some time for mysql to get up sleep 20 docker-compose exec mysql mysql -uroot -proot test <dummy1.sql 

Use another docker service to initialize the DB

version: "2" services:   web:     build: docker     ports:       - "8080:8080"    environment:     - MYSQL_ROOT_PASSWORD=root     mysql:    image: mysql:latest     environment:      - MYSQL_ROOT_PASSWORD=root      - MYSQL_DATABASE=test       ports:       - "3306:3306"    mysqlinit:      image: mysql:latest      volumes:        - ./dummy1.sql:/dump/dummy1.sql      command: bash -c "sleep 20 && mysql -h mysql -uroot -proot test < /dump/dummy1.sql" 

You run another service which will init the DB for you, like mysqlinit in the above one

like image 193
Tarun Lalwani Avatar answered Sep 19 '22 20:09

Tarun Lalwani