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
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"
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With