Create database on docker-compose startupDocker link container as build argumentDocker Compose Relative paths vs Docker volumeDocker, Runned mysql container with port forwarding is stopped immediately as soon as it launchedDocker mysql - run update command/script on image startupDocker Flyway MySQL 8 : Client does not support authentication protocol requested by server. Consider upgrading MariaDB clientHow to access wacore container using WhatsApp Business APICreating multiple databases with official MySQL image in docker-composeUnsupported config option for services service: 'elasticsearch'Exist a way to create a mysql docker image with volume attached and also executing sql script?Docker container killed after Ctrl +C

How to take photos in burst mode, without vibration?

Would Slavery Reparations be considered Bills of Attainder and hence Illegal?

Alternative to sending password over mail?

What does it mean to describe someone as a butt steak?

Can one be a co-translator of a book, if he does not know the language that the book is translated into?

prove that the matrix A is diagonalizable

How can I make my BBEG immortal short of making them a Lich or Vampire?

Why can't we play rap on piano?

Brothers & sisters

What is the intuition behind short exact sequences of groups; in particular, what is the intuition behind group extensions?

Facing a paradox: Earnshaw's theorem in one dimension

A reference to a well-known characterization of scattered compact spaces

How could indestructible materials be used in power generation?

Fully-Firstable Anagram Sets

How do conventional missiles fly?

Watching something be written to a file live with tail

Why doesn't H₄O²⁺ exist?

What killed these X2 caps?

If a Gelatinous Cube takes up the entire space of a Pit Trap, what happens when a creature falls into the trap but succeeds on the saving throw?

How much of data wrangling is a data scientist's job?

SSH "lag" in LAN on some machines, mixed distros

If human space travel is limited by the G force vulnerability, is there a way to counter G forces?

Memorizing the Keyboard

Is it possible to run Internet Explorer on OS X El Capitan?



Create database on docker-compose startup


Docker link container as build argumentDocker Compose Relative paths vs Docker volumeDocker, Runned mysql container with port forwarding is stopped immediately as soon as it launchedDocker mysql - run update command/script on image startupDocker Flyway MySQL 8 : Client does not support authentication protocol requested by server. Consider upgrading MariaDB clientHow to access wacore container using WhatsApp Business APICreating multiple databases with official MySQL image in docker-composeUnsupported config option for services service: 'elasticsearch'Exist a way to create a mysql docker image with volume attached and also executing sql script?Docker container killed after Ctrl +C






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








11















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?










