Original address: Liang Guizhao’s blog

Blog address: blog.720ui.com

Welcome to pay attention to the public account: “server-side thinking”. A group of people with the same frequency, grow together, progress together, break the limitations of cognition.

30 minutes quick Start Docker tutorial

Welcome to the world of Docker

1. Docker and virtualization

In the days before Docker, we used hardware virtualization (virtual machines) to provide isolation. The VM establishes an intermediate virtual software Hypervisor on the operating system and uses the resources of the physical machine to create multiple virtual hardware environments to share the resources of the host machine. The applications in these environments run on the VM kernel. However, virtual machines have a bottleneck in hardware utilization because it is difficult for virtual machines to dynamically adjust the hardware resources they occupy according to the current traffic volume, so containerization technology is popular. Among other things, Docker is an open source application container engine that allows developers to package their applications and dependencies into a portable container and then distribute them to any popular Linux machine.

The Docker container does not use hardware virtualization. Its daemon is a process on the host. In other words, the application runs directly on the host kernel. Because there is no additional middle layer between the program running in the container and the computer’s operating system, no resources are wasted by running redundant software or simulating virtual hardware.

That’s not all Docker has. Let’s compare.

features Docker The virtual machine
startup Second level Minutes of class
Delivery/deployment Consistent development, test, and production environments Immature system
performance Approximate physical machine High performance loss
dimension Minimal (MB) Larger (GB)
Migration/expansion Cross-platform, replicable More complicated

2. Mirrors, containers, and warehouses

Docker consists of Image, Container and Repository.

The image of Docker can be simply likened to the system disk used by the computer to install the system, including the operating system and the necessary software. For example, an image can contain a full centos operating system environment with Nginx and Tomcat servers installed. Note that the mirror is read-only. This makes sense, just as the system disks we burn are actually readable. We can use Docker images to view the list of local images.

Docker container can be simply understood as providing the system hardware environment, which is really running project programs, consuming machine resources and providing services. For example, we can temporarily think of the container as a Linux computer that runs directly. So, containers are started based on images, and each container is isolated from the other. Note that the container at startup creates a writable layer based on the image as the top layer. We can use Docker ps-a to view locally run containers.

Docker’s repository is used to store images. This is very similar to Git. We can download images from the central repository or from our own repository. In the meantime, we can commit our image locally and then push it to a remote repository. Warehouses are divided into public warehouses and private warehouses. The largest public warehouse is the official warehouse Dock Hub. There are also many choices for public warehouses in China, such as Aliyun.

3. Docker promotes development process change

In the author’s opinion, Docker’s influence on the development process lies in the standardization of the environment. For example, we had three environments: the development (daily) environment, the test environment, and the production environment. Here, we need to deploy the same software, scripts, and run programs for each environment, as shown in the figure. In fact, the content of the startup script is consistent, but there is no unified maintenance, which often causes problems. In addition, it can be confusing and unusual for a running program to rely on an inconsistent underlying runtime environment.

Now, after we’ve introduced Docker, we only need to maintain a Docker image. In other words, multiple environments, one image, implementing a system-level build everywhere. At this point, we standardize the running script, mirror the underlying software, and then standardize the deployment of the same application to be deployed. Therefore, Docker provides us with a standardized operation and maintenance mode and solidifies operation and maintenance steps and processes.

With this process improvement, it’s much easier to achieve our DevOps goals because our images can be generated and run on any system and deployed quickly. In addition, the great driving force of Docker is to realize flexible scheduling based on Docker, so as to make full use of machine resources and save costs.

Haha, I also found some great benefits in using Docker. For example, when we release rollback, we just need to switch the TAG and restart. For example, if we upgrade the environment, we only need to upgrade the base image, so the newly built application image will automatically reference the new version. (Welcome to add ~ ~ ~)

Second, start from building Web server

1. Environment first, install Docker

Now, we need to install the following steps to install Docker.

  • Register: Sign up at hub.docker.com/.
  • Download and install

