Touch your hands and take you docker from introduction to practice

Time:2021-9-14

Touch your hands and take you docker from introduction to practice

I recently encountered the scenario of installing mysql, nginx, easymock and other tools on the server. Here is a record of my installation process using docker. I hope I can help you in similar scenarios

The pre knowledge of this article requires some basic commands of Linux. Let’s take a look at them first< essential basic knowledge for CentOS introduction in half an hour >This article.

CentOS version:7.6

Nginx version:1.16.1

Docker version:19.03.12

If you learn more than one skill, you should say less begging

1. Introduction

1.1 causes

During the process from front-end development to test to production, I often encounter a problem. Obviously, I have no problem running locally. Why do I report an error when I go to the test environment or production environment? This is often caused by different development, test and production environments and configurations.

People who have tossed about the environment configuration understand the trouble. If you change a system, virtual machine or machine, you have to do it again, which is laborious and time-consuming. Due to the environment and configuration, all kinds of strange bugs always appear like hamsters in the hamster game

Touch your hands and take you docker from introduction to practice

Docker provides a good solution to this problem. It packages the system environment required in addition to the system from bottom to top through image, so as to achieve the seamless operation of services across platforms. That is as like as two peas, when the installation is done, the specific environment is moved exactly to solve the problem of “running on my computer and running in XX environment”.

Another important reason is lightweight, container based virtualization. Docker’s image only contains the runtime environment required for business operation, and a CentOS / Ubuntu basic image is only 170m, because a host can easily install hundreds of containers.

1.2 what is it

Docker is a cloud open source project based on go language, which has been widely concerned since its release in 2013. Docker allows you to quickly assemble applications like using containers, and can shield code level differences as much as possible like transporting standard containers. It packages the application and its dependencies in a file. Running this file will generate a virtual container.

The program runs in this virtual container as if it were running on a real physical machine. With docker, you don’t have to worry about environmental problems.

This article doesn’t compare the differences and advantages and disadvantages between virtual machines and docker. Every article is rotten. If you want to know, you can baidu. I won’t say more here. Let’s take a direct look at how to install and use it.

2. Installation & Configuration

2.1 installation under mac

Under Mac, you can directly use homebrew cask to install

#Homebrew installation
$ braw cask install docker

After installation, enter the command and report an error directly!

➜  ~ docker
Zsh: command not found: docker # error

Don’t worry about this error. After installation, double-click the docker application in the application list and enter the password to use this command.

2.2 installation under CentOS

Docker requires that the CentOS version must be 6.5 or above before installation.

#Installation
$ sudo yum install yum-utils device-mapper-persistent-data lvm2
$ sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
$ sudo yum install docker-ce

#Open docker
$ sudo systemctl start docker

On windows, you can directlyDownload installation packageTo install, or you can go without homebrew on the MacOfficial websiteDirectly download the installation package to install it. Baidu has installation methods everywhere, and there is no need to say more about others.

3. Simple configuration and running

3.1 configuring image acceleration

Docker configuration in MacOSPerferences -> Docker EngineOr windowsSettings -> DeamonAdd an item to JSON inregistry-mirrorsas follows

Touch your hands and take you docker from introduction to practice

After configuration, on the command linedocker infoYou can view the image acceleration address we configured.

➜  ~ sudo docker info
...
 Registry Mirrors:
  https://reg-mirror.qiniu.com/
  http://hub-mirror.c.163.com/
  https://registry.docker-cn.com/
...

If the docker of your system does not have a client, such as CentOS, you can directly modify the Deamon configuration file:

#Modify / create the daemon configuration file of docker
$ sudo vi /etc/docker/daemon.json

#Modify to the following configuration
{
  "experimental": false,
  "debug": true,
  "registry-mirrors": [
    "https://reg-mirror.qiniu.com",
    "http://hub-mirror.c.163.com",
    "https://registry.docker-cn.com"
  ]
}

