The ultimate guide to getting started with Docker, this is the best tutorial I have ever seen!

Click on the blue font above and select "Star Official Account"

High-quality articles, delivered immediately

Follow the official account backstage to reply to pay or mall to obtain actual project information + video

Author: jartto

Source: jartto.wang/2020/07/04/learn-docker/

In the rich  Web era, applications have become more powerful and at the same time more and more complex. Cluster deployment, isolated environment, grayscale release, and dynamic expansion are indispensable, and containerization becomes a necessary bridge in between.

In this section, we will explore  Docker the mysterious world, master Docker the basic principles and practical operations from zero to one  . Stop guarding the one-acre three-quarters at the front end, it's time to expand the territory.

We will focus on the following points:

  1. Tell a story

  2. Virtual machine and container

  3. understanding Docker

  4. Key concept

  5. installation Docker

  6. Quick start

  7. Routine operation

  8. Best Practices

1. Tell a story

In order to better understand  Docker what it is, let's first tell a story:

I need to build a house, so I move stones, chop wood, draw blueprints, and build a house. After an operation, the house was finally built.

As a result, after living for a while, I wanted to move to the beach on a whim. At this time, according to the previous method, I can only go to the beach, move stones, chop wood, draw drawings, and build houses again.

When I was troubled, a magician came to teach me a kind of magic. This kind of magic can make a copy of the house I built, make it a "mirror", and put it in my backpack.

img

dark magic

When I get to the beach, I use this "mirror" to copy a house and move in with my bags.

Isn’t it amazing? Corresponding to our project, the house is the project itself, the mirror is the copy of the project, and the backpack is the mirror warehouse. If you want to expand the capacity dynamically, take out the project image from the warehouse and copy it at will. Build once, Run anywhere!

No longer need to pay attention to issues such as version, compatibility, deployment, etc., and completely solve the embarrassment of "crash when online, endless construction".

Two, virtual machines and containers

Before we start, let's make some basic knowledge reserves:

1. Virtual machine : virtualized hardware

A virtual machine  Virtual Machine refers to a complete computer system with complete hardware system functions that is simulated by software and runs in a completely isolated environment . The work that can be done in the physical computer can be realized in the virtual machine.

When creating a virtual machine in a computer, part of the hard disk and memory capacity of the physical machine needs to be used as the hard disk and memory capacity of the virtual machine. Each virtual machine has its own  CMOShard disk and operating system, and can operate on the virtual machine just like a physical machine . Before container technology, the industry’s influencers were virtual machines.

Behalf of the virtual machine technology, are  VMWare and  OpenStack.

2. Container : It virtualizes the operating system layer and is a standard software unit

  • Run anywhere: The container can package code with configuration files and related dependent libraries to ensure consistent operation in any environment.

  • High resource utilization: The container provides process-level isolation, so you can fine-tune settings  CPU and memory usage, and make better use of the server's computing resources.

  • Rapid expansion: Each container can be run as a separate process and can share the system resources of the underlying operating system, which can speed up the start and stop efficiency of the container.

3. Differences and connections

  • Although virtual machines can isolate many "child computers", they take up more space and start more slowly. Virtual machine software may also cost money, for example VMWare;

  • Container technology does not need to virtualize the entire operating system, only a small-scale environment, similar to a "sandbox";

  • Running space, virtual machines generally require a few  GB to dozens  GB of space, while containers only need to be  MB level or even  KB level;

Let's take a look at the comparative data:

Compared with virtual machines, containers are lighter and faster because they use the  Linux underlying operating system to run in an isolated environment. The virtual machine  Hypervisor creates a very strong boundary to prevent the application from breaking through it, while the container boundary is not so strong.

Physical machine deployment cannot make full use of resources, resulting in waste of resources. Virtual machine deployment, the virtual machine itself will take up a lot of resources, resulting in waste of resources, and the performance of the virtual machine is also very poor. The containerized deployment is more flexible, lightweight, and has better performance.

Virtual machines are virtualization technologies, and container technologies such as Docker are lightweight virtualization.

Three, get to know Docker

img

Docker

1. Concept