The official download address: (Mac) : download.docker.com/mac/stable/… Ali cloud download address (Mac) : mirrors.aliyun.com/docker-tool… Ali cloud download address (Windows) : mirrors.aliyun.com/docker-tool…

  • Here, double-click the doker.dmg installation package you just downloaded to install it.

After the installation, an icon appears in the navigation bar at the top of the Mac, allowing you to configure and exit the Docker.

The official guide: docs.docker.com/install/ ali cloud guide (Linux) : yq.aliyun.com/articles/11…

  • Setting up accelerated Service

There are a lot of accelerated service providers in the market, such as DaoCloud, AliCloud, etc. Here, the author is using Ali Cloud. (It should be noted that the author’s operating system is Mac. For other operation series, please refer to aliyun operation documents.)

Right click on the Docker icon in the top bar of the desktop, select Preferences, The Daemon tag (Docker before version 17.03 to the Advanced TAB) under the Registry mirrors a list at https://xxx.mirror.aliyuncs.com Add it to the array of “Registry -mirrors”, click Apply & Restart, and wait for the Docker to Restart and Apply the configured mirror accelerator.

Ali Cloud operation document: cr.console.aliyun.com/cn-hangzhou…

  • Check the version

At this point, the installation is complete. Here, let’s look at the version.

docker version
Copy the code

View the result, as shown below.

2. Practical, starting from building Web servers

Let’s start by building a Web server. Then, I will take you slowly to understand what has been done in this process. First, we need to pull the centos image.

docker run -p 80 --name web -i -t centos /bin/bash
Copy the code

Next, we install the nginx server and execute the following command:

rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
Copy the code

After installing the Nginx source, you are ready to install Nginx.

yum install -y nginx
Copy the code

At this point, enter whereis nginx to see the installation path. Finally, we need to get Nginx running.

nginx
Copy the code

Now, we switch to the background by pressing CTRL + P + Q. Docker Ps-A is then used to view randomly assigned ports.

In this case, the port assigned by the author is 32769, so you can access http://127.0.0.1:32769 through a browser.

Done, ha ha ha

3. Review to understand the whole process

Now, let’s understand the process. First, we enter docker run -p 80 –name web -i -t centos /bin/bash to run the interactive container, where the -i option tells the Docker container to keep the standard input stream open to the container, even if the container has no terminal connection. The other -t option tells Docker to assign a virtual terminal to the container so we can install the Nginx server next. Docker also supports the -d option to tell Docker to run the container daemon in the background.

Docker automatically generates a random name for every container we create. In fact, although this method is convenient, the readability is very poor, and the cost of understanding our later maintenance will be relatively high. Therefore, we tell Docker to create a container whose name is Web with the –name Web option. In addition, we tell Docker to open port 80 via -p 80 so that Nginx can be accessed and served externally. However, our host machine will automatically do port mapping, such as the above allocation of port 32769, note that, if shut down or restart, this port will change, then how to solve the problem of fixed port, THE author will be in the back of the detailed analysis and take you to combat.

Here, there is another very important point docker run. Docker starts a new container with the run command. Docker first looks for the image on the host. If it is not installed, Docker looks for the image on Docker Hub and downloads it to the host. Finally, Docker creates a new container and starts the program.

However, when docker run is executed a second time, Docker creates a new container and starts the program because Docker already has the image installed on the machine.

Note that docker run creates a new container each time it is used, so when we start the container again in the future, we only need to use the command docker start. Here, docker start is used to restart the existing image, while Docker Run involves putting the image into the container docker Create, and then starting the container Docker start, as shown in the figure.

Now, we can build on the example above and close the Docker container with the exit command. Of course, if we are running a daemon in the background, we can also stop it by using docker Stop Web. Note that docker stop and Docker kill are slightly different in that docker stop sends SIGTERM while Docker kill sends SIGKILL. Then, we restart it using Docker start.

docker start web
Copy the code

After the Docker container is restarted, it will use the parameters specified by the Docker run command to run, but it is still running in the background. We must switch to running interactive containers by using the Docker attach command.

docker attach web
Copy the code

4. There are more orders

