How to Set Up a MySQL Database Container with Docker Machine
2020-07-17 13:50:05 |
- Linux Ubuntu 20.04
Problem: You want a MySQL database that you can quickly spin up and down for testing purposes.
Solution: We're going to use Docker Machine to deploy a MySQL database running inside a container. This has the added advantage of compartmentalizing all of the MySQL dependencies, making it easier to clean up when you're finished.
Creating the MySQL DB Container
Follow these instructions to install docker-machine on your preferred operating system. Make sure to replace Ch4ng3M3 with your preferred password.
# Create virtual machine docker-machine create --driver virtualbox --virtualbox-disk-size "40000" dev # Set environment variables docker-machine env dev eval "$(docker-machine env dev)" # Create postgresql database container (make sure to replace Ch4ng3M3 with your preferred password) docker run --name mysqldb -e MYSQL_ROOT_PASSWORD=Ch4ng3M3 -p 3306:3306 -d mysql # List containers to confirm db is running docker ps
Your terminal should output the following information about your docker container:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES f69c5c5f84cb mysql "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp mysqldb
If you get the following error, this means something is already running on port 3306. It could be another mysql instance, a mysql docker container, or a separate process entirely.
docker: Error response from daemon: driver failed programming external connectivity on endpoint mysqldb (ceb965e08c68a3e38f868346a2be60fd0dae125ed0685e8a5ac3c202ac70cd4c): Bind for 0.0.0.0:mysql failed: port is already allocated.
Please refer to this article to identify and terminate the process running on port mysql. If you would rather keep that existing process running, you can instead run the mysqldb docker container on a different port, such as 3307, with the following commands.
# Delete the mysqldb container docker rm -f mysqldb # Run mysqldb container on port 5433 docker run --name mysqldb -e MYSQL_ROOT_PASSWORD=Ch4ng3M3 -p 3306:3307 -d mysql
Connecting to the DB Container
# Get the virtual machine's IP address docker-machine ip dev # Identify which port the mysqldb container is running on docker ps # Install mysql-client if you haven't already sudo apt-get install mysql-client # Connect to the DB # Make sure to substitute IP_ADDRESS with the dev docker machine's ip... # ...and PORT_NUMBER with the mysqldb container port mysql -uroot -pCh4ng3M3 -h IP_ADDRESS -P PORT_NUMBER
Once you're connected, you'll be able to run your queries. If you want to connect from a program you've written, you can use the same connection parameters.
That's the end of this tutorial. We hope you found it helpful. Make sure to check out our other tutorials, as well.