share|improve this question






























    11















    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?










    share|improve this question


























      11












      11








      11


      5






      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?










      share|improve this question
















      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?







      mysql docker-compose






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 10 '17 at 12:18









      rlandster

      3,060104069




      3,060104069










      asked Apr 10 '17 at 11:30









      PedrogPedrog

      1031112




      1031112






















          5 Answers
          5






          active

          oldest

          votes


















          20














          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 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 (...);





          share|improve this answer

























          • /data/application/init.sql this file should be located in the host machine? or inside mysql container?

            – Madhan Ayyasamy
            Jan 31 at 15:52











          • @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

            – marszczybrew
            Jan 31 at 18:17











          • can i run multiple sql file?

            – Hamzawey
            Mar 26 at 20:25


















          15














          The database is probably already initialized and the configuration is stored in /var/lib/mysql. Since you defined a volume for that location the config will survive a restart. The MySQL image will not reconfigure the database over and over again, it only does this once.



          volumes:
          - dbdata:/var/lib/mysql



          If your database is empty you can reset the database by performing docker-compose down -v where the -v removes the volumes defined in the volume section. See https://docs.docker.com/compose/reference/down/. On the next docker-compose up the MySQL image will start fresh and will initialize the database with the configuration you've provided throug the environment section.






          share|improve this answer























          • Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

            – Pedrog
            Apr 10 '17 at 16:59











          • Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

            – coder_1432
            May 11 '18 at 18:14












          • Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

            – simonw16
            Jan 17 at 23:03


















          6














          For version 2 of docker-compose you'll .yml or .yaml can look like this:



          version: '2'
          volumes:
          dbdata:

          services:
          mysql:
          image: mysql:5.7
          container_name: mysql
          volumes:
          - dbdata:/var/lib/mysql
          restart: always
          environment:
          - MYSQL_ROOT_PASSWORD=secret
          - MYSQL_DATABASE=homestead
          - MYSQL_USER=root
          - MYSQL_PASSWORD=secret
          ports:
          - "33061:3306"


          start it with docker-compose up -d
          and check:



          $ docker ps
          CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
          a3567fb78d0d mysql:5.7 "docker-entrypoint..." 2 minutes ago Up 2 minutes 0.0.0.0:33061->3306/tcp mysql

          docker exec -it a3567fb78d0d bash
          root@a3567fb78d0d:/# mysql -u root -p homestead
          Enter password:
          Welcome to the MySQL monitor. Commands end with ; or g.
          Your MySQL connection id is 7
          Server version: 5.7.17 MySQL Community Server (GPL)

          Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

          Oracle is a registered trademark of Oracle Corporation and/or its
          affiliates. Other names may be trademarks of their respective
          owners.

          Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

          mysql> show databases;
          +--------------------+
          | Database |
          +--------------------+
          | information_schema |
          | homestead |
          | mysql |
          | performance_schema |
          | sys |
          +--------------------+
          5 rows in set (0.00 sec)


          Your volume will be persisted in docker volume nameoffolder_dbdata (/var/lib/docker/volumes/...)






          share|improve this answer

























          • That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

            – Pedrog
            Apr 10 '17 at 12:29






          • 1





            I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

            – lvthillo
            Apr 10 '17 at 13:46












          • I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

            – fiza khan
            Dec 22 '17 at 7:03











          • Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

            – lvthillo
            Dec 22 '17 at 7:28


















          6














          If I understand your question correctly, you want to to have a container with a specific database in it. Like have a MySQL container with CREATE DATABASE mydb, etc. already executed. If so you need to use docker-entrypoint-initdb.d:
          https://docs.docker.com/samples/library/mysql/#docker-secrets



          When the official MySQL container is started for the first time, a new database will be created first. Then it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So all you need to do is create /docker-entrypoint-initdb.d directory and put your initialisation script there.






          share|improve this answer






























            5














            Answering your question ...



            One thing I use to do when building a new docker container is understand what the image I pull from does when is builded.



            In your docker-compose.yml tou have this



            # The Database
            database:
            image: mysql:5.7


            This is the image you pull from, "mysql:5.7"



            Dockerhub is a repository where you can find info of this images.



            Do a google search "mysql:5.7 dockerhub"



            First result is https://hub.docker.com/_/mysql/



            There you have your image 5.7, if you click on 5.7 you have this



            https://github.com/docker-library/mysql/blob/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7/Dockerfile



            Which is the Dockerfile from the image, you can have a look at interesting things that happen when building the image.



            One of this is ENTRYPOINT ["docker-entrypoint.sh"]



            This is the file that got executed when image is ready



            I you go one level up in the repo you will see this file



            https://github.com/docker-library/mysql/tree/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7



            The you can see your environment variables being used to create new database etc...



            file_env 'MYSQL_DATABASE'
            if [ "$MYSQL_DATABASE" ]; then
            echo "CREATE DATABASE IF NOT EXISTS `$MYSQL_DATABASE` ;" | "$mysql[@]"
            mysql+=( "$MYSQL_DATABASE" )
            fi





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43322033%2fcreate-database-on-docker-compose-startup%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              20














              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 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 (...);





              share|improve this answer

























              • /data/application/init.sql this file should be located in the host machine? or inside mysql container?

                – Madhan Ayyasamy
                Jan 31 at 15:52











              • @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

                – marszczybrew
                Jan 31 at 18:17











              • can i run multiple sql file?

                – Hamzawey
                Mar 26 at 20:25















              20














              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 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 (...);





              share|improve this answer

























              • /data/application/init.sql this file should be located in the host machine? or inside mysql container?

                – Madhan Ayyasamy
                Jan 31 at 15:52











              • @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

                – marszczybrew
                Jan 31 at 18:17











              • can i run multiple sql file?

                – Hamzawey
                Mar 26 at 20:25













              20












              20








              20







              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 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 (...);





              share|improve this answer















              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 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 (...);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 8 at 23:27









              naXa

              14.6k894142




              14.6k894142










              answered Apr 10 '17 at 19:23









              marszczybrewmarszczybrew

              38625




              38625












              • /data/application/init.sql this file should be located in the host machine? or inside mysql container?

                – Madhan Ayyasamy
                Jan 31 at 15:52











              • @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

                – marszczybrew
                Jan 31 at 18:17











              • can i run multiple sql file?

                – Hamzawey
                Mar 26 at 20:25

















              • /data/application/init.sql this file should be located in the host machine? or inside mysql container?

                – Madhan Ayyasamy
                Jan 31 at 15:52











              • @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

                – marszczybrew
                Jan 31 at 18:17











              • can i run multiple sql file?

                – Hamzawey
                Mar 26 at 20:25
















              /data/application/init.sql this file should be located in the host machine? or inside mysql container?

              – Madhan Ayyasamy
              Jan 31 at 15:52





              /data/application/init.sql this file should be located in the host machine? or inside mysql container?

              – Madhan Ayyasamy
              Jan 31 at 15:52













              @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

              – marszczybrew
              Jan 31 at 18:17





              @MadhanAyyasamy see the updated answer. Since /data/application/init.sql is an argument to mysql which runs in the container, the path has to be "internal" too. The file can get there by being bind mounted.

              – marszczybrew
              Jan 31 at 18:17













              can i run multiple sql file?

              – Hamzawey
              Mar 26 at 20:25





              can i run multiple sql file?

              – Hamzawey
              Mar 26 at 20:25













              15














              The database is probably already initialized and the configuration is stored in /var/lib/mysql. Since you defined a volume for that location the config will survive a restart. The MySQL image will not reconfigure the database over and over again, it only does this once.



              volumes:
              - dbdata:/var/lib/mysql



              If your database is empty you can reset the database by performing docker-compose down -v where the -v removes the volumes defined in the volume section. See https://docs.docker.com/compose/reference/down/. On the next docker-compose up the MySQL image will start fresh and will initialize the database with the configuration you've provided throug the environment section.






              share|improve this answer























              • Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

                – Pedrog
                Apr 10 '17 at 16:59











              • Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

                – coder_1432
                May 11 '18 at 18:14












              • Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

                – simonw16
                Jan 17 at 23:03















              15














              The database is probably already initialized and the configuration is stored in /var/lib/mysql. Since you defined a volume for that location the config will survive a restart. The MySQL image will not reconfigure the database over and over again, it only does this once.



              volumes:
              - dbdata:/var/lib/mysql



              If your database is empty you can reset the database by performing docker-compose down -v where the -v removes the volumes defined in the volume section. See https://docs.docker.com/compose/reference/down/. On the next docker-compose up the MySQL image will start fresh and will initialize the database with the configuration you've provided throug the environment section.






              share|improve this answer























              • Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

                – Pedrog
                Apr 10 '17 at 16:59











              • Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

                – coder_1432
                May 11 '18 at 18:14












              • Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

                – simonw16
                Jan 17 at 23:03













              15












              15








              15







              The database is probably already initialized and the configuration is stored in /var/lib/mysql. Since you defined a volume for that location the config will survive a restart. The MySQL image will not reconfigure the database over and over again, it only does this once.



              volumes:
              - dbdata:/var/lib/mysql



              If your database is empty you can reset the database by performing docker-compose down -v where the -v removes the volumes defined in the volume section. See https://docs.docker.com/compose/reference/down/. On the next docker-compose up the MySQL image will start fresh and will initialize the database with the configuration you've provided throug the environment section.






              share|improve this answer













              The database is probably already initialized and the configuration is stored in /var/lib/mysql. Since you defined a volume for that location the config will survive a restart. The MySQL image will not reconfigure the database over and over again, it only does this once.



              volumes:
              - dbdata:/var/lib/mysql



              If your database is empty you can reset the database by performing docker-compose down -v where the -v removes the volumes defined in the volume section. See https://docs.docker.com/compose/reference/down/. On the next docker-compose up the MySQL image will start fresh and will initialize the database with the configuration you've provided throug the environment section.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Apr 10 '17 at 13:26









              Sebastiaan RenkensSebastiaan Renkens

              1513




              1513












              • Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

                – Pedrog
                Apr 10 '17 at 16:59











              • Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

                – coder_1432
                May 11 '18 at 18:14












              • Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

                – simonw16
                Jan 17 at 23:03

















              • Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

                – Pedrog
                Apr 10 '17 at 16:59











              • Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

                – coder_1432
                May 11 '18 at 18:14












              • Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

                – simonw16
                Jan 17 at 23:03
















              Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

              – Pedrog
              Apr 10 '17 at 16:59





              Oh yeah! thank you very much, it must was that because now it is getting values from env. vars.

              – Pedrog
              Apr 10 '17 at 16:59













              Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

              – coder_1432
              May 11 '18 at 18:14






              Thank you very much sir! I couldn't import my database sql gz file automatically since volume was already created without it the first time. The -v argument fixed this.

              – coder_1432
              May 11 '18 at 18:14














              Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

              – simonw16
              Jan 17 at 23:03





              Oh my days this was so useful. I spent the best part of a whole work day trying to figure out why docker up wasn't creating the DB. (It had been deleted). This fixed it. Surprisingly doing docker stop $(docker ps -a -q), docker rm $(docker ps -a -q) and docker rmi $(docker images -q) did NOT solve this. I would've thought nuking everything would have worked.

              – simonw16
              Jan 17 at 23:03











              6














              For version 2 of docker-compose you'll .yml or .yaml can look like this:



              version: '2'
              volumes:
              dbdata:

              services:
              mysql:
              image: mysql:5.7
              container_name: mysql
              volumes:
              - dbdata:/var/lib/mysql
              restart: always
              environment:
              - MYSQL_ROOT_PASSWORD=secret
              - MYSQL_DATABASE=homestead
              - MYSQL_USER=root
              - MYSQL_PASSWORD=secret
              ports:
              - "33061:3306"


              start it with docker-compose up -d
              and check:



              $ docker ps
              CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
              a3567fb78d0d mysql:5.7 "docker-entrypoint..." 2 minutes ago Up 2 minutes 0.0.0.0:33061->3306/tcp mysql

              docker exec -it a3567fb78d0d bash
              root@a3567fb78d0d:/# mysql -u root -p homestead
              Enter password:
              Welcome to the MySQL monitor. Commands end with ; or g.
              Your MySQL connection id is 7
              Server version: 5.7.17 MySQL Community Server (GPL)

              Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

              Oracle is a registered trademark of Oracle Corporation and/or its
              affiliates. Other names may be trademarks of their respective
              owners.

              Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

              mysql> show databases;
              +--------------------+
              | Database |
              +--------------------+
              | information_schema |
              | homestead |
              | mysql |
              | performance_schema |
              | sys |
              +--------------------+
              5 rows in set (0.00 sec)


              Your volume will be persisted in docker volume nameoffolder_dbdata (/var/lib/docker/volumes/...)






              share|improve this answer

























              • That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

                – Pedrog
                Apr 10 '17 at 12:29






              • 1





                I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

                – lvthillo
                Apr 10 '17 at 13:46












              • I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

                – fiza khan
                Dec 22 '17 at 7:03











              • Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

                – lvthillo
                Dec 22 '17 at 7:28















              6














              For version 2 of docker-compose you'll .yml or .yaml can look like this:



              version: '2'
              volumes:
              dbdata:

              services:
              mysql:
              image: mysql:5.7
              container_name: mysql
              volumes:
              - dbdata:/var/lib/mysql
              restart: always
              environment:
              - MYSQL_ROOT_PASSWORD=secret
              - MYSQL_DATABASE=homestead
              - MYSQL_USER=root
              - MYSQL_PASSWORD=secret
              ports:
              - "33061:3306"


              start it with docker-compose up -d
              and check:



              $ docker ps
              CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
              a3567fb78d0d mysql:5.7 "docker-entrypoint..." 2 minutes ago Up 2 minutes 0.0.0.0:33061->3306/tcp mysql

              docker exec -it a3567fb78d0d bash
              root@a3567fb78d0d:/# mysql -u root -p homestead
              Enter password:
              Welcome to the MySQL monitor. Commands end with ; or g.
              Your MySQL connection id is 7
              Server version: 5.7.17 MySQL Community Server (GPL)

              Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

              Oracle is a registered trademark of Oracle Corporation and/or its
              affiliates. Other names may be trademarks of their respective
              owners.

              Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

              mysql> show databases;
              +--------------------+
              | Database |
              +--------------------+
              | information_schema |
              | homestead |
              | mysql |
              | performance_schema |
              | sys |
              +--------------------+
              5 rows in set (0.00 sec)


              Your volume will be persisted in docker volume nameoffolder_dbdata (/var/lib/docker/volumes/...)






              share|improve this answer

























              • That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

                – Pedrog
                Apr 10 '17 at 12:29






              • 1





                I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

                – lvthillo
                Apr 10 '17 at 13:46












              • I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

                – fiza khan
                Dec 22 '17 at 7:03











              • Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

                – lvthillo
                Dec 22 '17 at 7:28













              6












              6








              6







              For version 2 of docker-compose you'll .yml or .yaml can look like this:



              version: '2'
              volumes:
              dbdata:

              services:
              mysql:
              image: mysql:5.7
              container_name: mysql
              volumes:
              - dbdata:/var/lib/mysql
              restart: always
              environment:
              - MYSQL_ROOT_PASSWORD=secret
              - MYSQL_DATABASE=homestead
              - MYSQL_USER=root
              - MYSQL_PASSWORD=secret
              ports:
              - "33061:3306"


              start it with docker-compose up -d
              and check:



              $ docker ps
              CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
              a3567fb78d0d mysql:5.7 "docker-entrypoint..." 2 minutes ago Up 2 minutes 0.0.0.0:33061->3306/tcp mysql

              docker exec -it a3567fb78d0d bash
              root@a3567fb78d0d:/# mysql -u root -p homestead
              Enter password:
              Welcome to the MySQL monitor. Commands end with ; or g.
              Your MySQL connection id is 7
              Server version: 5.7.17 MySQL Community Server (GPL)

              Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

              Oracle is a registered trademark of Oracle Corporation and/or its
              affiliates. Other names may be trademarks of their respective
              owners.

              Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

              mysql> show databases;
              +--------------------+
              | Database |
              +--------------------+
              | information_schema |
              | homestead |
              | mysql |
              | performance_schema |
              | sys |
              +--------------------+
              5 rows in set (0.00 sec)


              Your volume will be persisted in docker volume nameoffolder_dbdata (/var/lib/docker/volumes/...)






              share|improve this answer















              For version 2 of docker-compose you'll .yml or .yaml can look like this:



              version: '2'
              volumes:
              dbdata:

              services:
              mysql:
              image: mysql:5.7
              container_name: mysql
              volumes:
              - dbdata:/var/lib/mysql
              restart: always
              environment:
              - MYSQL_ROOT_PASSWORD=secret
              - MYSQL_DATABASE=homestead
              - MYSQL_USER=root
              - MYSQL_PASSWORD=secret
              ports:
              - "33061:3306"


              start it with docker-compose up -d
              and check:



              $ docker ps
              CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
              a3567fb78d0d mysql:5.7 "docker-entrypoint..." 2 minutes ago Up 2 minutes 0.0.0.0:33061->3306/tcp mysql

              docker exec -it a3567fb78d0d bash
              root@a3567fb78d0d:/# mysql -u root -p homestead
              Enter password:
              Welcome to the MySQL monitor. Commands end with ; or g.
              Your MySQL connection id is 7
              Server version: 5.7.17 MySQL Community Server (GPL)

              Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

              Oracle is a registered trademark of Oracle Corporation and/or its
              affiliates. Other names may be trademarks of their respective
              owners.

              Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

              mysql> show databases;
              +--------------------+
              | Database |
              +--------------------+
              | information_schema |
              | homestead |
              | mysql |
              | performance_schema |
              | sys |
              +--------------------+
              5 rows in set (0.00 sec)


              Your volume will be persisted in docker volume nameoffolder_dbdata (/var/lib/docker/volumes/...)







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Apr 10 '17 at 13:48

























              answered Apr 10 '17 at 12:14









              lvthillolvthillo

              10.4k74273




              10.4k74273












              • That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

                – Pedrog
                Apr 10 '17 at 12:29






              • 1





                I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

                – lvthillo
                Apr 10 '17 at 13:46












              • I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

                – fiza khan
                Dec 22 '17 at 7:03











              • Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

                – lvthillo
                Dec 22 '17 at 7:28

















              • That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

                – Pedrog
                Apr 10 '17 at 12:29






              • 1





                I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

                – lvthillo
                Apr 10 '17 at 13:46












              • I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

                – fiza khan
                Dec 22 '17 at 7:03











              • Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

                – lvthillo
                Dec 22 '17 at 7:28
















              That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

              – Pedrog
              Apr 10 '17 at 12:29





              That is no exactly that i asking but it is interesting. I wonder if the envinronment vars are to create the database as well. Because in the docker-compose.yml figure the database name, why?

              – Pedrog
              Apr 10 '17 at 12:29




              1




              1





              I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

              – lvthillo
              Apr 10 '17 at 13:46






              I don't fully understand your reply/question but yes, the env var's are creating a database with the name homestead. Check my answer when I perform show databases. You see the homestead db, also I'm authenticating on that db (-p)

              – lvthillo
              Apr 10 '17 at 13:46














              I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

              – fiza khan
              Dec 22 '17 at 7:03





              I already have the container. I want to create the database for the container. Can you please tell me that how to create the docker-compose file for the container?

              – fiza khan
              Dec 22 '17 at 7:03













              Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

              – lvthillo
              Dec 22 '17 at 7:28





              Use an image which contains a database in the container like mysql or postgres? if you want to install your own db you have to write a Dockerfile and build the image in docker-compose

              – lvthillo
              Dec 22 '17 at 7:28











              6














              If I understand your question correctly, you want to to have a container with a specific database in it. Like have a MySQL container with CREATE DATABASE mydb, etc. already executed. If so you need to use docker-entrypoint-initdb.d:
              https://docs.docker.com/samples/library/mysql/#docker-secrets



              When the official MySQL container is started for the first time, a new database will be created first. Then it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So all you need to do is create /docker-entrypoint-initdb.d directory and put your initialisation script there.






              share|improve this answer



























                6














                If I understand your question correctly, you want to to have a container with a specific database in it. Like have a MySQL container with CREATE DATABASE mydb, etc. already executed. If so you need to use docker-entrypoint-initdb.d:
                https://docs.docker.com/samples/library/mysql/#docker-secrets



                When the official MySQL container is started for the first time, a new database will be created first. Then it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So all you need to do is create /docker-entrypoint-initdb.d directory and put your initialisation script there.






                share|improve this answer

























                  6












                  6








                  6







                  If I understand your question correctly, you want to to have a container with a specific database in it. Like have a MySQL container with CREATE DATABASE mydb, etc. already executed. If so you need to use docker-entrypoint-initdb.d:
                  https://docs.docker.com/samples/library/mysql/#docker-secrets



                  When the official MySQL container is started for the first time, a new database will be created first. Then it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So all you need to do is create /docker-entrypoint-initdb.d directory and put your initialisation script there.






                  share|improve this answer













                  If I understand your question correctly, you want to to have a container with a specific database in it. Like have a MySQL container with CREATE DATABASE mydb, etc. already executed. If so you need to use docker-entrypoint-initdb.d:
                  https://docs.docker.com/samples/library/mysql/#docker-secrets



                  When the official MySQL container is started for the first time, a new database will be created first. Then it will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d. So all you need to do is create /docker-entrypoint-initdb.d directory and put your initialisation script there.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Feb 26 '18 at 2:47









                  Gene SGene S

                  126111




                  126111





















                      5














                      Answering your question ...



                      One thing I use to do when building a new docker container is understand what the image I pull from does when is builded.



                      In your docker-compose.yml tou have this



                      # The Database
                      database:
                      image: mysql:5.7


                      This is the image you pull from, "mysql:5.7"



                      Dockerhub is a repository where you can find info of this images.



                      Do a google search "mysql:5.7 dockerhub"



                      First result is https://hub.docker.com/_/mysql/



                      There you have your image 5.7, if you click on 5.7 you have this



                      https://github.com/docker-library/mysql/blob/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7/Dockerfile



                      Which is the Dockerfile from the image, you can have a look at interesting things that happen when building the image.



                      One of this is ENTRYPOINT ["docker-entrypoint.sh"]



                      This is the file that got executed when image is ready



                      I you go one level up in the repo you will see this file



                      https://github.com/docker-library/mysql/tree/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7



                      The you can see your environment variables being used to create new database etc...



                      file_env 'MYSQL_DATABASE'
                      if [ "$MYSQL_DATABASE" ]; then
                      echo "CREATE DATABASE IF NOT EXISTS `$MYSQL_DATABASE` ;" | "$mysql[@]"
                      mysql+=( "$MYSQL_DATABASE" )
                      fi





                      share|improve this answer





























                        5














                        Answering your question ...



                        One thing I use to do when building a new docker container is understand what the image I pull from does when is builded.



                        In your docker-compose.yml tou have this



                        # The Database
                        database:
                        image: mysql:5.7


                        This is the image you pull from, "mysql:5.7"



                        Dockerhub is a repository where you can find info of this images.



                        Do a google search "mysql:5.7 dockerhub"



                        First result is https://hub.docker.com/_/mysql/



                        There you have your image 5.7, if you click on 5.7 you have this



                        https://github.com/docker-library/mysql/blob/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7/Dockerfile



                        Which is the Dockerfile from the image, you can have a look at interesting things that happen when building the image.



                        One of this is ENTRYPOINT ["docker-entrypoint.sh"]



                        This is the file that got executed when image is ready



                        I you go one level up in the repo you will see this file



                        https://github.com/docker-library/mysql/tree/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7



                        The you can see your environment variables being used to create new database etc...



                        file_env 'MYSQL_DATABASE'
                        if [ "$MYSQL_DATABASE" ]; then
                        echo "CREATE DATABASE IF NOT EXISTS `$MYSQL_DATABASE` ;" | "$mysql[@]"
                        mysql+=( "$MYSQL_DATABASE" )
                        fi





                        share|improve this answer



























                          5












                          5








                          5







                          Answering your question ...



                          One thing I use to do when building a new docker container is understand what the image I pull from does when is builded.



                          In your docker-compose.yml tou have this



                          # The Database
                          database:
                          image: mysql:5.7


                          This is the image you pull from, "mysql:5.7"



                          Dockerhub is a repository where you can find info of this images.



                          Do a google search "mysql:5.7 dockerhub"



                          First result is https://hub.docker.com/_/mysql/



                          There you have your image 5.7, if you click on 5.7 you have this



                          https://github.com/docker-library/mysql/blob/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7/Dockerfile



                          Which is the Dockerfile from the image, you can have a look at interesting things that happen when building the image.



                          One of this is ENTRYPOINT ["docker-entrypoint.sh"]



                          This is the file that got executed when image is ready



                          I you go one level up in the repo you will see this file



                          https://github.com/docker-library/mysql/tree/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7



                          The you can see your environment variables being used to create new database etc...



                          file_env 'MYSQL_DATABASE'
                          if [ "$MYSQL_DATABASE" ]; then
                          echo "CREATE DATABASE IF NOT EXISTS `$MYSQL_DATABASE` ;" | "$mysql[@]"
                          mysql+=( "$MYSQL_DATABASE" )
                          fi





                          share|improve this answer















                          Answering your question ...



                          One thing I use to do when building a new docker container is understand what the image I pull from does when is builded.



                          In your docker-compose.yml tou have this



                          # The Database
                          database:
                          image: mysql:5.7


                          This is the image you pull from, "mysql:5.7"



                          Dockerhub is a repository where you can find info of this images.



                          Do a google search "mysql:5.7 dockerhub"



                          First result is https://hub.docker.com/_/mysql/



                          There you have your image 5.7, if you click on 5.7 you have this



                          https://github.com/docker-library/mysql/blob/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7/Dockerfile



                          Which is the Dockerfile from the image, you can have a look at interesting things that happen when building the image.



                          One of this is ENTRYPOINT ["docker-entrypoint.sh"]



                          This is the file that got executed when image is ready



                          I you go one level up in the repo you will see this file



                          https://github.com/docker-library/mysql/tree/607b2a65aa76adf495730b9f7e6f28f146a9f95f/5.7



                          The you can see your environment variables being used to create new database etc...



                          file_env 'MYSQL_DATABASE'
                          if [ "$MYSQL_DATABASE" ]; then
                          echo "CREATE DATABASE IF NOT EXISTS `$MYSQL_DATABASE` ;" | "$mysql[@]"
                          mysql+=( "$MYSQL_DATABASE" )
                          fi






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 26 '18 at 5:31

























                          answered Feb 26 '18 at 5:25









                          jonhidjonhid

                          1,3731514




                          1,3731514



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f43322033%2fcreate-database-on-docker-compose-startup%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                              2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                              Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme