Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database on docker-compose startup

I would like to create a MySQL database using environment variables in docker-compose.yml file, but it is not working. I have the following code:

# The Database database:   image: mysql:5.7   volumes:     - dbdata:/var/lib/mysql   restart: always   environment:     MYSQL_ROOT_PASSWORD: secret     MYSQL_DATABASE: homestead     MYSQL_USER: root     MYSQL_PASSWORD: secret   ports:     - "33061:3306" 

Could someone explain the function of this vars?

like image 206
Pedrog Avatar asked Apr 10 '17 11:04

Pedrog


People also ask

Can you build a production database inside of a docker container?

If you're working on a small project, and are deploying to a single machine, it's completely okay to run your database in a Docker container. Be sure to mount a volume to make the data persistent, and have backup processes in place. Try to restore them every once in a while to make sure your backups are any good.

How can we control the start up order of services in docker compose?

You can control the order of service startup and shutdown with the depends_on option. Compose always starts and stops containers in dependency order, where dependencies are determined by depends_on , links , volumes_from , and network_mode: "service:..." .

How do I create a new database in MySQL?

Open the MySQL Workbench as an administrator (Right-click, Run as Admin). Click on File>Create Schema to create the database schema. Enter a name for the schema and click Apply. In the Apply SQL Script to Database window, click Apply to run the SQL command that creates the schema.


1 Answers

There is also an option to provide an init file for mysql container which will be applied each time a container is created.

database:     image: mysql:5.7     ports:         - "33061:3306"     command: --init-file /data/application/init.sql     volumes:         - ./init.sql:/data/application/init.sql     environment:         MYSQL_ROOT_USER: root         MYSQL_ROOT_PASSWORD: secret         MYSQL_DATABASE: homestead         MYSQL_USER: root         MYSQL_PASSWORD: secret 

Such file (init.sql) could contain your initial database structure and data - for example:

CREATE DATABASE IF NOT EXISTS dev; CREATE DATABASE IF NOT EXISTS test; USE dev; CREATE TABLE IF NOT EXISTS (...); 
like image 142
marszczybrew Avatar answered Oct 06 '22 02:10

marszczybrew