In this tutorial, we are going to set up the MySQL 8 server using Docker.
First, verify the Docker installation using the following command.
bash
docker -vPulling the MySQL image
Let's pull the MySQL 8 from Docker Hub
bash
sudo docker pull mysql:8.0Output:
139627f60883: Pull complete
Digest: sha256:d0304ed9fdb64a3f6c7ad11a5fb4f13abfc10e6dfa3f288d652e7320c34df7f9
Status: Downloaded newer image for mysql:8.0
docker.io/library/mysql:8.0We can verify if the MySQL Docker image is pulled or not by using the following command:
bash
docker imagesRunning MySQL container
Use the following command to start the container
bash
sudo docker run -d \
--name mysql-server \
-e MYSQL_ROOT_PASSWORD=your_strong_password \
-p 3306:3306 \
--restart unless-stopped \
mysql:8.0- -d: runs the container in the background
- --name: this will be the name of your container
- -e MYSQL_ROOT_PASSWORD: Set the root password
- -p 3306:3306: Maps the port on Ubuntu to the port inside the container
- --restart unless-stopped: the database starts automatically if the server reboots
Once succeed, verify it wheather the container is running or not:
bash
docker psWe can see the output something like this:
455s5esf6f983 mysql:8.0 "docker-entrypoint.s…" 29 hours ago Up 29 hours 0.0.0.0:3306->3306/tcp, [::]:3306->3306/tcp, 33060/tcp mysql-serverPersist MySQL data
If we delete the container, the MySQL data inside the container will be deleted. This is not good in a production environment. So we need to map the directory on Ubuntu.
bash
sudo docker run -d \
--name mysql-server \
-v /my/local/directory:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=your_strong_password \
-p 3306:3306 \
mysql:8.0Using a shared Docker network
When we are running an application that needs to connect to this container, we need to put it into the same Docker network. By default, standalone containers run on the bridge network. In order to create the Docker network, use the following command.
bash
docker network create tutorial-netWhere tutorial-net is the shared network name.
Now update you docker command:
bash
sudo docker run -d \
--name mysql-server \
--network tutorial-net \
-e MYSQL_ROOT_PASSWORD=your_strong_password \
-p 3306:3306 \
--restart unless-stopped \
mysql:8.0Now, when we set up the other container, we will use the same network so they can communicate with each other.
Accessing MySQL Shell
To create a database for MySQL users, we can use the MySQL shell.
bash
sudo docker exec -it mysql-server mysql -u root -pCommands for MySQL server
Check Status:
bash
sudo docker psStop the database:
bash
sudo docker stop mysql-serverWhere mysql-server is the name of the MySQL container.
Start the database:
bash
sudo docker start mysql-serverView MySQL server logs:
bash
sudo docker logs mysql-serverUsing Docker to containerize MySQL will help make its installation easy. By utilizing the volume and port mapping, we can build a robust database environment.
