How to run MySQL in a Docker container
Prerequisite: You have installed Docker and it is running.
Run Docker Container with Empty Database
docker run -d -p 3306:3306 –name mysql -e MYSQL_ROOT_PASSWORD=password -e MYSQL_USER=user \ -e MYSQL_PASSWORD=password -e MYSQL_DATABASE=mydatabase mysql/mysql-server:5.7
Explanation: the goal of this command is to run a MySQL server version 5.7 and setup an empty database with a user and password. The MYSQL_ROOT_PASSWORD is an environment variable inside the container; it is mandatory and provides the password at the root for the superuser. The other MYSQL environment variables are optional. But as you can see, I am here created a user, a password, and an empty database called mydatabase.
–name parameter provides a name to the docker container.
-p 3306:3306 tells Docker to use host port 3306 and communicate with container port 3306. host:container
-d tells Docker to run in detached mode so that we can continue to use the terminal.
Add SQL Files to the Docker Container
docker cp file.txt container:/filename.ext
docker cp myfile.sql mysql:/myfile.sql
Run the SQL in the Container from the Host
docker exec mysql /bin/sh -c ‘mysql -u user -ppassword < /myfile.sql’