How to populate a Mysql docker container during build of another container?

删除回忆录丶 提交于 2021-02-05 05:30:10

问题


I am trying to build a docker-compose file that automatically builds a container for my application and a mysql-container that stores all the data.

Within my dockerfile for my application I have a script, that sets up all the database tables and preset values, that are necessary for the application to run. Is it possible to somehow pass the reference of the mysql container to myapplication that during build of myapplication it can access the mysql container?

If so, how can I do that, and if not, how should it be done then?

docker-compose.yml

mysql:
  image: mysql/mysql-server
  ports:
    - "3306:3306"
  environment:
    MYSQL_USER: root
    MYSQL_ROOT_PASSWORD: mysql-root-password

myapplication:
  command: /home/myapplication/startup.sh
  build: ./..
  dockerfile: ./dockerfiles/myapplication
  ports:
    - "443:443"
    - "8090:8090"
  links:
    - mysql:docker-mysql
  environment:
    MYSQL_SERVER: docker-mysql

myapplication-dockerfile

FROM ubuntu:latest

EXPOSE 443

ENV applicationPath="/home/application“

COPY . ${applicationPath}

#Execute installationScript
RUN /bin/bash -c "./${applicationPath}/Tools/install_all.sh"

回答1:


When executing the docker-compose build command, docker will just build the images of each service defined in the docker-compose.yml file (in your case mysql and myapplication), so that means that no container will be run.

Once you execute the docker-compose run command, docker will run a container per image built previously, one for the mysql and another for the myapplication. Now that both are up, they can interact with each other.

So, what should I do?

I will just execute the install_all.sh script (guessing that it contains the database setup) when running the container and before the startup.sh script is executed. Note that the mysql container will only be accessible when it is up, that mean only after the docker-compose up execution.

docker-compose.yml

...
myapplication:
  command: bash -c "/home/myapplication/Tools/install_all.sh && /home/myapplication/startup.sh"
...

Also, note that your myapplication container has to have installed a mysql-client to be able to communicate with the mysql server. Just adding the below line to your Dockerfile will install it:

RUN apt-get update && apt-get install mysql-client -y

And in your install_all.sh script, you can have some calls to mysql like below (that create a database):

#!/bin/bash
mysql -h $DOCKER_MYSQL_PORT_3306_TCP_ADDR -P $DOCKER_MYSQL_PORT_3306_TCP_PORT -u $DOCKER_MYSQL_ENV_MYSQL_USER -p $DOCKER_MYSQL_ENV_MYSQL_ROOT_PASSWORD -e "CREATE DATABASE IF NOT EXISTS new_database;"


来源:https://stackoverflow.com/questions/35290901/how-to-populate-a-mysql-docker-container-during-build-of-another-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!