Docker's method for creating the MySQL container

  • 2020-06-03 08:48:46
  • OfStack

The purpose of this article is to create an image of MySQL and automatically start the MySQL service in the newly created container to accept external connections

Steps:

1. First create 1 directory and create 1 Dockerfile under the directory. The contents of the file are as follows


FROM centos:centos6 
MAINTAINER Fanbin Kong "kongxx@hotmail.com" 
  
RUN yum install -y mysql-server mysql 
  
RUN /etc/init.d/mysqld start &&\ 
  mysql -e "grant all privileges on *.* to 'root'@'%' identified by 'letmein';"&&\ 
  mysql -e "grant all privileges on *.* to 'root'@'localhost' identified by 'letmein';"&&\ 
  mysql -u root -pletmein -e "show databases;" 
  
EXPOSE 3306 
  
CMD ["/usr/bin/mysqld_safe"] 

2. Run the build command in the Dockerfile directory to generate the image file, using mysql_server as the image file name


sudo docker build -t mysql_server . 

After running the build command, you can view it using "sudo docker images".

3. Start the container

3.1 Start the container using the following command


sudo docker run --name=mysqlserver -d -P mysql_server 

After starting the container, you can use "sudo docker ps" to view it. At this point, you can see that the contents of the PORTS column are "0.0.0.0:49153-" > 3306/tcp ", port 3306 of the container will be mapped to port 49153 of the host machine, so we can connect through port 49153 of the host machine, such as:


mysql -h < The host machine > -u root -pletmein -P 49153 

3.2 The following command can also be used when running the container


sudo docker run --name=mysqlserver -d -p 3306:3306 mysql_server 

Port 3306 of the container is mapped to port 3306 of the host machine so that we can access mysql through port 3306 of the host machine


mysql -h < The host machine > -u root -pletmein 

3.3 There is another case where, for security reasons, I only want the current host machine to have access to the mysql service, at which point we can


sudo docker run --name=mysqlserver -d -p 127.0.0.1 : 3306:3306 mysql_server 

Related articles: