Docker: Creating MySQL 5.7 with a volume

Nuwan Zen
3 min readJan 19, 2023

Let’s install MySQL server 5.7 as Docker container with an external volume. Hope you already installed Docker in your environment :)

Sri Lanka — Sigiriya Rock view from Aliya Resorts

01: Create Docker Container

Create the docker volume to store files.

docker volume create nuwan-mysql-bizao
# output:
nuwan-mysql-bizao

List the volumes to see our volume is created.

docker volume ls
#output:
local nuwan-mysql-bizao

Inspect volume is created successfully.

docker volume inspect nuwan-mysql-bizao
#output
[
{
"CreatedAt": "2023-01-19T22:23:22+05:30",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/nuwan-mysql-bizao/_data",
"Name": "nuwan-mysql-bizao",
"Options": {},
"Scope": "local"
}
]

Now let’s create a MySQL container using our docker volume.

docker run -d --name mysql-bizao -v nuwan-mysql-bizao:/mysql-bizao -p3309:3306 -e MYSQL_ROOT_PASSWORD=root  mysql/mysql-server:5.7
#output
20240ea51f7f1ad3b7fceba06a93c9dd51ad1926e370ae7a96194d9d77b366c4

List the containers

docker ps
#output

Lets verify our volume is mounted or used by the container.

docker  inspect mysql-bizao |grep mounts -i -A10
#output
"Mounts": [
{
"Type": "volume",
"Name": "nuwan-mysql-bizao",
"Source": "/var/lib/docker/volumes/nuwan-mysql-bizao/_data",
"Destination": "/mysql-bizao",
"Driver": "local",
"Mode": "z",
"RW": true,
"Propagation": ""
},

02. Configuring the Database

Get the container name by running docker ps command and log in to the server.

docker exec -it mysql-bizao bash

Log in to mysql server internally.

mysql -uroot -proot

Let’s create a new user named ‘nuwan’ with a password ‘nuwan’

mysql> CREATE USER 'nuwan'@'%' IDENTIFIED BY 'nuwan';
#
Query OK, 0 rows affected (0.00 sec)

Grant all permissions.

mysql> GRANT ALL PRIVILEGES ON *.* TO 'nuwan'@'%';

03. Accessing the Database

Let’s log in as user nuwan

mysql -h localhost -P 3309 --protocol=TCP  -unuwan -pnuwan

Please do note that the parameter protocol=TCP. This enables us to connect to the mysql on docker otherwise mysql client will ignore the port and will connect to the local database server.

04. Next Day

Next day when you tring to access the container, you probably will see that our database container isn’t running. So this is how you should start the container.

docker container start mysql-bizao

Before You Leave …

Subscribing to my stories would be awesome!

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!