Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Foreword, how to explain clearly the authenticity of Docker to the front-end students with zero foundation is not a big challenge, seemingly simple content, but I don’t know where to start, or, HOW dare I share the three points I have learned by myself? After several rounds of in-depth discussion with the backend students, I decided to tell everyone what Docker is and how to use it from the most basic use.

The purpose of this article

If you have enough time and energy, the most direct and effective way is to read the official documents and follow Get Started step by step. One day is enough time to learn.

Hope to help you understand Docker.

This article will introduce:

  • How to install docker (as a reasonable closed loop, this link needs to exist)
  • I first knew Docker and briefly got startted.
  • Run a simple app
  • Build your own mirror image
  • Sharing best Practices
  • Configuration item optimization

The installation

You will need to install the Docker desktop (more than 500MB installation package) locally.

Mac Intel PM me

Mac Apple I

Windows point I

Of course, if you need more types of installation packages, you’ll need to look here

concept

  • Docker dockers?? Container??

Imagine taking 15 elephants from Xishuangbanna to Kunming in a few steps. One head at a time, if helicopters are available, or 15 helicopters can be used; Or put 15 elephants together, put them in a super large container, find a super large plane and transport them to Kunming in one go; Of course, elephants prefer to walk by themselves, and they do. Then the question comes. If it is shipped back to Xishuangbanna from Kunming, is container more convenient? On the way back, you can take the train, and you can put the pineapple that the elephant loves to eat in another container, and you don’t have to worry about being eaten by the elephant. That’s Docker.

- Orderly placement - Standardization - no mutual influenceCopy the code
  • Containers/Apps Containers/applications
  • Mirror Images
  • Volumes mount

I met

After successful installation, this is the screen

We’ll Skip the tutorial by clicking start or Skip tutorial, so we’ll click Skip here and go straight back

Command line execution

docker run -d -p 80:80 docker/getting-started
Copy the code
  • -d The container ID is displayed after the background is successfully started
  • -p Specifies the internal and external mapping port number
  • Docker /getter- Started image name for execution

The command will download and start the Docker /getting-started image locally

~ $ docker run -d -p 80:80 docker/getting-started
Unable to find image 'docker/getting-started:latest' locally
latest: Pulling from docker/getting-started
540db60ca938: Pull complete 
0ae30075c5da: Pull complete 
9da81141e74e: Pull complete 
b2e41dd2ded0: Pull complete 
7f40e809fb2d: Pull complete 
758848c48411: Pull complete 
23ded5c3e3fe: Pull complete 
38a847d4d941: Pull complete 
Digest: sha256:10555bb0c50e13fc4dd965ddb5f00e948ffa53c13ff15dcdc85b7ab65e1f240b
Status: Downloaded newer image for docker/getting-started:latest
8bc8dcde4b87fb57620d0df43f0da3b14688a2c27f15709692ed59497f2127c4
Copy the code

Switch to Images, and you see the mirror that you just pulled

Switch to Containers and you can see the Containers already running, using a browser to access the tutorial

So, what happens in this whole process?

  • An nginx service is started
  • Static some HTML pages

To see how the image is built, use the Inspect option or click on the image name in the container interface

You can log in to the container on the CLI and view physical files

Reunderstand the concept

  • Container, a completely independent native process, is completely isolated from all other processes.
  • Image, which is similar to the ISO we need to install the operating systemDisc mirror imageRun the image to complete the deployment of various applications
  • Each Docker image is like a thousand Layer pie.

Simple application

Let’s take a look at a simple Express-based demo instead of Docker

git clone [email protected]:fuchunhui/docker-start.git
cd docker-start
npm install && node server.js
Copy the code

The code structure is as follows:

  1. server.jsIs the main entrance
import express from 'express'; import path from 'path'; import word from './word.js'; const app = express(); app.use(express.json()); app.use(express.text()); app.use(express.raw()); app.use(express.urlencoded({ extended: false })); const __dirname = path.resolve(); app.use(express.static(path.join(__dirname, 'public'))); app.get('/get', (req, res) => { res.send('get request success.'); }); app.get('/test', (req, res) => { res.send(word.random().join('</br>')); }); app.post('/faces', (req, res) => { const num = req.body? .num || 10; res.send(word.random(num).join('\n\n')); }); app.listen(8080);Copy the code