Docker It is an open source application container engine that allows developers to package their applications and dependent packages into a portable container, and then publish it to any popular  Linux machine, which can also be virtualized. Containers use the sandbox mechanism completely, and there will be no interfaces between them.

Docker The three core concepts of technology are: mirroring  Image, container  Container, and warehouse Repository.

2. Docker The reason for being lightweight?

I believe you will also have such doubts: Why is the  Docker startup fast? How to share the kernel with the host?

When we request to  Docker run the container, Docker a resource-isolated environment will be set up on the computer. Then copy the packaged application and associated files to the  Namespace internal file system. At this time, the configuration of the environment is complete. After  Docker that, the pre-specified command will be executed to run the application.

The image does not contain any dynamic data, and its content will not be changed after it is built.

Fourth, the core concept

1. Build, Ship and Run(Setup, transportation, operation);

2. Build once, Run anywhere(Build once, run everywhere);

3. Docker It is not a container itself, it is a tool to create a container, it is an application container engine;

4. The Docker three core concepts are: mirroring  Image, container  Container, warehouse  Repository;

5. Docker Technology uses the  Linux kernel and kernel functions (such as  Cgroups and  namespaces) to separate processes so that each process runs independently of each other.

6. Since the  Namespace and  Cgroups functions are only  Linux available on the Internet, the container cannot run on other operating systems. So  Docker how does  it run on  macOS or  Windows? Docker In fact, I used a trick Linux to install a Linux virtual machine on a non-  operating system  , and then run the container inside the virtual machine.

7. The image is an executable package that contains the code, runtime, libraries, environment variables and configuration files required to run the application. The container is the runtime instance of the image .

Five, install Docker

1. Command line installation

Homebrew The  Cask already supported  Docker for Mac, so you can easily use  Homebrew Cask to install, execute the following command:

brew cask install docker

For more installation methods, please check the official document:

https://www.docker.com/get-started

2. View version

docker -v  

3. Configure mirror acceleration

Set Docker Engine write configuration:

{
  "registry-mirrors": [
    "http://hub-mirror.c.163.com/",
    "https://registry.docker-cn.com"
  ],
  "insecure-registries":[],
  "experimental": false,
  "debug": true
}

4. Install the desktop

img

Docker desktop

The desktop operation is very simple, first go to the official website to download. Through the  Docker desktop, we can conveniently operate:

  1. clone: ​​clone a project

  2. build: package image

  3. run: run the instance

  4. share: share mirror

Okay, the preparations are ready, now you can show your skills!

Six, start quickly

After the installation  Docker , we first make a mirror image of the actual project and use it while learning.

1. First, we need to get a general understanding   of the commands we will use11

2. New project

For speed, we directly use Vue scaffolding to build the project:

vue create docker-demo  

Try to start it:

yarn serve  

Access http://localhost:8080/address: . The project is ready, we then package the project:

yarn build  

At this time, Dist the static resources we want to deploy are in the project directory  , and we continue to the next step.

Note : Front-end projects are generally divided into two categories, one is directly  Nginx deployed statically, and the other requires Node services to be started  . In this section we only consider the first one.

3. New Dockerfile

cd docker-demo && touch Dockerfile  

The project directory at this time is as follows:

.  
├── Dockerfile  
├── README.md  
├── babel.config.js  
├── dist  
├── node_modules  
├── package.json  
├── public  
├── src  
└── yarn.lock  

You can see that we have docker-demo successfully created a Dockerfile file in the  directory  .

4. Prepare the  Nginx mirror

Run your  Docker desktop, it will start the instance by default, we pull the Nginx image in the console  :

docker pull nginx  

The following information will appear on the console:

Using default tag: latest
latest: Pulling from library/nginx
8559a31e96f4: Pull complete
8d69e59170f7: Pull complete
3f9f1ec1d262: Pull complete
d1f5ff4f210d: Pull complete
1e22bfa8652e: Pull complete
Digest: sha256:21f32f6c08406306d822a0e6e8b7dc81f53f336570e852e25fbe1e3e3d0d0133
Status: Downloaded newer image for nginx:latest
docker.io/library/nginx:latest

If you have such an exception, please confirm  Docker whether the instance is running normally.

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?  