Docker provides a very rich set of commands. A picture is worth a thousand words, and we can learn a lot from the pictures below and their previous uses. (Can directly skip the reading, suggested collection, easy to expand reading)

For more information, read the official usage documentation.

Command Description
docker attach Attach local standard input, output, and error streams to a running container
docker build Build an image from a Dockerfile
docker builder Manage builds
docker checkpoint Manage checkpoints
docker commit Create a new image from a container’s changes
docker config Manage Docker configs
docker container Manage containers
docker cp Copy files/folders between a container and the local filesystem
docker create Create a new container
docker deploy Deploy a new stack or update an existing stack
docker diff Inspect changes to files or directories on a container’s filesystem
docker engine Manage the docker engine
docker events Get real time events from the server
docker exec Run a command in a running container
docker export Export a container’s filesystem as a tar archive
docker history Show the history of an image
docker image Manage images
docker images List images
docker import Import the contents from a tarball to create a filesystem image
docker info Display system-wide information
docker inspect Return low-level information on Docker objects
docker kill Kill one or more running containers
docker load Load an image from a tar archive or STDIN
docker login Log in to a Docker registry
docker logout Log out from a Docker registry
docker logs Fetch the logs of a container
docker manifest Manage Docker image manifests and manifest lists
docker network Manage networks
docker node Manage Swarm nodes
docker pause Pause all processes within one or more containers
docker plugin Manage plugins
docker port List port mappings or a specific mapping for the container
docker ps List containers
docker pull Pull an image or a repository from a registry
docker push Push an image or a repository to a registry
docker rename Rename a container
docker restart Restart one or more containers
docker rm Remove one or more containers
docker rmi Remove one or more images
docker run Run a command in a new container
docker save Save one or more images to a tar archive (streamed to STDOUT by default)
docker search Search the Docker Hub for images
docker secret Manage Docker secrets
docker service Manage services
docker stack Manage Docker stacks
docker start Start one or more stopped containers
docker stats Display a live stream of container(s) resource usage statistics
docker stop Stop one or more running containers
docker swarm Manage Swarm
docker system Manage Docker
docker tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
docker top Display the running processes of a container
docker trust Manage trust on Docker images
docker unpause Unpause all processes within one or more containers
docker update Update configuration of one or more containers
docker version Show the Docker version information
docker volume Manage volumes
docker wait Block until one or more containers stop, then print their exit codes

The official reading link: docs.docker.com/engine/refe…

5. Advanced: Simplified warehouse and software installation

Remember “mirrors, containers, and warehouses” that I introduced at the beginning of this article? Docker’s repository is used to store images. We can download images from the central repository or from our own repository. At the same time, we can push the image from the local to the remote repository.

First of all, the author introduces a knowledge point: Docker’s image is its file system, an image can be placed on the upper layer of another image, so the lower layer is its parent image. Therefore, Docker will have many mirror layers, each of which is read-only and will not change. When we create a new container, Docker builds a mirror stack and adds a read-write layer to the top of the stack, as shown.

Now we can view the local image using the Docker images command.

docker images
Copy the code

The query result is shown in the figure.

Here, explain the meanings of a few terms.

  • REPOSITORY: REPOSITORY name.
  • TAG: Mirror label, where lastest indicates the latest version. Note that an image can have multiple tags, so we can manage useful version and feature tags through tags.
  • IMAGE ID: indicates the unique ID of an IMAGE.
  • CREATED: CREATED time.
  • SIZE: indicates the mirror SIZE.

Docker run -p 80 –name web -i -t centos /bin/bash docker run -p 80 –name web -i -t centos /bin/bash Because the image is already installed on this machine, Docker simply creates a new container and launches the program.

In fact, Nginx images are already available for direct use. Now let’s rebuild a Web server by pulling the image. First, we use Docker Search to find the image. We get the image listing for Nginx.

docker search nginx
Copy the code

In addition, we can also search the repository by visiting Docker Hub (hub.docker.com/), so the more stars, the more reliable it is, can be trusted to use.

