Posted by H-AZAD
Install Docker
- To install docker desktop on Windows, mac, or Linux machines follow this link: Docker Desktop Install
- To install docker-engine on the Ubuntu server follow this link: Install Docker on Ubuntu
Create Mysql Server
Now create a MySQL server container from the image. In the meantime, we will expose the 3306 port as 3307 to the local machine and set the password as root.
sudo docker run --name my-mysql -p3307:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql/mysql-server:5.7
Note that this run command creates a new container from the image and starts a MySQL server on the 3307 port that can be accessible from the container outside. Here my-mysql
is the container name and the --name
flag is to assign the name of the container. The -d
flag tells the docker to run a container in detached mode and print the unique container ID in the background.
To log in to the MySQL instance through the container follow the code below:
sudo docker exec -it my-mysql mysql -uroot -proot
This is because MySQL limits access to DB from externals IP’s . So let’s add a new user and allow access from any IP.
Now you can access the newly created container MySQL CLI and there MySQL queries can be executed.
If you see the Error message like this:
ERROR 1130 (HY000): Host ‘172.17.0.1’ is not allowed to connect to this MySQL server
This is because MySQL limits access to db from externals ip’s. So let’s add a new user and allow access from any IP.
Create a new user
mysql> CREATE USER 'NewUser'@'%' IDENTIFIED BY 'NewUser';
Allow the user to access from any IP:
mysql> GRANT ALL PRIVILEGES ON *.* TO 'NewUser'@'%';
All done, if you try to access from the terminal using the below command you should be able to access the MySQL instance running in the docker container.
mysql -h localhost -P 3307 -uNewUser -p
Some other useful commands,
When you start your next docker container use
docker start my-mysql
docker restart my-mysql
docker stop my-mysql
To check your list of running docker containers
docker ps