[Container technology - basic use of Docker]

docker

1 Overview

1.1 what is

A Docker image is a special file system. In addition to providing the programs, libraries, resources, configuration and other files required by the container runtime, it also contains some configuration parameters prepared for runtime (such as anonymous volumes, environment variables, users, etc. )

Docker supports compiling software into an image, and then configures various software in the image, and releases the image, so that other users can directly use this image. The running image is called a container, and the container starts very quickly.

That is, the packaged software, all environments are configured, and it can be used out of the box without further configuration

  • Mirroring, packaged software, released, equivalent to a software template (similar to a class in Java)
  • Container, get the image to the local, run it, it is a container (similar to an instance of a class in Java)
  • The docker host is the local machine
  • The docker warehouse, where the image is stored, is similar to git
  • Docker registers the warehouse server, where the warehouse is stored, which is equivalent to github

insert image description here

1.2 Related resources

Article reference:

  • https://blog.csdn.net/u010358168/article/details/86711551?spm=1001.2014.3001.5506
  • https://blog.csdn.net/qq_39611230/article/details/108641842

related resources:

  • Docker official homepage: https://www.docker.com
  • Docker official blog: https://blog.docker.com/
  • Docker official documentation: https://docs.docker.com/
  • Docker Store: https://store.docker.com
  • Docker Cloud: https://cloud.docker.com
  • Docker Hub: https://hub.docker.com
  • Alibaba Cloud Accelerator: https://help.aliyun.com/document_detail/60750.html
  • Netease Accelerator: http://hub-mirror.c.163.com
  • Official China Accelerator: https://registry.docker-cn.com
  • Mirror of ustc: https://docker.mirrors.ustc.edu.cn

2 use

2.1 Mirroring

2.1.1 Pull image

The command to get an image from a Docker registry is docker pull. Its command format is:

  • Docker mirror warehouse address: the format of the address is generally <域名/IP>[:端口号]. The default address is Docker Hub( docker.io)
  • Warehouse name: <用户名>/<软件名>. For Docker Hub, if no username is given, the default is library, which is the official image
  • version, mysql defaults to the latest mysql:latest if no version is added
# 官方镜像
docker image pull 镜像名称 
# 或简写为 
docker pull 镜像名称
# 比如
docker pull ubuntu
docker pull ubuntu:18.04

# 个人镜像
docker pull 仓库名称/镜像名称
docker pull xunmi/django

# 第三方仓库拉去
docker pull 第三方仓库地址/仓库名称/镜像名称
docker pull hub.c.163.com/library/mysql:latest
(默认仓库名为library,所有从官方获取镜像相当于`sudo docker image pull library/镜像名称`)

2.2.2 List images

docker image ls
# 或者
docker images

docker image ls ubuntu:18.04

2.2.3 Delete image

docker image rm 镜像名/镜像ID 
# 或简写为
docker rmi 镜像名/镜像ID

docker image rm hello-world
docker rmi 9e64176cd8a2

2.2 Container

2.2.1 Running the container

The image is just a read-only file, we need to load this image into our environment, that is, turn it into a container.

docker run [可选参数] 镜像名 [向启动容器中传入的命令]
Common optional parameters effect
-i Indicates to run the container in interactive operation.
-d A daemon container will be created to run in the background (so that the container will not be automatically logged in after the container is created).
-t Indicates that the container will enter its command line after it starts. -it indicates that the container requires an interactive terminal, that is, allocates a pseudo-terminal.
–name Give the created container a name. (The name will be given randomly by default, Chinese characters are not supported!!!)
-v Directory mapping, that is, host directory: directory in the container. Note: It is best to do directory mapping, modify it on the host, and then share it to the container.
-p Port mapping, that is, host port: port in the container. For example: -p 8080:80 is to map port 80 in the container to port 8080 in the host
-network=host Indicates that the network environment of the host is mapped to the container. Using this command will allow the container and the host to share a network space.
  • After the image name is the command , here we hope to have an interactive shell, so we usebash
docker run -it ubuntu:18.04 bash

# 启动docker lab容器,输入localhost:8080即可使用
docker run -d -p 8080:80 docker/getting-started

# Docker 以 ubuntu15.10 镜像创建一个新容器,然后在容器里执行 bin/echo "Hello world",然后输出结果
runoob@runoob:~$ docker run ubuntu:15.10 /bin/echo "Hello world"
Hello world

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ZMbgvnN4-1674114793665) (C:\Users\sommer.liu\Desktop\Study Notes\Back-end development technology stack \docker.assets\image-20230119150147176.png)]

2.2.2 View container

