Learning Docker by building micro-services

Source: Internet
Author: User
Tags mysql client mysql in docker ps docker hub docker run

If you're looking for a mobile phone to learn more about Docker, then this is your best bet. In this article, I'll show you how Docker works, and the application Docker completes building a basic micro-service development task.

We will use a simple node.js service with a MySQL backend for example, to implement the migration from locally run code to a container run of micro services and databases.

What is Docker?

The core of it is: Docker is a software that allows you to create mirrors (which contain many steps, just like the templates in a virtual machine) and allow the instance of the mirror to run in a container.

Docker maintains a huge mirrored repository, which we call the Docker Hub, which we can use as a starting point for our own mirrored storage. You can follow the Docker, select any mirror that we want to use, and then execute the mirror instance in a container. Install Docker

In order to continue to learn and use the following content of this article, the first step you need to install Docker.

The following is an installation guide docs.docker.com/engine/installation based on your platform.

If you're using a Mac or Windows, you might consider using a virtual machine. Parallels is used on Mac OS X to run Ubuntu to support most development activities. This approach is handy for taking snapshots, interruptions, and restores in various experiments. Trial Start

Enter the following command:

Docker run-it Ubuntu  

You will soon see the following command prompt:

root@719059da250d:/#  

Let's test a few more commands and then terminate the container:

root@719059da250d:/# lsb_release-a  
No LSB modules are available.  
Distributor ID:    ubuntu  
Description:    ubuntu 14.04.4 LTS release  
:    14.04  
codename:    Trusty  
root@719059da250d:/# exit  

It may seem like nothing, but there's actually a lot going on behind it. What you see is a bash shell of Ubuntu, which runs in a container that is quarantined on your machine. Here, you can install anything, run any software, or whatever else you want to do. The following is a process breakdown diagram of the above action, which comes from the "Understanding architecture" of the Docker document library and is highly recommended.

1. Enter a docker command:

Odocker: Running Docker client
Orun: This command launches a new container
O-it: Optional options for starting interactive terminal mode
Oubuntu: Mirror name on which the container is started

2. The Docker service running on the host first checks the local request for a mirrored copy, and if not, executes the next step.

The 3.Docker service checks whether the public version library (Docker Hub) has a mirrored presence named Ubuntu, finds it and executes the next step.

The 4.Docker service downloads the mirror and stores it in the local cache for next time.

The 5.Docker service creates a new container based on the mirrored Ubuntu.

Try more commands as follows:

Docker run-it Haskell  
Docker run-it Java  
Docker run-it python  

We use Haskell, but as you can see, it's also very easy to configure the environment to run.

This example describes how to create your own mirrors and include our service programs, databases, and everything else that is needed. We can run them on any machine that has Docker installed, and these mirrors will be executed in the same, predictable way. So we can easily build the software and encode and deploy the environment needed for the software to run. Let's take a look at a simple example of a micro service. Overview

The following is going to create a micro-service that lets us manage the phone numbers in the e-mail directory using Node.js and MySQL. departure

To start local development, we need to install MySQL and create a test database ...
Creating a local database and executing a script is a simple start, but it can also be a mess. A lot of uncontrollable things happen. It might work, and we could even execute some scripts to check our version library, but what if there are other developers who have MySQL installed on the machine? and assume that the database they're using already has the database name ' users ' that we want to use.

First step: Create a Test database server on Docker

This is a very good Docker user case. Maybe we won't run the production database on the Docker, but we can quickly deploy a pure MySQL database based on Docker container for developers at any time, keep our clean development machine environment and everything is controllable and repeatable.

Execute the following command:

Docker run--name db-d-e mysql_root_password=123-p 3306:3306 mysql:latest  

