A tutorial for using MySQL in Docker

  • 2020-10-23 21:13:48
  • OfStack

When it comes to virtualization, I'm a big fan of linuxContainer. But with the popularity of Docker technology, I wanted to show 1 how to use Mysql with Docker

What is Docker?

In fact, Docker is the encapsulation of LXC. It's fun to use. Docker USES LXC to virtualize each application. So in the following example, we will start an instance of mysql in the chroot environment encapsulated in our own namespace (you can also set the resource corresponding to Cgroups). One of the highlights of using Docker is the Unified file system (aufs). So when an Docker container is started, it records its aufs total and updates only the newly written data.


Aufs is useful at 10 for most applications, and it also supports database testing very well. I just want to do a simple example here - just to get the point across, it may not be very practical - Dockerfile. Dockerfile is the build script for the Docker image

Let's take a look at Dockerfile:


FROM ubuntu
MAINTAINER erkan yanar <erkan.yanar@linsenraum.de>
 
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get install -y python-software-properties
RUN apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xcbcb082a1bb943db
RUN add-apt-repository 'deb http://mirror2.hs-esslingen.de/mariadb/repo/10.0/ubuntu precise main'
RUN apt-get update
RUN apt-get install -y mariadb-server
RUN echo "[mysqld]"      >/etc/mysql/conf.d/docker.cnf
RUN echo "bind-address = 0.0.0.0"  >>/etc/mysql/conf.d/docker.cnf
RUN echo "innodb_flush_method = O_DSYNC" >>/etc/mysql/conf.d/docker.cnf
RUN echo "skip-name-resolve"    >>/etc/mysql/conf.d/docker.cnf
RUN echo "init_file = /etc/mysql/init" >>/etc/mysql/conf.d/docker.cnf
RUN echo "GRANT ALL ON *.* TO supa@'%' IDENTIFIED BY 'supa';" >/etc/mysql/init
 
EXPOSE 3306
USER mysql
ENTRYPOINT mysqld

You can change it to suit your own needs. Once you understand the general idea, you can take another step to optimize your code. For example, fewer steps to run :)

Run 1 to see (call it mysql)


> cat $DOCKERFILENAME | docker build -t mysql -

Very good! Start 51 containers to see:


> time for i in $(seq 10 60 ) ; do docker run -d -p 50$i:3306 mysql ; done                
..  
real 0m27.446s
user 0m0.264s
sys  0m0.211s

This is all on my laptop. Performance is better with KVM :)


> docker ps | grep mysqld |wc -l 
51
> docker ps | head -2
CONTAINER ID  IMAGE    COMMAND    CREATED    STATUS    PORTS     NAMES
6d3a5181cd56  mysql:latest  /bin/sh -c mysqld About a minute ago Up About a minute 0.0.0.0:5060->3306/tcp lonely_pare

Come and try it \o/


Related articles: