Install MySQL with Docker

I often need to install a certain version of MySQL to run some experiments or to test other software but need database support. In this article, I will look into how to install a MySQL server with Docker and some basic commands.

This article is designed to get a test instance quickly and easily, please do not use it in your production environment. I assume you have already had Docker knowledge.

Pull the Latest MySQL image

docker pull mysql

This will download the latest Mysql version on the server

Create MySQL folder

mkdir -p /opt/docker-mysql/conf.d
mkdir -p /opt/docker-mysql/var/lib/mysql

Create configuration config-file.cnf

[mysqld]
lower_case_table_names=1 
#server-id=1
datadir=/var/lib/mysql
#socket=/var/lib/mysql/mysqlx.sock
#symbolic-links=0
# sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES 
[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Start MySQL

$ docker run --name mysql \
    --restart=always \
    -p 3306:3306 \
    -v /opt/docker-mysql/conf.d:/etc/mysql/conf.d \
    -v /opt/docker-mysql/var/lib/mysql:/var/lib/mysql \
    -e MYSQL_ROOT_PASSWORD=Root@123 \
    -d mysql

This will create a container named mysql and start the latest MySQL in Docker Container.

if you want to run a specified version of MySQL, you can just pick the version you want with Docker Image Tag and change the Name to be different in order to avoid name conflict:

$ docker run --name mysql-5.7 \
    --restart=always \
    -p 3306:3306 \
    -v /opt/docker-mysql/conf.d:/etc/mysql/conf.d \
    -v /opt/docker-mysql/var/lib/mysql:/var/lib/mysql \
    -e MYSQL_ROOT_PASSWORD=Root@123 \
    -d mysql:5.7

Frequently use commands

Enter container

docker exec -it mysql bash

check MySQL container log

docker logs -f mysql

Backup MySQL database

docker exec mysql sh -c 'exec mysqldump --all-databases -uroot -p"Root@123"' > /root/tensquare_gathering.sql

Restore Database

docker exec -i mysql sh -c 'exec mysql -uroot -p"Root@123"' < /root/tensquare_gathering.sql

Leave a Reply

Your email address will not be published. Required fields are marked *