The app listens on three interfaces

  • /getServer returnget request success.prompt
  • /testReturns a random emoji
  • /facesReturns a random number of emojis and displays them on a newline

After NPM run dev, the browser accesses GET

NPM run POST Tests the POST request

2. Word.js is an emoji character library constructed based on Baidu input method, which provides a random(num) function to randomly return a specified number of emoji

3. Test.js Test word. Js function locally.

4. Public /index.html provides a static page that provides a button to get data, and when clicked, invokes the test request of server.js to display an emoji.

At this point, our demo presentation is complete, so what if we don’t have Node in our native environment? In addition to installing Node locally, we can borrow Docker’s power and build our own image to get the Demo running.

Before continuing, let’s stop the local Node service by holding down Control + C

Build the mirror

We need a file called Dockerfile, whose text content Docker automatically reads to build the image. Dockerfile is a collection of command lines.

Let’s start by building a Node service.

Preparing the Node Environment

touch Dockerfile
Copy the code

Docker Hub and we know npmjs.com, Docker Hub is the source of all images, we search for official Node images

Next, edit the Dockerfile file

FROM node:16
CMD ["node", "--version"]
Copy the code

Build an image for Node16. By default, the current version information is displayed. Then execute the build command

docker build -t node:16 .
Copy the code

Run the docker build in the.(current directory) and generate the image with the name node and tag 16.

Docker-start (main) $docker build-t node:16. [+] Building 440.6s (5/5) FINISHED => [internal] Load Build definition From Dockerfile 2.0s => => dokerfile: Dockerignore 0.0s => => transferring context: 2 b 0.0 s = > (internal) load metadata for docker. IO/library/node: 16 70.2 s = > [1/1] the FROM Docker. IO/library/node: 16 @ sha256:7 a888d7030be38976daabcd0881ff6564fb05885046fef9d08eb6002fa651 370.1 s = > = > resolve Docker. IO/library/node: 16 @ sha256:7 a888d7030be38976daabcd0881ff6564fb05885046fef9d08eb6002fa6516f 0.0 s = > = > Sha256: e1b0cde43c0e73ca4ef26ae54aed841b7e5152f6dd510ad5e5e30cb771265f02 7.60 kB / 7.60 kB of 0.0 s = > = > Sha256:8 f04e8168e3873638397ca4beb7d8484b150eca0d10fe1b033a125202ba57692 50.44 50.44 MB 91.6 MB/s = > = > Sha256: c1c8f1c77d6674046d7deb41be1ca07f25cb43fd67f87e879ee79cc6586087f0 10.00 10.00 MB 6.0 MB/s = > = > Sha256:7 a888d7030be38976daabcd0881ff6564fb05885046fef9d08eb6002fa6516fb 1.21 kB / 1.21 kB of 0.0 s = > = > Sha256:2465 d69d013cb7ea85444fac62310badce86e89c54716999eae31577ec2bc6f3 2.21 kB / 2.21 kB of 0.0 s = > = > Sha256:82 e5f66f5d0e1c97622f33d44fb04efb42bd3562bdc3482537d121040c789f9a 7.83 7.83 MB 17.9 MB/s = > = > Sha256:5095 cab277710f0c2883844158323ad986c763ffc37353ddff874dd85585d9b6 51.84 51.84 MB 25.8 MB/s = > = > Sha256: ea7fe362a971515971cf53613a30cc824f94d544272a5e061eb6365923ccbc11 192.39 192.39 MB 357.4 MB/s = > = > Sha256:9000 ed6ad54103b2ede6fec607e8b3f7cb6a2610158eb76c6091eecd65961179 4.20 kB / 4.20 kB of 27.1 s = > = > Sha256: bda6f8304dc4da996112a502fe92f5636bd29849f06aa75527febd6910342f74 34.19 34.19 MB 43.4 MB/s = > = > Sha256:74 bed10e609e5fb224fd52136389aa57e9b8c35c675be45211e4cd29a8e5675c 2.26 2.26 MB 45.8 MB/s = > = > Sha256:5 bacd780a65fbe617d4d47adf55e74f97d8d0143a021ea55557c75e5c3ae4978 282 b / 282 b 46.3 s = > = > extracting Sha256:8 f04e8168e3873638397ca4beb7d8484b150eca0d10fe1b033a125202ba57692 2.8 s = > = > extracting Sha256:82 e5f66f5d0e1c97622f33d44fb04efb42bd3562bdc3482537d121040c789f9a 0.4 s = > = > extracting Sha256: c1c8f1c77d6674046d7deb41be1ca07f25cb43fd67f87e879ee79cc6586087f0 0.4 s = > = > extracting Sha256:5095 cab277710f0c2883844158323ad986c763ffc37353ddff874dd85585d9b6 3.1 s = > = > extracting Sha256: ea7fe362a971515971cf53613a30cc824f94d544272a5e061eb6365923ccbc11 9.0 s = > = > extracting Sha256:9000 ed6ad54103b2ede6fec607e8b3f7cb6a2610158eb76c6091eecd65961179 0.1 s = > = > extracting Sha256: bda6f8304dc4da996112a502fe92f5636bd29849f06aa75527febd6910342f74 2.2 s = > = > extracting Sha256:74 bed10e609e5fb224fd52136389aa57e9b8c35c675be45211e4cd29a8e5675c 0.2 s = > = > extracting Sha256:5 bacd780a65fbe617d4d47adf55e74f97d8d0143a021ea55557c75e5c3ae4978 0.0 s = > exporting to image 0.1 s = > = > exporting The layers of 0.0 s = > = > writing image sha256:88211 c2be135416f38e0814a33a644ca4224f13ce946b831f4cfcd44f52e2a82 0.0 s = > = > naming to docker.io/library/node:16Copy the code