# 查看当前所有正在运行的容器
docker ps
# 查看当前所有的容器
docker ps -a
# 使用过滤器(除了name外,常用的还可以指定id:id= 、所有停止的容器:status=exited,正在运行的容器:status=running 等)
docker ps -f name=指定的名字
# 显示2个上次创建的容器(2可以改变)
docker ps -n 2
# 显示最新创建的容器(包括所有状态)
docker ps -l
# 仅显示ip
docker ps -q
 # 显示容器大小
docker ps -s

2.2.3 Starting and shutting down containers

The difference between stop and kill: stop is similar to exiting a software normally, while kill is to forcibly close a process when an accident occurs and cannot be closed normally, a bit like using the task manager to end the process

# 停止容器
docker container stop 容器名/容器id
# 或可简写为
docker stop 容器名/容器id

# 强制关闭容器
docker container kill 容器名/容器id
# 或可简写为
docker kill 容器名/容器id

# 启动容器
docker container start 容器名/容器id
# 或可简写为
docker start 容器名/容器id

2.2.4 Delete container

If an error Error response from daemon: You cannot remove a running container 容器ID. Stop the container before attempting removal or force removeis reported, it means that the container has been started, and you need to execute docker stop container id to stop the container

# 使用rm删除容器
docker rm 容器名/容器id
# 列如
docker rm docker-test

2.3 Make a mirror image

# 将容器制作成镜像
docker commit 容器名 镜像名
# 镜像打包备份(打包备份的文件会自动存放在当前命令行的路径下,如果想让保存的文件可以打开,可以加.tar后缀)
docker save -o 保存的文件名 镜像名
# 镜像解压
docker load -i 文件路径/备份文件

2.4 Docker repository

At present, Docker officially maintains a public warehouse Docker Hub . Most of the requirements can be achieved by directly downloading images in Docker Hub.

2.4.1 Register and log in

Sign up for a Docker account for free at https://hub.docker.com . You need to enter the user name and password to log in. After the login is successful, we can pull all the images under our account from the docker hub.

$ docker login

img

Exit docker hub can use the following command:

$ docker logout

2.4.2 Push image

After the user logs in, he can push his image to Docker Hub through the docker push command.

docker tag ubuntu:18.04 username/ubuntu:18.04 
docker push username/ubuntu:18.04

2.5 dockerfile

Dockerfile is a text file used to build a mirror, and the text content contains instructions and instructions for building a mirror.

Write the commands for modification, installation, construction, and operation of each layer into a script, and use this script to build and customize the image. This script is the Dockerfile.

Note : Every time the instructions of the Dockerfile are executed, a new layer will be created on the docker. Therefore, too many meaningless layers will cause the image to expand too much. Connect the commands with the && symbol, and only one layer of mirroring will be created after execution.

2.5.1 Build image

Execute the build action in Dockerfilethe directory where the file is located. You can build an nginx:v3 (image name: image label) through the Dockerfile in the directory.

docker build [选项] <上下文路径/URL/->

docker build -t dtf_service:v1 .	#这个.是在指定上下文目录,docker build 命令会将该目录下的内容打包交给 Docker 引擎以帮助构建镜像
docker build -t nginx:v3 .  # 指定了最终镜像的名称 -t nginx:v3
# docker build 还支持从 URL 构建,比如可以直接从 Git repo 中构建
docker build -t hello-world https://github.com/docker-library/hello-world.git #master:amd64/hello-world

The context path means that when docker builds the image, sometimes it wants to use the local files (such as copying). After the docker build command knows this path, it will package all the contents under the path.

Analysis : Since the operating mode of docker is C/S. Our native machine is C, and the docker engine is S. The actual build process is done under the docker engine, so our local files cannot be used at this time. This requires the files in the specified directory of our local machine to be packaged and provided to the docker engine for use.

If the last parameter is not specified, the default context path is where the Dockerfile is located.

Note : Do not put useless files in the context path, because they will be packaged together and sent to the docker engine. If there are too many files, the process will be slow.

2.5.2 dockerfile example

from ubuntu:latest #指定基础镜像

run apt update \		# shell格式的命令,就像直接在命令行中输入的命令一样
    && apt install sudo \
    && apt install net-tools \
    && apt install jq -y \
    && mkdir /home/djitool 
    
    
copy .  /home/djitool/   # 从上下文目录中复制文件或者目录到容器里指定路径

run cd /home/djitool/ \
    && sudo ./upgrade.sh

expose 5100 5101 #声明容器运行时提供服务的端口,仅仅是声明容器打算使用什么端口而已,并不会自动在宿主进行端口映射。

entrypoint ["/home/dji/dtf/start.sh","5101"]