#Modified: WQ restart
$ sudo systemctl restart docker

3.2 Hello World !

Then we can run happily. Our first docker instruction is hello world

Touch your hands and take you docker from introduction to practice

Good start ! 🎉

4. Image & Container & Warehouse

The relationship between an image and a container is like that between a class and an instance of a class. An image can run multiple containers at the same time, and a single container instance can create a new image. As shown below:

Touch your hands and take you docker from introduction to practice

Let’s explain the elements that appear in this figure

concept explain
Docker image Read only for creating docker containersTemplateFor example, Ubuntu 16.04 system and nginx 1.16.0 are special file systems, including programs, libraries, resources, parameters, etc. required for container running, but they do not contain any dynamic data, and the content will not be changed after construction. One image can create multiple containers
Docker container A container is an application or group of applications running independently and isolated from each other. It is a running instance created by an image. It is essentially a process and can be regarded as a processSimple linux environment + applications running in it
Docker client The client uses the docker SDK through the command line or other tools(https://docs.docker.com/devel…Communicate with docker’s daemon
Docker host A physical or virtual machine is used to execute docker daemon and container
Docker repository The centralized storage of image files is divided into public warehouse and private warehouse.
Docker registration server registry It is a service for centralized storage and distribution of images, which is officially calledDocker Hub。 A docker registry can contain multiple warehouses. Each warehouse can contain images of multiple tag tags. Different tags correspond to different versions
Docker Machine Docker machine is a command line tool to simplify docker installation. Docker can be installed on corresponding platforms through a simple command line, such as VirtualBox, digital ocean and Microsoft azure

Lifecycle diagram of a container

Touch your hands and take you docker from introduction to practice

The five core states of the container are represented by the color blocks in the figure: created, running, paused, stopped and deleted:

  1. Created: the container has been created and the relevant resources required by the container are ready, but the programs in the container are not running yet.
  2. Running: the container is running, that is, the applications in the container are running.
  3. Paused: the container is paused, indicating that all programs in the container are paused (not stopped).
  4. Stopped: the container is stopped, the occupied resources and sandbox environment still exist, but the applications in the container have been stopped.
  5. Deleted: the container has been deleted, and the related resources and management information stored in docker have been released and removed.

This article mainly focuses on the use, so I won’t repeat the switching of these states. Let’s start directly below.

5. Basic use

5.1 operation command

#Start docker and start automatically
$ sudo systemctl enable docker

#Close docker and start up automatically
$ sudo systemctl disable docker

5.2 mirror command

#To download the image, first look for it locally, but not to the image, and finally not to the hub. The tag is not written, and the default is lastest
$docker pull [image name]: [tagtag]

#List all image files on this machine, - a displays all local images (including intermediate images), - Q displays only image ID, - digests displays summary information of images
$ docker image ls
$ docker images

#Delete image files, -f force image deletion
$docker RMI [image name] [: tag]
$docker RMI [image name 1] [: tag] [image name 2] [: tag] # delete multiple
$docker RMI $(docker PS - A - Q) # delete all, followed by subcommands

#Query the image name, -- no TRUNC displays the complete image description, -- filter = stars = 30 lists the images with star not less than the specified value, -- filter = is automated = true lists the images of automatic build type
$docker search [keyword]

#Download the image. The tag tag is not written. The default is lastest. You can also add it yourself, such as 3.2.0
$docker pull [image name] [: tag]

5.3 container command

#List the running containers of the local machine, - a list all containers of the local machine, including those terminated, - Q silent mode displays only the container number, - L display the recently created container
$docker container LS # is equivalent to the following command
$ docker ps

#New and start container
$docker run [option] [container name] 

#Start container
$docker start [container ID] / [container names]

#Restart container
$docker restart [container ID] / [container names]

#Terminate container operation
$docker kill [container ID] # forcibly terminates, which is equivalent to sending sigkill signal to the main process in the container. All ongoing operations will be lost
$docker kill $(docker PS - A - Q) # forcibly terminate all containers
$docker stop [container ID] # calmly terminates, which is equivalent to sending a SIGTERM signal to the main process in the container, and then sending a sigkill signal after a period of time
$docker stop $(docker PS - A - Q) # terminate all containers

#The container file that terminates the operation will still occupy the hard disk space. You can use the docker container RM command to delete it, - f forced deletion can delete the running container
$docker RM [container ID]
$docker RM ` docker PS - AQ ` # deletes all containers that have been stopped, because RM that has not been stopped cannot be deleted, and - f needs to be added

#View the output of the container, - t add a timestamp, - f print with the latest log, - tail number displays the last number. If - it is not used when docker runs, use this command to view the output
$docker logs [container ID]

#Viewing container process information
$docker top [container ID] / [container names]
$docker port [container ID] / [container names]

#Exit container
$exit # container exit
CTRL + P + Q # container exit, shortcut key

#Enter container
$ docker attach [容器ID]      #Exit container时会让容器停止,本机的输入直接输到容器中
$ docker exec -it [容器ID]    #Exit container时不会让容器停止,在已运行的容器中执行命令,不创建和启动新的容器

#Set the container to start automatically when docker starts
$docker container update -- restart = always [container name]

I want to say something special heredocker runofoption, because most commonly used:

  1. --nameSpecify a name for the container;
  2. -dAfter the container is started, enter the background and return the container ID, that is, start the guardian container;
  3. -PRandom port mapping;
  4. -p 80:8080Mapping the local port 80 to the 8080 port of the container;
  5. bashAfter the container is started, it is the first command executed internally. Start bash here to ensure that users can use shell;
  6. -iRun the container in interactive mode, usually with-tSimultaneous use;
  7. -tReassign a pseudo input terminal to the container, the shell of the container will be mapped to the current shell, and then the command entered in the local window will be passed into the container, which is usually associated with-iSimultaneous use;
  8. --rmAutomatically delete the container file after the container terminates;
  9. --restart=alwaysSet container self start;
  10. -v /xxx:/yyyThe mapping command maps the local XXX directory to the YYY directory in the container, that is, changing the content under the local XXX directory will also change the content in the container YYY directory;

For example, I run a docker container of CentOS under CentOS:

#Download
$ docker pull centos

#Based on the CentOS image downloaded above, create a new CentOS instance named mycentos0901 and enter the bash of this container
$ docker run -it --name mycentos0901 0d120b6ccaa8

[ [email protected] /]# enter the container and enter the command below. Note the string of IDS after root
$LS # can see the list of CentOS root files
$docker # bash: docker: command not found this container does not have docker installed

Isn’t it amazing that we can execute it under CentOS at the beginningdocker psTo view the container list:

Touch your hands and take you docker from introduction to practice

You will find that the ID above is the ID of the container running in the following list, and the ID of the image is also the ID in front of uspullThe following CentOS image ID and name are also given by usmycentos0901

Ifdocker runPost reportConflict. The container name "xxxx" is already in use by containerJust run directlydocker rm $(docker ps -a -q)Delete stopped containers, or delete exactlydocker rm [containerID]Yes, that’s all.

5.4 command usage in several common scenarios

Daemon boot container

usecentosStart a container in background modedocker run -d --name mycentos0903 0d120b6ccaa8, after startupdocker ps -aIt is found that the container is not running because of the docker’s operating mechanism:Docker container runs in the background, and there must be a foreground process

If the commands run by the container are not those that have been suspended, such astoptail, it will exit automatically after running. Therefore, in order to keep the container running in the background, you need to run the running program in the form of a previous process.

For example, there is a command running in the background, which is printing all the timedocker run -d centos /bin/sh -c "while true; do echo hello zzyy; sleep 2; done"And then welogsCheck:

Touch your hands and take you docker from introduction to practice

Operate on the container after exiting the container

After exiting the container, you canexecMethod to operate on a running container:

Touch your hands and take you docker from introduction to practice

Copy files in container to external

Copy file usagecpcommand

$docker CP [container ID] / [container names]: [directory of files to be copied] [local directory] # copy container files to the local computer
$docker CP [local directory] [container ID] / [container names]: [file directory to copy] # local files are copied to the container

cpNot only the files / folders in the container can be copied to the local machine, but also the files / folders in the local machine can be copied to the container.

To demonstrate, first go to the container to create a boring filexixi.txt, and then copy to this computer:

Touch your hands and take you docker from introduction to practice

When practical, we can copy configuration, log and other files locally.

6. Install MySQL

#Query image
$ docker search mysql

#Downloading the image is actually slow when the image acceleration is not configured. It's better to configure it
$ docker pull mysql

#View mirror
$ docker images

#Create and run containers
$ docker run -d -p 3307:3306 -e MYSQL_ROOT_PASSWORD=888888 -v /Users/sherlocked93/Personal/configs/mysql.d:/etc/mysql/conf.d --name localhost-mysql mysql

Explain the above parameters a little:

  1. -p 3307:3306Map the 3307 port of the local machine to the 3306 port of the MySQL container, and change it as needed;
  2. -e MYSQL_ROOT_PASSWORD=<string>Set the root user password for remote login;
  3. --name <string>Optional, set container alias;
  4. -v xxx/mysql.d:/etc/mysql/conf.dMap the settings folder under the local directory to the container/etc/mysql/conf.d
  5. -v xxx/logs:/logsThe specified directory of this machinelogsDirectory mounted to container/logs
  6. -v xxx/data:/var/lib/mysqlSet the host to the directorydataDirectory mounted to container/var/lib/mysql

Operation screenshot:

Touch your hands and take you docker from introduction to practice

Then go to Navicat to connect to MySQL.

That’s great! It’s really installed with a few lines of command. It’s much happier than before

7. Install nginx

The installation of nginx is similar to others. If you don’t know how to use nginx, you can see< nginx explains everything in detail from introduction to practice >After reading this article, you will basically understand how to use and configure it.

#Query / Download Image
$ docker search nginx
$ docker pull nginx

Touch your hands and take you docker from introduction to practice

Then create a temporary container to copy the default configuration to the local machine. I’ll put the configuration file here/mntUnder the directory, there are mainly three configuration folders:

  1. /etc/nginxPlace the nginx configuration file;
  2. /var/log/nginx/Place nginx log files;
  3. /usr/share/nginx/html/Put the static files of the nginx front end in this folder;

Copy these directories to the local directory/mntUnder foldernginxnginx_logshtmlfolder.

The temporary container just created is uselessDocker RM - f [temporary container ID]Dry out the temporary container, and thendocker runRecreate the nginx container:

$ docker run -d --name localhost-nginx -p 8082:80 \
-v /mnt/nginx:/etc/nginx \
-v /mnt/nginx_logs:/var/log/nginx \
-v /mnt/html:/usr/share/nginx/html \
--privileged=true nginx

--privileged=trueIndicates that the container has read and write privileges for the mounted directory.

Other configurations have just been mentioned above, so there should be no need to talk about them.

Touch your hands and take you docker from introduction to practice

Then you can access it on your own browser. If it is a ECs, remember to open the corresponding port.

8. Install easy mock

Because easy mock relies on redis and mongodb, it should be a best practice for the local environment to use docker compose to build easy mock.

Install docker compose

Official documents:https://docs.docker.com/compose/install/

First of all, you have to make sure that you have a docker environment. If you are a Windows / Mac user, you will install the client and bring your own docker compose.

Because we are building on ECs centos7.6 this time, we need to install docker compose by ourselves. Run the following command to download the current stable version of docker compose

$ sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

Modify file permissions to executable

$ sudo chmod +x /usr/local/bin/docker-compose

Verify that the installation was successful

$ docker-compose version

Write the docker-compose.yml configuration file

Can refer toOfficial documentsFor the deployment documents given, you can also refer to my following configuration process.

Create a new file firstdocker-compose.ymlAnd copy the contents of the following docker compose file into thedocker-compose.yml, and then replace the comment location in the content with the local address you need

version: '3'

services:
  mongodb:
    image: mongo:3.4.1
    volumes:
      #/ apps / easy mock / data / DB is the storage address of database files, which can be modified to the local address as needed
      - '/apps/easy-mock/data/db:/data/db'
    networks:
      - easy-mock
    restart: always

  redis:
    image: redis:4.0.6
    command: redis-server --appendonly yes
    volumes:
      #/ apps / easy mock / data / redis is the storage address of redis data files, which can be modified to the local address as needed
      - '/apps/easy-mock/data/redis:/data'
    networks:
      - easy-mock
    restart: always

  web:
    image: easymock/easymock:1.6.0
    #The official file of easy mock is NPM start, which is modified to NPM run dev
    command: /bin/bash -c "npm run dev:server"
    ports:
      -7300:7300 # change to your own desired mapping
    volumes:
      #Log address, which can be changed to local address as needed
      - '/apps/easy-mock/logs:/home/easy-mock/easy-mock/logs'
    networks:
      - easy-mock
    restart: always

networks:
  easy-mock:

Start easy mock

In the docker compose file directory, run the following command:

$ docker-compose up -d

If an easymock docker instance is encountered, a file permission error is reported

Error: EACCES: permission denied....

To execute the following command at the project root

$ chmod 777 /yourfile/logs

Then you can use theYour domain name. Com: 7300Visit easy mock!

If you think the port number followed by the domain name is ugly, you can access the easy mock you deployed by configuring the secondary domain name of nginx. For the method of configuring the secondary domain name, seeThis article

9. Visual management

Here is a brief introduction to the visual query toolLazyDocker, because it runs on the terminal and supports keyboard operation and mouse click, it is very coquettish. With this, some query statements can be typed a few times less.

The installation is relatively simple. Run the following command:

$ docker run --rm -it -v \
/var/run/docker.sock:/var/run/docker.sock \
-v ~/.config/lazydocker:/.config/jesseduffield/lazydocker \
lazyteam/lazydocker

You can set the alias of a terminal

$ alias lzd='docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock -v ~/.config/lazydocker:/.config/jesseduffield/lazydocker lazyteam/lazydocker'

Then you enter it at the terminallzdYou can browse your image, container, log, configuration, status, etc.

10. Conclusion

Since the main scenario of using docker in the current scenario is the installation of tools such as MySQL and nginx, most of the contents introduced in this article also belong to this scenario.

Space reasons docker has some contents that are not introduced in this article, but the above contents have basically met daily use. For other docker contents, please pay attention to the following articles ~


Most of the online posts are different in depth and even contradictory. The next articles are a summary of the learning process. If you find an error, you are welcome to leave a message and point it out~

Reference documents:

  1. Empowering app development for developers docker official website
  2. Docker core technology (Fundamentals)
  3. Docker installation MySQL
  4. Docker document
  5. Docker compose document
  6. Run easy mock with docker – know what
  7. Docker compose easy mock – simple book
  8. Run easy mock | codingdiary with docker
  9. Easymock official docker warehouse: easy mock / easy mock docker
  10. Installing nginx using docker

Other highly praised articles by the author:

  1. Tips to improve happiness in JS
  2. Tips for using Vue
  3. Nginx from introduction to practice, ten thousand words in detail!
  4. Half an hour to get started with CentOS
  5. Hands on webpack multi entry configuration practice
  6. Basic principle of front-end routing jump

PS: my blog addressGithub – SHERlocked93/blogI also welcome you to pay attention to my official account [front end afternoon tea].

Touch your hands and take you docker from introduction to practice