🐳 Setting up MySQL on Docker container in 2 minutes

gustavoisensee

Gustavo Isensee

Posted on December 21, 2023

🐳 Setting up MySQL on Docker container in 2 minutes

I wanna bring you today something simple that helped me a lot and I hope it can help some of you.

Let's set up our environment to support all this.

Just follow these steps:

# 1. Installing docker via Homebrew
brew install docker

# 2. Downloading mysql-server image to docker context
docker pull mysql/mysql-server

# 3. Creating the container with the image downloaded
docker run --name=my_container \
-e MYSQL_ROOT_HOST=% \
-e MYSQL_DATABASE=my_database \
-e MYSQL_ROOT_PASSWORD=root \
-p 3306 \
-d mysql/mysql-server:latest
Enter fullscreen mode Exit fullscreen mode

If you wanna know more about the variables I'm setting up there you can find all the details here.

you can quickly run docker stats just to see if you container is up and running.

if all is good, you should be able to connect via Sequel Ace now.

but before run

docker port my_container
Enter fullscreen mode Exit fullscreen mode

so you know which ports to connect.
on my case I had this:

3306/tcp -> 0.0.0.0:60245
Enter fullscreen mode Exit fullscreen mode

That means if I open Sequel Ace now I should fill the form as following:

Name: whatever you like
Host: localhost
Username: root
Password: root
Database: my_database
Port: 60245:3306
Enter fullscreen mode Exit fullscreen mode

And voilà!

Backup your container

In order to backup the container we have to take a few steps here:

# 1. We need to commit to create a local image. copy the 
# image id returned on this step.
docker commit my_container

# 2. Rename your image by creating a tag
docker tag image_id new_image_name

# 3. We save the local image into a .tar file
docker save -o ./Documents/my_image_backup.tar new_image_name
Enter fullscreen mode Exit fullscreen mode

Import and use the Backup

And in order to import we need to follow these steps:

# 4. We need to load the .tar file 
docker load -i ./Documents/my_image_backup.tar

# 5. Finally we can create our new container with the new image.
docker run --name=my_container_v2 \
-e MYSQL_ROOT_HOST=% \
-e MYSQL_DATABASE=my_database \
-e MYSQL_ROOT_PASSWORD=root \
-p 3306 \
-d new_image_name:latest
Enter fullscreen mode Exit fullscreen mode

Well, that's it, as I said it's quite simple, just a few commands and we have mysql up and running, and you also learned how to backup and restore the container/image.

I hope this was helpful, see you on the next one!

💖 💪 🙅 🚩
gustavoisensee
Gustavo Isensee

Posted on December 21, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related