Very simple installation and running MySQL using docker

Make sure you have installed and run docker on your machine.

$ docker pull mysql

This command will make docker to pull latest version of MySQL. If you want a specific version

$ docker pull mysql:8.0.24

After successfully pulled image, you can check it by running

$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql latest d4c3cafb11d5 3 months ago 545MB

The simplest way is

$ docker run --name mysql-container -e MYSQL_ROOT_PASSWORD=password -d mysql:latest

By this, it will run pulled image with specific name and tag mysql:latest as a container with name mysql-container. It also set environment variable MYSQL_ROOT_PASSWORD for user root . Argument -d or --detach is for running container in background.

You can also check running container

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
288b789ca408 mysql "docker-entrypoint.s…" 13 days ago Up 4 seconds 3306/tcp, 33060/tcp mysql-container

Can stop docker using

$ docker stop mysql-container

Start it again with command

$ docker start mysql-container

You can access MySQL on running container by get into its bash shell first.

$ docker exec -it mysql-container /bin/bash
root@288b789ca408:/#
root@288b789ca408:/# mysql -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.22 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql>

Now, you can execute any MySQL command that you want to test.

Sometimes you want to connect application to MySQL container and need information such as db host or port (by default is 3306). For host, can run docker inspect mysql-container and check IPAddress under NetworkSettings

References

A software engineer