Open the desktop and in the Images directory, you can see that the Node image has just been generated

Click on the RUN

The default image will execute the node –version command in the agreed way, indicating that the image is successfully built. Next, we will deploy the docker-start content to the docker.

Deploy the executable

Continue editing the Dockerfile file

FROM node:16

WORKDIR /docker-start

COPY . .
RUN npm install --production
CMD [ "node", "server.js" ]
Copy the code

Set docker-start to the working directory and set the Copy all contents of the directory to the docker-start directory, and start the server service after NPM install.

We build a new image from the command line and run the image.

Docker-start is the image name, v1 is the tag, and the build operation is performed in the.(current directory)

Docker-start (main) $docker build-t Docker-start :v1. [+] Building 8.2s (9/9) FINISHED => [internal] FINISHED Definition from Dockerfile 0.9s => => 152B 0.9s => [internal] loading. Dockerignore 0.9s => => transferring-transferring-context: 2 b 0.0 s = > (internal) load metadata for docker. IO/library/node: 16 s = > 0.0 (1/4) FROM docker. IO/library/node: 16 s = 0.0 > [internal] Load build context 0.1s => => transferring-window context: WORKDIR /docker-start 5.0s => [3/4] COPY.. 0.0s => [4/4] RUN NPM install --production 7.1s => exporting to image 0.1s => => exporting layers 0.1s => => Writing image Sha256: c9822dcaf7fdda7107445d13acbc184f269e52909244fefa577c6f2f6299b70 0.0 s = > = > naming the to docker.io/library/docker-start:v1Copy the code

Since we just built a mirror for Node16, we built an image based on Node16 again quickly, using the cache of the previous image.

docker run -dp 8080:8080 docker-start:v1
Copy the code

Run the run command to start the service. -d background run, ‘-p’ specifies the internal and external mapping port number, because we in server.js app.listen(8080), for easy use, directly 1-to-1 mapping.

Open your browser again and visit http://localhost:8080/

Give it a try. There it is again.

  • Browser accesshttp://localhost:8080/getTo check whether the display is displayedget request success.
  • Browser accesshttp://localhost:8080, click on theTo get the dataButton to detect the presence of emoji
  • Command line executionnpm run post, checks whether to output the specified number of emojis, of course, can also be directlycurlOr use another POST request detection

Build optimization

Our command line build process, COPY.. copies all the local content to the target directory, of course, this must include node_modules content, which is not what we want to see, so like.gitignore, we create.dockerignore, Ignore node_modules and redo the build.

