I am able to run a SQL file as follows:
Setup Dockerfile as:
ENV MYSQL_DATABASE stock_app
COPY ./sql-scripts/ /docker-entrypoint-initdb.d/
Building the image:
docker build -t db.
Run the following command:
docker run -d -p 3306:3306 –name db -e MYSQL_ROOT_PASSWORD=password db
This is working and able to verify that SQL commands inside the script are executed and the table is created.
What changes should I make so that all three steps are done when I do the following command to bring up all my images?
docker-compose up -d
Instead of manually building the image for db and running the command to execute the SQL file, is there an option to place the run SQL file within Dockerfile? That is to include step 3 mentioned above within Dockerfile.
The mysql image has the a volume mounted that stores the database. If the folder does not exists, it is created and your scripts are applied.
Instead of trying to write a script that destroys the way the base image is built, just change your base image and make it run scripts every times as it is suggested in this question : docker-compose: reinitializing MySQL db every time
You probably don’t even need the Dockerfile unless you are doing something else that isn’t listed above. You should be able to do what you want with a simple docker-compose like this:
version: '3.3' services: database: image: mysql volumes: - "./sql-scripts:/docker-entrypoint-initdb.d" environment: MYSQL_DATABASE: stock_app MYSQL_ROOT_PASSWORD: password ports: - '3306:3306'
Whenever you update your sql script you would need to recreate the containers with
docker-compose up -d --force-recreate. By design the mysql image will run any sql files found in the “/docker-entrypoint-initdb.d” folder so you should not have to manually run those every time you recreate the containers.