Command summary for dockerfile

  • FROM - where the image came from

  • MAINTAINER - Mirror maintainer information

  • RUN- Build the command executed by the image, each RUN will build a layer

  • CMD- The command started by the container, if there are more than one, the last one will prevail, and parameters can also be provided for ENTRYPOINT

  • VOLUME - defines the data volume, if not defined the default is used

  • USER - Specifies the user group and user for subsequent executions

  • WORKDIR - switch the currently executing working directory

  • HEALTHCHECH - Health check command

  • ARG - variable attribute value, but does not work inside the container

  • EXPOSE - expose the port

  • ENV - variable attribute value, also works inside the container

  • ADD - add files, if compressed files also decompress

  • COPY - Add files, as copied

  • ENTRYPOINT - the command to execute when the container enters

Self-starting at boot: Both ENTRYPOINT and CMD allow the user to specify an executable program, which will automatically start after the container starts .

CMDThe role is to specify specific parameters

  • Shell format: CMD <command>, shellin the format, the actual command will be packaged as sh -ca parameter for execution, and docker is invoked with the syntax of /bin/sh -c.
  • exec format: CMD ["executable file", "parameter 1", "parameter 2"...], followed by a syntax similar to JSON to indicate the command to be executed. This usage tells docker that there is no need to call /bin/ sh execute command
CMD ["executable","param1","param2"] (exec form, this is the preferred form)
CMD ["param1","param2"] (as default parameters to ENTRYPOINT)
CMD command param1 param2 (shell form)

# 例如
FROM ubuntu:trusty
CMD ping localhost # 相当于实际运行的命令是 /bin/sh -c 'ping localhost'.
CMD ["/bin/ping","localhost"] 
# 例如
CMD ["/bin/echo", "this is a echo test"]
# 运行镜像
docker run test  # docker run命令如果指定了参数会把CMD里的参数覆盖,如docker run -it ubuntu /bin/bash 
# 输出
this is a echo test

ENTRYPOINT entry point

It is used to set the command and its parameters to be run first when the container is starteddocker run <image> . Any parameters passed in using the command will be appended entrypointafter the command

  • ENTRYPOINT specifies the default running command, and CMD specifies the default running parameters. When ENTRYPOINT and CMD exist at the same time, docker splices the CMD command to the ENTRYPOINT command, and the spliced ​​command is the final executed command
FROM ubuntu:trusty
ENTRYPOINT ["/bin/ping","-c","3"]
CMD ["localhost"] 
# 相当于  /bin/ping -c 3 localhost,用shell命令行发送ping请求3次

ENTRYPOINT [ "sh", "-c", "echo $HOME" ] # 相当于 sh -c echo $HOME,即用shell命令行 执行echo $HOME命令

Another form is to use a script as ENTRYPOINTthe value. By convention, entrypointkeywords are usually included in script names. In this script, you can make relevant configurations, set environment variables, etc., for example, the following code:

COPY ./docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["postgres"]

For example, here is what the script in the official Postgres mirror looks like:ENTRYPOINT

#!/bin/bash
set -e
if [ "$1" = 'postgres' ]; then
    chown -R postgres "$PGDATA"
    if [ -z "$(ls -A "$PGDATA")" ]; then
        gosu postgres initdb
    fi
    exec gosu postgres "$@"
fi
exec "$@"

3 Practical development

Copy native content into docker containerdocker cp 源地址 容器名称:目标地址

docker cp  D:\cts\cts-0825 59082bc9f284fe4b1309e3bd617b65c5506c6446f8098b317114f9e11b0a3f9b:/app/

View existing port docker image

docker run -it -p 8080:8080  yushl/tomcat  /bin/bash	 # 指定本机端口映射容器端口

docker run -it -p 127.0.0.1:5100:5100 -p 127.0.0.1:5102:5102  ubuntu  # 指定本机ip:端口映射

View running containers:docker ps

View the port mapping information of the container:docker port 容器名称

Every time you start a new ubuntu container, the original downloaded things will not be

# 增加新的用户
adduser sommer
# 修改用户的sudo 权限

vim /etc/sudoers
# 在/etc/sudoers文件中找到root	ALL=(ALL:ALL) ALL,在该行下面添加:
sommer	ALL=(ALL:ALL) ALL

# 包括但不限于以下update方法
sudo apt-get update
sudo apt-get upgrade
sudo apt update

# 下载安装 vim sudo
apt-get update
apt-get install vim
apt-get install sudo

4 Docker Commands Encyclopedia

Container Lifecycle Management

container operations

Container rootfs command

mirror warehouse

Local image management

info|version

Guess you like

Origin blog.csdn.net/qq_42647903/article/details/128735685