Now let’s use docker pull nginx to pull the latest nginx image. Of course, we can also do this by docker pull nginx:latest.

docker pull nginx
Copy the code

Then, we create and run a container. Instead, we tell Docker to run the container’s daemon in the background with the -d option. In addition, 8080:80 tells Docker that port 8080 is an open port, and port 80 is an open port mapped to the port number in the container.

docker run -p 8080:80 -d --name nginx nginx
Copy the code

We then check through docker ps -a and find that the container has been running in the background, and the nginx command has been executed in the background, and port 8080 has been opened to the outside world.

Therefore, go to http://127.0.0.1:8080 via your browser.

6. Alternatively, use an alternate registry server

Docker Hub is not the only source of software, we can also switch to other alternative registration servers in China, such as Aliyun. We can search and pull public images at cr.console.aliyun.com.

Now, we enter the docker pull command to pull.

docker pull registry.cn-hangzhou.aliyuncs.com/qp_oraclejava/orackejava:8u172_DCEVM_HOTSWAPAGEN_JCE
Copy the code

Here, the author continues to add a knowledge point: the address of the registration server. In fact, there is a set of specifications for the address of the registry server. The full format is: [warehouse host /][user name /] Container short name [: label]. Here, the repository host is registry.cn-hangzhou.aliyuncs.com, the user name is qp_ORacleJava, the container short name is OrackeJava, and the label name is 8u172_DCEVM_HOTSWAPAGEN_JCE. In fact, we through above docker pull centos: latest pull mirror, equivalent to a docker pull registry.hub.docker.com/centos:latest.

Construct my mirror image

Through the above learning, I believe you have a general understanding of the use of Docker, just like we install a system through VMware, and let it run, then we can work on the Linux system (CentOS or Ubuntu) on anything we want. In fact, we will often take snapshots of our installed VMware system and clone it for our next quick copy. Here, Docker can also build custom content Docker image, such as the above we use the official provided good Nginx Docker image. Note that we only built the new image by adding a mirror layer on top of the existing base image.

To summarize, Docker provides the ability to customize images, which allows us to save changes to the base image and use them again. Then we can package the operating system, runtime environment, scripts, and programs together and serve them externally on the host.

Docker build image there are two ways, one way is to use Docker commit command, the other way is to use Docker build command and Dockerfile file. Among them, it is not recommended to use docker commit command to build, because it does not standardize the whole process. Therefore, in the enterprise, it is more recommended to use docker build command and Dockerfile file to build our image. We use Dockerfile files to make building images more repeatable and to standardize startup scripts and running programs.

1. Build the first Dockerfile

Now, let’s move on. Here, we build an image of the Web server we started with. First, we need to create an empty Dokcerfile file.

mkdir dockerfile_test
cd dockerfile_test/
touch Dockerfile
nano Dockerfile
Copy the code

Next, we need to write a Dockerfile. The code listing is as follows

FROM centos:7
MAINTAINER LiangGzone "[email protected]"
RUN rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
RUN yum install -y nginx
EXPOSE 80
Copy the code

Finally, we build with the Docker build command.

docker build -t="lianggzone/nginx_demo:v1" .
Copy the code

Now let’s take a look at our new image via Docker Images.

2. Understand the whole process of Dockerfile

Wow, we built a new image by writing a Dockerfile. The process is unbelievably simple. Now, let’s understand the whole process. First, FROM centos:7 is a mandatory first step for Dockerfile. It will run a container FROM an existing image. In other words, Docker needs to rely on a base image to build. Here, we specify centos as the base image, which is version 7 (centos 7). MAINTAINER LiangGzone “[email protected]” is used to specify that the author of the image is LiangGzone and the email address is [email protected]. This helps inform the user of its author and contact information. Next, we performed two RUN commands to download and install Nginx, and finally exposed port 80 of the Dokcer container through EXPOSE 80. Note that Docker is executed from top to bottom, so we need to clarify the execution order of the whole process. In addition, Docker creates and commits a new image layer after each instruction.

