5626463547 | San Jose, CA 95126

Docker & MySQL

How to run MySQL in a Docker container

Prerequisite: You have installed Docker and it is running.

Run Docker Container with Empty Database

[simterm]
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
[/simterm]

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

[simterm]
docker cp file.txt container:/filename.ext
docker cp myfile.sql mysql:/myfile.sql
[/simterm]

Run the SQL in the Container from the Host

[simterm]
docker exec mysql /bin/sh -c ‘mysql -u user -ppassword < /myfile.sql’
[/simterm]

2018-06-07T19:47:00+00:00 June 7th, 2018|Comments Off on Docker & MySQL