touch .dockerignore
echo 'node_modules'>.dockerignore
Copy the code

To see if this works, let’s comment out these two lines of code

FROM node:16

WORKDIR /docker-start

COPY . .
# RUN npm install --production
# CMD [ "node", "server.js" ]

Copy the code

Re-execute the build and mark the new image with tag:v2

docker build -t docker-start:v2 .
Copy the code

Start docker-start:v2 and check to see if node_modules is included

docker run -it --name=start2 docker-start:v2 /bin/bash
Copy the code

Images released

It is basically the same as the NPM publishing process. You need to register an account first, and then use the push command to publish the account after successful local login.

The following uses docker-start:v3 as an example.

First remove two lines of comments from Dockerfile, then modify server.js to add the listen callback

app.listen(8080, () => {
  console.log('server start.');
});
Copy the code

Build THE V3 version

docker build -t docker-start:v3 .
docker tag docker-start:v3 fuchunhui/docker-start
Copy the code

View the image and rename it USER_NAME/image:tag. If no tag is specified, latest is used by default

Create a repO named docker-start at hub.docker.com

Log in locally and push the image

docker login
docker push fuchunhui/docker-start
Copy the code

The speed of uploading depends on the size of the image and the network condition. We wait for a while, and when we are done, we refresh the hub to see

Playground

We can also run our mirror through Palyground

After a successful login, we pull down the newly published image and start it.

docker run -dp 8080:8080 fuchunhui/docker-start
Copy the code

When you’re done, click OPEN PORT in the upper right corner and type 8080, then press Enter.

This is a 4-hour Server. After closing, you can continue to pay for it. It’s so cool.

You can use the logs command to see if the callback just performed

Docker container ls // Obtain the container ID docker logs containerIdCopy the code

Other content

Due to the length, OTHER content will not be introduced too much, the following content is also very exciting, is the beginning of using Docker, recommend you to follow the official document step by Step hands-on practice.

  • Compose, as its name suggests, is a composite, uses YAML files and can perform multiple tasks simultaneously, similar to Github Action or Ci.yml

  • Volumes are used to share the same database, whether you are V1, V2 or V3, and ensure data persistence. The todolist example on the official website is todolist. After each new build, you can see the todo written last time.

  • Network Because each container is isolated from each other, if two containers want to communicate, they need to use A network. Create A network and run two containers under the network to communicate with each other. For example, container A can access data of container B.

Best practices

Personal summary of a few best practices for reference.

  • Each mirror, as clean as possible, provides a single service.
  • Building images, promoted by individual images, builds one by one, ensures service traceability. (Think of a delicious thousand layer cake.)
  • For specific resources that need to be installed, consider loading them in at the top level, such as NPM, without affecting other functionalitycanvasThe package (because it’s particularly hard to install) can be used to keep node_modules available while building the imagenpm installThe trouble.
  • In a single mirror, the fewer control layers, the smaller the volume of the mirror. Therefore, you should try to obtain smaller mirrors to ensure higher transmission speed and deployment efficiency.
  • Choosing the right base image, such as node images for different environments, has a fundamentally different feature set
Mirror node:16 is built based on Debian: Buster. Mirror node:16-stretch is built based on Debian: StretchCopy the code
  • Docker-compose for personal use

Recommended Configuration Items

  1. If we open the configuration center on the desktop, you will find that Docker has taken up 60GB of your hard drive space. I recommend 20GB, which is enough. Note that every time you modify the configuration item, all images, containers, mounts, etc. built locally will be deleted after saving, which is equivalent to an initial setting, so please be careful to operate, do a good backup.

  1. Let’s turn on the Mac’s built-in activity monitor and search the Docker background for stealthily running processes

It’s a little scary, but these things run in the background whether you’re running on the desktop or not (which is great, of course), so when you’re not using Docker, kill them all to reduce CPU load.

conclusion

Broaden your horizons and make your thinking less narrow and limited. As software engineers, it’s ultimately about solving problems, and there are many ways to solve problems, and we should choose the one that is most appropriate, not the one that we are best at.

QA

After sharing, collect your questions and summarize them hereCopy the code

The resources

  • The docker’s official website
  • docker hub
  • docker-start
  • docker-node
  • docker cli
  • Popular understanding of Docker