We use the docker build command to build, specifying -t to tell docker the name and version of the image. Note that if no label is specified, Docker will automatically set a Lastest label for the image. One more thing, we have a. At the end, which is for the Docker to find the Dockerfile in the current local directory. Note that Docker will submit the results as images in each step of build, and then treat the previous image layer as cache. Therefore, when we rebuild similar image layer, we will directly reuse the previous image. If we need to skip, we can use the –no-cache option to tell Docker not to cache.

3. Dockerfile instruction explanation

Dockerfile provides a lot of instructions. The author arranged a list specially here, suggest collect to view.

The official address: docs.docker.com/engine/refe…

Instruction discrimination 1: RUN, CMD, ENTRYPOINT

The three commands RUN, CMD, and ENTRYPOINT have similar uses. The difference is that the RUN command runs when the container is built, while the CMD and ENTRYPOINT command executes shell commands when the container is started. RUN is overwritten by the Docker RUN command, but ENTRYPOINT is not. In fact, any arguments specified by the Docker run command are passed as arguments again to the ENTRYPOINT directive. CMD and ENTRYPOINT can also be used together. For example, we can use ENTRYPOINT’s exec form to set fixed default commands and parameters, and then use either form of CMD to set other defaults that may change.

FROM ubuntu
ENTRYPOINT ["top"."-b"]
CMD ["-c"]
Copy the code

Instruction discrimination 2: ADD, COPY

The use of ADD and COPY commands is the same. The only difference is that ADD supports extracting and decompressing archive files (tar, gzip, bzip2, etc). Note that the COPY command must COPY directories in the same directory as the Dockerfile file.

4. Push the image to the remote repository

Remote repository: Docker Hub

Once the image is built, we can upload it to the Docker Hub. First, we need to make sure we’re logged in via Docker Login. Next, we use the Docker push command to push.

docker push lianggzone/nginx_demo:v1
Copy the code

Docker push [OPTIONS] NAME[:TAG] docker push [OPTIONS] NAME[:TAG] docker push [OPTIONS] NAME[:TAG] docker push [OPTIONS] NAME[:TAG] Docker push [OPTIONS] NAME[:TAG] Docker push [OPTIONS] NAME[:TAG] Docker push [OPTIONS] NAME[:TAG] (note: author push Docker Hub speed is slow, patience) finally, after the completion of the upload access: hub.docker.com/u/lianggzon… /, as shown in the figure.

Remote warehouse: Aliyun

At the same time, we can also use domestic warehouses, such as Aliyun. First, enter access credentials in the terminal to log in to the Registry instance. If you don’t know which one, you can go to cr.console.aliyun.com/cn-hangzhou… .

Docker login --username= account registry.cn-hangzhou.aliyuncs.comCopy the code

Now, push the image to ali Cloud mirror warehouse. Among them, Docker tag [IMAGE_ID] registry.cn-hangzhou.aliyuncs.com/[namespace]/[image name]:[version] and docker push Registry.cn-hangzhou.aliyuncs.com/ [namespace]/[mirror name]: the usage of the [version] command is as follows.

docker tag 794c07361565 registry.cn-hangzhou.aliyuncs.com/lianggzone/nginx_demo:v1
docker push registry.cn-hangzhou.aliyuncs.com/lianggzone/nginx_demo:v1
Copy the code

Finally, after uploading, visit: cr.console.aliyun.com/cn-hangzhou… , as shown in the figure.

5. Dockerfile Github source address

Here, attached is the warehouse of Dockerfile I sorted out. In the future, I will update some commonly used files, welcome star to follow.

Github.com/lianggzone/…

Attached: Reference materials

  • Docker In Action
  • The First Docker Book
  • Docker command reference document
  • Dockerfile Image building reference document

(End, reprint please indicate the author and source.)

Write in the end

[Server-side thinking] : Let’s talk about the core technologies of the server-side and discuss the project architecture and practical experience of the first-line Internet. At the same time, we are looking forward to your joining the big family of “back-end circle” with many technical masters. We are a group of people with the same frequency to grow up together, make progress together and break the limitation of cognition.

More wonderful articles, all in the “server-side thinking”!