To prepare for mirroring  OK, we create a Nginx configuration file in the root directory  :

touch default.conf  

Write:

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/error.log  error;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

5. Configure mirroring

Open  Dockerfile and write the following:

FROM nginx  
COPY dist/ /usr/share/nginx/html/  
COPY default.conf /etc/nginx/conf.d/default.conf  

Let's explain the code line by line:

  • FROM nginx Specify that the image is nginx:latest built based on the  image;

  • COPY dist/ /usr/share/nginx/html/ The command means to dist copy all files in the folder under the project root directory to the directory  in the mirror  /usr/share/nginx/html/ ;

  • COPY default.conf /etc/nginx/conf.d/default.conf Will be  default.conf copied to  etc/nginx/conf.d/default.conf, default.conf replace  Nginx the default configuration in the mirror with the local  configuration.

6. Build the image  to build the image Docker through the  buildcommand:

docker build -t jartto-docker-demo .  

By convention, we explain the above code:

  • -t Parameter to name the image jartto-docker-demo

  • . Is based on the current directory  Dockerfile to build a mirror

After successful execution, it will output:

Sending build context to Docker daemon  115.4MB
Step 1/3 : FROM nginx
 ---> 2622e6cca7eb
Step 2/3 : COPY dist/ /usr/share/nginx/html/
 ---> Using cache
 ---> 82b31f98dce6
Step 3/3 : COPY default.conf /etc/nginx/conf.d/default.conf
 ---> 7df6efaf9592
Successfully built 7df6efaf9592
Successfully tagged jartto-docker-demo:latest

The mirror is made successfully! Let's take a look at the container:

docker image ls | grep jartto-docker-demo  

As you can see, we have typed a  133MB project mirror:

jartto-docker-demo latest 7df6efaf9592 About a minute ago 133MB  

Mirroring is also good or bad. We will introduce how to optimize it later, which can be ignored for now.

7. Run the container

docker run -d -p 3000:80 --name docker-vue jartto-docker-demo  

Explain the parameters here:

  • -d Set the container to run in the background

  • -p Represents port mapping, the 3000 port to which container the  80 port of the machine is  mapped  (so that the external network can be accessed through the 3000 port of the machine 

  • --name Set container name docker-vue

  • jartto-docker-demo Is the name of the image we built above

Add this: In the console, we can  docker ps see just ran  Container a  ID:

docker ps -a  

The console will output:

CONTAINER ID IMAGE              COMMAND                  CREATED       STATUS PORTS  NAMES
ab1375befb0b jartto-docker-demo "/docker-entrypoint.…"   8 minutes ago Up 7 minutes  0.0.0.0:3000->80/tcp  docker-vue

If you use the desktop, you Docker Dashboard can see the container list when you open  it, as shown in the figure below:

8. Visit the project

Because we mapped the local  3000 port, execute:

curl -v -i localhost:3000  

Or open the browser and visit:localhost:3000

9. Publish the image

If you want to contribute to the community, then you need to publish the image for the convenience of other developers.

The following steps are required to publish a mirror:

  • Log in  [dockerhub](https://hub.docker.com)and register an account;

  • Execute the command line  docker login, and then enter our account password to log in;

  • Before pushing the image, you need to type one  Tagand execute docker tag <image> <username>/<repository>:<tag>

After the whole process is over, we will use it in the future. We no longer need to "move rocks, chop wood, draw drawings, and build houses", and move in with bags. This is also the  docker unique charm.

Seven, conventional operations

Here, congratulations on Docker the introductory project you have completed  ! If you still want to go deeper, you might as well look down.

1. Parameter usage

FROM:
#指定基础镜像,所有构建的镜像都必须有一个基础镜像,且 FROM 命令必须是 Dockerfile 的第一个命令
FROM <image> [AS <name>] 指定从一个镜像构建起一个新的镜像名字
FROM <image>[:<tag>] [AS <name>] 指定镜像的版本 Tag
示例:FROM mysql:5.0 AS database

MAINTAINER:
#镜像维护人的信息
MAINTAINER <name>
示例:MAINTAINER Jartto [email protected]

RUN:
#构建镜像时要执行的命令
RUN <command>
示例:RUN [executable, param1, param2]

ADD:
#将本地的文件添加复制到容器中去,压缩包会解压,可以访问网络上的文件,会自动下载
ADD <src> <dest>
示例:ADD *.js /app 添加 js 文件到容器中的 app 目录下

COPY:
#功能和 ADD 一样,只是复制,不会解压或者下载文件

CMD:
#启动容器后执行的命令,和 RUN 不一样,RUN 是在构建镜像是要运行的命令
当使用 docker run 运行容器的时候,这个可以在命令行被覆盖
示例:CMD [executable, param1, param2]

ENTRYPOINT:
#也是执行命令,和 CMD 一样,只是这个命令不会被命令行覆盖
ENTRYPOINT [executable, param1, param2]
示例:ENTRYPOINT [donnet, myapp.dll]

LABEL:
#为镜像添加元数据,key-value 形式
LABEL <key>=<value> <key>=<value> ...
示例:LABEL version=1.0 description=这是一个web应用

ENV:
#设置环境变量,有些容器运行时会需要某些环境变量
ENV <key> <value> 一次设置一个环境变量
ENV <key>=<value> <key>=<value> <key>=<value> 设置多个环境变量
示例:ENV JAVA_HOME /usr/java1.8/

EXPOSE:
#暴露对外的端口(容器内部程序的端口,虽然会和宿主机的一样,但是其实是两个端口)
EXPOSE <port>
示例:EXPOSE 80
容器运行时,需要用 -p 映射外部端口才能访问到容器内的端口

VOLUME:
#指定数据持久化的目录,官方语言叫做挂载
VOLUME /var/log 
#指定容器中需要被挂载的目录,会把这个目录映射到宿主机的一个随机目录上,实现数据的持久化和同步
VOLUME [/var/log,/var/test.....] 
#指定容器中多个需要被挂载的目录,会把这些目录映射到宿主机的多个随机目录上,实现数据的持久化和同步

VOLUME /var/data var/log 
#指定容器中的 var/log 目录挂载到宿主机上的 /var/data 目录,这种形式可以手动指定宿主机上的目录

WORKDIR:
#设置工作目录,设置之后 ,RUN、CMD、COPY、ADD 的工作目录都会同步变更
WORKDIR <path>
示例:WORKDIR /app/test

USER:
#指定运行命令时所使用的用户,为了安全和权限起见,根据要执行的命令选择不同用户
USER <user>:[<group>]
示例:USER test

ARG:
#设置构建镜像是要传递的参数
ARG <name>[=<value>]
ARG name=sss

For more operations, please move to the official documentation:

https://docs.docker.com/

8. Best Practices

After mastering the  Docker normal operations, we can easily create the project mirror we want. However, the images produced by different operations are also very different.

What causes the mirror image difference, we may as well continue to explore.

The following are Docker the best practices in the application  process , please follow the following guidelines as much as possible:

  1. Require Be clear: what mirroring is needed

  2. Streamlined steps: Step Priority with fewer changes 

  3. Clear version: clear image name

  4. Documentation: The entire image packaging steps can be reproduced

Nine, summary

Containerization technology is bound to be one of the indispensable skills in the cloud era, but  Docker only a drop in the ocean. There followed a cluster container management  K8s, Service Mesh , Istio and other technologies. Open  Docker the door, continue to peel off the cocoon, go deeper and deeper , and you will feel the infinite charm of containerization.

Hurry up and open the skill boundary and empower your front-end technology!




有热门推荐????
再见,xShell,自己用Java撸一个Web版的,网友直呼:6662020 国内互联网公司的薪酬排名,加班时长排名 !IDEA这样 配置注释模板,让你高出一个逼格!!
Java后端线上问题排查常用命令收藏SpringBoot+Prometheus+Grafana实现应用监控和报警10个解放双手实用在线工具,有些代码真的不用手写!微信小程序练手实战:前端+后端(Java)
又一神操作,SpringBoot2.x 集成百度 uidgenerator搞定全局ID为什么要在2021年放弃Jenkins?我已经对他失去耐心了...

点击阅读原文,前往学习SpringCloud实战项目

Guess you like

Origin blog.csdn.net/qq_17231297/article/details/115019223