This command starts a MySQL database instance and allows the root user and 123 passwords to access it through Port 3306. Docker run here we tell the Docker engine we need to load a mirror (this mirror name at the end of the command: mysql:vlatest). –name db here gives the container the name DB. -D (Or–detach) separation, that is, a container that runs in the background. The-e mysql_root_password=123 (OR–ENV) environment variable-tells Docker the environment variable we need to provide, and then this variable is the MYSQL mirror needs to check the configured ROOT default password. -P 3,306:3,306 (or –publish tells the Docker engine that we need to map 3306 ports inside the container to the external 3306 port.

The return value of this command is the ID of the container, which is the reference code of the container that can be used to stop, restart, execute commands, and so on for a specific container. Next let's take a look at which containers are currently running:

$ docker PS
CONTAINER ID  IMAGE         ...  NAMES  
36e68b966fd0  mysql:latest ...  Db  

The key information here is the container ID, mirror, and container name. Let's connect to the image below and see what's on it:

$ docker exec-it db/bin/bash

root@36e68b966fd0:/# mysql-uroot-p123 mysql> show  
databases;  
+--------------------+
| Database           |
+--------------------+
| information_schema |
+--------------------+
1 rows in Set (0.01 sec)

mysql> exit  
Bye  
root@36e68b966fd0:/# exit  

The implementation here is also quite ingenious: Docker Exec-it DB here tells Docker that we want to execute a command in the container named db (where we can also use the container ID, or the partial abbreviation on the ID header). mysql-uroot-p123 This is the command to actually run a specific process within the container, in this case, the MySQL client is started.

So far, we can create databases, tables, users, and everything else we need.

Test Database Summary

The above article describes some of the Docker techniques for running MySQL in a container, but pause and move on to the service. Now we're going to create a test-database folder and use a script to start the database, stop the database, and set the test data:

Test-database\setup.sql  
test-database\start.sh  
test-database\stop.sh  

The startup command is simple:

#!/bin/sh

# Run The MySQL container, with a database named ' users ' and credentials
# for a users-service user whic H can access it.
echo "Starting DB ..."  
Docker run--name db-d \  
  e mysql_root_password=123 \
  e mysql_database=users-e mysql_ User=users_service-e mysql_password=123 \
  p 3306:3306 \
  mysql:latest # Wait for the

database service to star T up.
echo "Waiting for DB to start up ..."  
Docker exec db mysqladmin--silent--wait=30-uusers_service-p123 Ping | | Exit 1

# Run the setup script.
echo "Setting up initial data ..."  
Docker exec-i db mysql-uusers_service-p123 users < Setup.sql  

This script runs database mirroring on a separate container (that is, a background-run container) while the user sets access to the users database, waits for the database server to start, and finally executes the Setup.sql script to set the initial data.
The contents of Setup.sql are as follows:

CREATE table directory (user_id INT not NULL auto_increment PRIMARY KEY, email text, phone_number text);  
Insert into directory (email, phone_number) VALUES (' homer@thesimpsons.com ', ' +1 888 123 1111 ');  
Insert into directory (email, phone_number) VALUES (' marge@thesimpsons.com ', ' +1 888 123 1112 ');  
Insert into directory (email, phone_number) VALUES (' maggie@thesimpsons.com ', ' +1 888 123 1113 ');  
Insert into directory (email, phone_number) VALUES (' lisa@thesimpsons.com ', ' +1 888 123 1114 ');  
Insert into directory (email, phone_number) VALUES (' bart@thesimpsons.com ', ' +1 888 123 1115 ');  

The stop.sh script will stop the container and delete it (by default, the container will not be removed immediately by Docker, so they can be recovered quickly when needed, which we do not need in this case):

#!/bin/sh

# Stop The DB and remove the container.
Docker Stop DB && Docker RM db  

The next step is to make these steps smoother and more concise, and you can see the version Library Branch code for the first step in this phase.

Step two: Create a node.js micro-service

Because the main focus of this article is to learn Docker, so I will not spend too much ink on how to implement Node.js, on the contrary, I will focus on Docker areas and conclusions.

test-database/          # contains the code seen in step 1  
users-service/          # root for our node.js microservice  
-Pack Age.json          # Dependencies, metadata
-index.js              # main entrypoint of the app
-api/                  # Our APIs and API Te  STS
-config/               # Config for the app
-repository/           # Abstraction on our DB
-server/               # Server Setup code

First look at repository. It is a very useful way of encapsulating your database access classes and abstractions, and allows you to simulate it for testing purposes:

Repository.js////exposes a single function-' Connect ', which returns//a connected repository.
Call ' Disconnect ' is done with this object.

' Use strict ';

var mysql = require (' mysql ');
Class which holds an open connection to a repository//and exposes some simple functions for accessing data.
  Class Repository {Constructor (connection) {this.connection = connection; } getusers () {return new Promise (Resolve, Reject) => {this.connection.query (' SELECT email, Phone_numbe R from directory ', (err, results) => {if (err) {return reject (new error ("A error occured getting th
        E Users: "+ err)"; } Resolve (Results | |
          []). Map ((user) => {return {email:user.email, phone_number:user.phone_number
        };
      }));

    });
  });
      Getuserbyemail (email) {return new Promise (Resolve, Reject) => {//Fetch the customer. This.connectioN.query (' SELECT email, phone_number from directory WHERE email =? ', [email], (err, results) => {if (err) {
        Return reject ("An error occured getting the user:" + err));
        } if (results.length = = 0) {resolve (undefined);
          else {Resolve ({email:results[0].email, phone_number:results[0].phone_number
        });

    }

      });
  });
  } disconnect () {this.connection.end ();
}//One and only exported function, returns a connected repo. Module.exports.connect = (connectionsettings) => {return new Promise (Resolve, Reject) => {if (!connections
    Ettings.host) throw new Error ("A host must be specified.");
    if (!connectionsettings.user) throw new Error ("A user must be specified.");
    if (!connectionsettings.password) throw new Error ("A password must be specified.");

    if (!connectionsettings.port) throw new Error ("A port must be specified."); Resolve (New Repository (Mysql.createconnection (connectionsettings)));
}); };

There may be a number of better ways to do this, but basically we can create repository objects in the following ways:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.