Running MySQL in a Docker container is a fairly straight-forward task. In this article, I will take an opportunity to use this task to explain a few basic concepts about how Docker works.

Docker machine

The first step is to create a droplet in DigitalOcean. And then install Docker engine in it. Thankfully, docker-machine does both with a single command.

We specify the driver as DigitalOcean to create our droplet. Then, we provide an access token. Create an access token in the API section of DigitalOcean.

Create an access token in API section

With the above command, a droplet by name mysql-droplet is created. Go to the droplet console and type docker version.

Docker version

Running MySQL container

Before we get to run MySQL container, let me explain what a container is. A container is a docker process which runs an application which we call image. In our case, we want to run the MySQL application. MySQL application is available as an image in Docker Hub or the public Docker registry. We create a MySQL container as follows.

As you can see, there is a lot going in the background. First, the command pulls the mysql image from Docker Hub. Next, it creates a new container (or process) with a name mysql_server. It forwards traffic coming in through port 3306 of the droplet to port 3306 of the container. It sets the MySQL root password with an environment variable. Finally, it runs the process in background mode using the --detach option. Quite a lot for a single command!

Verify if the container is running using docker container ls command.

Running the database scripts

Database script is not like application code. While application code makes an application, database script creates a database which is data. Data should not reside within the container but outside of it. Docker has a mechanism to deal with data associated with containers using Docker volume. The official mysql image makes use of volume to store the database information.

To run the database scripts, we connect to the MySQL server using MySQL workbench from your local Mac or Windows. In the Host, provide the IP address of droplet. And leave the default port 3306 as such. Connect to the server using root password as root. Once inside, create a new schema as you normally do. Then run the database initialization script.

You are all set to use MySQL container in DigitalOcean now.

Running MySQL in a Docker container in DigitalOcean
Tagged on: