Author: Jartto.Wang /2020/07/04/…

preface

What is a Docker and what is a virtual container? How to use it? How to create it? Essential for Java development.

In the era of the rich Web, applications are becoming more powerful and complex at the same time. Cluster deployment, isolated environment, gray scale publishing and dynamic capacity expansion are all indispensable, and containerization is a necessary bridge in the middle.

In this paper, we will explore the mysterious world of Docker and master the basic principles and practical operations of Docker from zero to one. It’s time to get out of the back end of the field.

Tell a story

To better understand what Docker is, let’s start with a story:

I needed to build a house, so I carried stones, cut wood, drew drawings, and built a house. After a lot of manipulation, the house was finally built.

The result, lived for a period of time, whim want to move to the seaside. At this time, as usual, I had to go to the seaside, and once again carry stones, chop wood, draw drawings, and build houses.

Trouble, a magician to teach me a kind of magic. This magic can make a “mirror image” of the house I built and carry it in my backpack.

When I get to the seaside, I will use this “mirror” to copy a house and move in with a bag.

Isn’t that amazing? For 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 dynamically expand, pull the project image from the repository and copy it at will. Build once, Run Anywhere!

No longer pay attention to version, compatibility, deployment and other issues, completely solve the embarrassment of “on-line collapse, endless build”.

VMS and containers

Before we get started, let’s do some basics:

① VMS: virtualization hardware

Virtual Machine A Virtual Machine is a complete computer system that is simulated by software and has the functions of a complete hardware system and runs in a completely isolated environment. Everything that can be done in a physical computer can be done in a virtual machine.

When creating a VM on a COMPUTER, use part of the physical machine’s hard disk and memory capacity as the VM’s hard disk and memory capacity.

Each VM has its own CMOS, hard disk, and operating system, and can be operated as a physical vm. Before container technology, the industry’s influencers were virtual machines.

Virtual machine technology is represented by VMWare and OpenStack.

Container: virtualizes the operating system layer, which is a standard software unit

Its characteristics are as follows:

  • Run anywhere: Containers can package code with configuration files and associated dependent libraries to ensure that it runs consistently in any environment.
  • High resource utilization: The container provides process-level isolation so that CPU and memory utilization can be fine-tuned to better utilize the computing resources of the server.
  • Fast scaling: Each container can be run as a separate process and can share the system resources of the underlying operating system, making it faster to start and stop containers.

Differences and connections:

  • Virtual machines can isolate many “child computers,” but they take up more space and start more slowly. Virtual machine software may also cost money, such as VMWare.
  • Container technology does not require the entire operating system to be virtual, just a small virtual environment, like a “sandbox.”
  • Running space, virtual machines generally require a few to dozens of GB of space, while containers only need MB or even KB.

Let’s take a look at the comparative data:

Virtual machines are virtualization technologies, while container technologies like Docker are lightweight virtualization.

A container is lighter and faster than a virtual machine because it takes advantage of the Linux underlying operating system to run in an isolated environment.

The virtual machine’s Hypervisor creates a very strong boundary to prevent applications from breaching it, while the container’s boundary is less strong.

Know the Docker

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, as well as virtualization. Containers are completely sandboxed and have no interface with each other.

The three core concepts of Docker technology are:

  • The mirror Image
  • Container, the Container
  • Warehouse Repository

What makes Docker lightweight? I believe you will also have such doubts: why Docker start fast? How to share the kernel with the host?

When we ask Docker to run the container, Docker sets up a resource-isolated environment on the computer.

The packaged application and associated files are then copied to the file system in the Namespace, and the configuration of the environment is complete. Docker will then execute our pre-specified commands to run the application.

The image does not contain any dynamic data and its contents are not changed after the build.

The core concept

The core concepts are as follows:

  • Build, Ship and Run.
  • Build once, Run anywhere.
  • Docker itself is not a container, it is a tool for creating containers, it is an application container engine.
  • The three core concepts of Docker are: Image Image, Container, and Repository.
  • Docker technology uses the Linux kernel and kernel features such as Cgroups and Namespaces to separate processes so that they run independently of each other.
  • Because the Namespace and Cgroups capabilities are only available on Linux, containers cannot run on other operating systems. So how does Docker work on macOS or Windows? Docker actually uses a trick and installs a Linux virtual machine on a non-Linux operating system and then runs the container inside the virtual machine.
  • An image is an executable package that contains the code, runtime, libraries, environment variables, and configuration files needed to run an application, and a container is a runtime instance of the image.

Install the Docker

(1) Cli installation

Homebrew Cask already supports Docker for Mac, so you can easily install it using Homebrew Cask by running the following command:

brew cask install docker

Copy the code

For more installation methods, please refer to the official document www.docker.com/get-started

② Viewing the version

The command is as follows:

docker -v

Copy the code

3 configure mirror acceleration

Docker Engine write configuration:

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

Copy the code

4 Install the desktop

Desktop operation is very simple, first go to the official website to download. Through Docker desktop, we can easily operate: Clone: clone a project.

  • Build: package the image.
  • Run: runs an instance.
  • Share: indicates a shared mirror.

All right, we’re all set. Now we’re ready to go! Docker complete guide

Quick start

After installing Docker, we will first type a mirror image of the actual project and use it while learning.

1.The first thing you need toTake a look at the 11 commands we will use

The diagram below:

② New project

For speed, we built the project directly using Vue scaffolding:

vue create docker-demo

Copy the code

Try booting it up:

yarn serve

Copy the code

Visit http://localhost:8080/. With the project in place, we proceed to package the project:

yarn build

Copy the code

At this point, Dist in the project directory is our static resource to deploy, and we move on to the next step.

Note that front-end projects generally fall into two categories: direct Nginx static deployment and Node service startup. We will consider only the first in this section. I’ll explain more about Node services later.

(3) new Dockerfile

The command is as follows:

cd docker-demo && touch Dockerfile

Copy the code

The project directory is as follows:

.├ ── All exercises, all exercises, all Exercises, all Exercises, all Exercises, all Exercises, all Exercises yarn.lockCopy the code

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

4 Prepare an Nginx image

Running your Docker desktop will start the instance by default. We pulled the Nginx image from the console:

docker pull nginx

Copy the code

The following information appears 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

Copy the code

If you have such an exception, make sure the Docker instance is working properly.

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

Copy the code

Image ready OK, we create Nginx configuration file in the root directory:

touch default.conf

Copy the code

Writing:

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; }}Copy the code

⑤ Configuring a mirror

Open the Dockerfile and write the following:

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

Copy the code

Let’s explain the code line by line:

  • FROM nginx specifies that the image is built based on nginx:latest image.
  • COPY dist/ /usr/share/nginx/ HTML/COPY dist/ /usr/share/nginx/ HTML/COPY dist/ /usr/share/nginx/
  • COPY the default. The conf/etc/nginx/conf. D/default. Conf will default. The conf COPY to the/etc/nginx/conf. D/default. Conf, Replace the default configuration in the Nginx image with the local default.conf configuration.
docker build -t jartto-docker-demo .

Copy the code

As usual, let’s explain the above code:

  • The -t parameter names the image jartto-docker-demo.
  • . Is based on the current directory Dockerfile to build the image. After successful execution, the following output is displayed:
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:latestCopy the code

Image created successfully! Let’s take a look at the container:

docker image ls | grep jartto-docker-demo

Copy the code

As you can see, we typed out a 133MB project image:

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

Copy the code

There are good and bad mirror images, and we’ll talk about how to optimize them later, but we can ignore them for now.

⑦ Operating container

The command is as follows:

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

Copy the code

Here are the parameters:

  • -d Sets the container to run in the background.
  • -p indicates port mapping. Port 3000 of the local server is mapped to port 80 of the Container. In this way, the Internet can access port 3000 of the local server.
  • –name Sets the container name docker-vue.
  • Jartto-docker-demo is the name of the image we built above.

A sidebar: On the console, we can check the ID of the Container we just ran with Docker ps:

docker ps -a

Copy the code

The console will print:

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-vueCopy the code

If you’re using the desktop, open the Docker Dashboard and you’ll see a list of containers, as shown below:

⑧ Visit Items

Since we mapped the native 3000 port, execute:

curl -v -i localhost:3000

Copy the code

Or open a browser and go to: localhost:3000.

⑨ Publishing an Image

If you want to contribute to the community, you need to publish the image so that other developers can use it.

To publish an image, perform the following steps:

  • Log in to DockerHub and sign up.
  • Command line to execute docker login, and then enter our account password to login.
  • Before pushing an image, add a Tag and run the command
docker tag <image> <username>/<repository>:<tag>

Copy the code

The whole process is over, we will use it in the future, no longer need to “carry stones, cut wood, draw drawings, build houses”, carry bags to move in. This is also the unique charm of Docker.

Normal operation

Congratulations on getting started with Docker! If you want to go further, read on.

① Parameter Usage

FROM: All built images must have a base image. FROM <image>[AS <name>] specifies the name of a new image to be built FROM an image. FROM <image>[:<tag>] [AS <name>] specifies the version tag of the image Example: FROM mysql:5.0 AS Database MAINTAINER: # Image MAINTAINER information MAINTAINER <name> Example: MAINTAINER Jartto [email protected] RUN: Example: RUN [executable, param1, param2] ADD: ADD < SRC > <dest> example: ADD *.js /app ADD js files to the app directory in the container: CMD: # The command to execute after starting the container, unlike RUN, which is the command to RUN when building an image. This can be overridden on the command line when running the container using docker RUN. Example: CMD [executable, param1, param2] ENTRYPOINT: # also executes the command, just like CMD, except that this command is not overridden by the command line: ENTRYPOINT [Donnet, myapp.dll] LABEL: <key>=<value> <key>=<value>... Example: LABEL version=1.0 description= This is a web application ENV: ENV <key> <value> ENV <key>=<value> <key>=<value> <key>=<value> ENV JAVA_HOME /usr/java1.8/ EXPOSE: # When the EXPOSE 80 container runs, you need to map external ports with -p to access the port VOLUME inside the container: VOLUME [/var/log,/var/test.....] VOLUME /var/data var/log; /var/data var/log; WORKDIR <path> example: WORKDIR /app/test USER: USER < USER >:[<group>] Example: USER test ARG: ARG <name>[=<value>] ARG name= SSSCopy the code

More operations, please go to the official use of the document: docs.docker.com/

Best practices

After mastering the Docker general operation, we can easily type the image of the project we want.

However, the image produced by different operations also varies greatly. It’s worth exploring what causes the mirror image difference.

The following are the best practices in Docker application, please try to follow the following guidelines:

  • Require specifies what mirror is required.
  • Simplify steps: Take precedence over steps that change less.
  • Clear version: The image name is clear.
  • Documentation: The entire image packaging step can be repeated.

conclusion

Containerization is bound to be one of the indispensable skills of the cloud age, and Docker is just a drop in the bucket. Cluster container management Kubernetes, Service Mesh, Istio and other technologies followed.

Open the door of Docker, continue to peel off the cocoon, layer by layer, you will feel the endless charm of container.

The last

If you like the article, you can click a “like”. Finally, we will recommend a high-quality technology-related article every day, mainly sharing Java related technology and interview skills, learning Java without getting lost.