Docker commonly used commands collection

Docker commonly used commands collection

1. Introduction to docker

  • Docker is an open source application container engine, based on the Go language and open source following the Apache2.0 protocol.
  • Docker allows developers to package their applications and dependent packages into a lightweight, portable container, and then publish to any popular Linux
    machine, it can also be virtualized.
  • Containers use the sandbox mechanism completely, and there will not be any interfaces between each other (apps similar to iPhone), and more importantly, the container performance overhead is extremely low.
  • Docker has been divided into CE (Community Edition: Community Edition) and EE (Enterprise Edition: Enterprise Edition) since version 17.03, we can use the Community Edition

Two, Docker application scenarios

Automated packaging and publishing of Web applications.
Automated testing and continuous integration and release.
Deploy and adjust databases or other background applications in a service-oriented environment.
Compile or extend the existing OpenShift or Cloud Foundry platform from scratch to build your own PaaS environment.

2.1 Advantages of Docker

Docker is an open platform for developing, delivering and running applications. Docker enables you to separate applications from infrastructure so that software can be delivered quickly. With Docker, you can manage your infrastructure in the same way you manage applications. By using Docker's method to quickly deliver, test, and deploy code, you can greatly reduce the delay between writing code and running it in a production environment.
(1) Deliver your applications quickly and consistently.
Docker allows developers to use the local containers of the applications or services you provide to work in a standardized environment, thus simplifying the development life cycle.
Containers are great for continuous integration and continuous delivery (CI/CD) workflows. Consider the following example scenario:
Your developers write code locally and use Docker containers to share their work with colleagues.
They use Docker to push their applications into the test environment and perform automated or manual testing.
When developers find errors, they can fix them in the development environment and then redeploy them to the test environment for testing and verification.
After the test is completed, pushing the patch to the production environment is as simple as pushing the updated image to the production environment.
(2) Responsive deployment and expansion

Docker is a container-based platform that allows highly portable workloads. Docker containers can be run on the developer's machine, on a physical or virtual machine in the data center, on a cloud service, or in a hybrid environment.
Docker's portability and lightweight features can also enable you to easily complete the workload of dynamic management, and according to business needs instructions, real-time expansion or removal of applications and services.
(3)
Docker is light and fast to run more workloads on the same hardware . It provides a viable, economical, and efficient alternative to virtual machines based on hypervisors, so you can use more computing power to achieve business goals. Docker is very suitable for high-density environments and small and medium-sized deployments, and you can do more with fewer resources.

Three, Docker architecture

  • Docker includes three basic concepts:
    Image: Docker image is equivalent to a root file system. For example, the official mirror ubuntu:16.04 contains a complete set of the root file system of Ubuntu 16.04 minimal system.
    Container: The relationship between the image and the container is like the class and instance in object-oriented programming. The image is a static definition, and the container is the entity of the image at runtime. Containers can be created, started, stopped, deleted, suspended, etc.
    Repository: The repository can be regarded as a code control center for storing images.
    Docker uses a client-server (C/S) architecture model and uses remote APIs to manage and create Docker containers.
    Docker containers are created through Docker images.
    The relationship between containers and mirrors is similar to objects and classes in object-oriented programming.
  • Docker object-oriented
  • Container object
  • Mirror class
    Insert picture description here

Four, docker installation

  • Deploy version 19 of docker

4.1 install dependencies


yum -y install yum-utils device-mapper-persistent-data lvm2

//yum-utils 提供了yum-config-manager 

//device mapper 存储驱动程序需要device-mapper-persistent-data和lvm2

//device mapper 是Linux2.6内核中支持逻辑卷管理的通用设备映射机制。

//它为实现用于存储资源管理的块设备驱动提供了一个而高度模块化的内核架构

4.2 Set Alibaba Cloud Image Source


yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

4.3 install docker-ce


yum -y install docker-ce

systemctl start docker.service

systemctl enable docker.service 

setenforce 0

vim /etc/selinux/config
SELINUX=disabled

4.4 Image acceleration

Enter Alibaba Cloud official website" "Search Mirror Acceleration" "Select the centos version


sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
    
    
  "registry-mirrors": ["https://1i3tpy0i.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

4.5 Network optimization


vim /etc/sysctl.conf
net.ipv4.ip_forward=1

sysctl -p

service network restart
systemctl restart docker

Five, docker image use

  • View docker version
docker version
  • Search Nginx mirror (public warehouse)
docker  search nginx
  • Download Nginx image
docker pull  nginx
  • Download the latest official image of Redis, which is equivalent to: docker pull redis:latest

docker pull redis

  • Download all Redis images of the warehouse

docker pull -a redis

  • After downloading the private warehouse mirror
    , the establishment of the private library will be introduced in detail
docker pull bitnami/redis
  • AUFS (Associated File System) several layers download
  • Stored in /var/lib/docker after downloading
  • /var/lib/docker/image/overlay/repositories/json //Download file information
  • View mirror list

docker images  //查看下载镜像信息
[root@localhost opt]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              7e4d58f0e5f3        8 days ago          133MB

    REPOSITORY:表示镜像的仓库源

    TAG:镜像的标签

    IMAGE ID:镜像ID

    CREATED:镜像创建时间

    SIZE:镜像大小
//含中间映像层
docker images -a

//只显示镜像ID
docker images -q
//含中间映像层
docker images -qa 

//显示镜像摘要信息(DIGEST列)
docker images --digests
//显示镜像完整信息
docker images --no-trunc

  • Get mirror information

docker inspect 7e4d58f0e5f3 

  • Add new label

docker tag nginx:latest  nginx:web

[root@localhost opt]# docker tag nginx:latest  nginx:web
[root@localhost opt]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
nginx               latest              7e4d58f0e5f3        8 days ago          133MB
nginx               web                 7e4d58f0e5f3        8 days ago          133MB

//查看镜像Nginx信息

[root@localhost opt]# docker images | grep nginx 
nginx               latest              7e4d58f0e5f3        8 days ago          133MB
nginx               web                 7e4d58f0e5f3        8 days ago          133MB

  • Delete mirror
docker rmi  nginx:web   (如果只有一个别名,那么这个就是删除docker。如果是多个标签,那么就是只是删除一个标签)

  • Delete docker
docker rmi  docker——id  注:删除docker如果有其他别名需要删除只剩一个,才能删除docker
在删除容器之前需要先停止容器

  • Single image deletion, equivalent to: docker rmi redis:latest
docker rmi redis
  • Forced deletion (for container processes running based on images)
docker rmi -f redis
  • Delete multiple mirrors, separated by spaces between different mirrors
docker rmi -f redis tomcat nginx
  • Delete all local mirrors in batch

docker rmi -f $(docker images -q)

  • The exported Nginx image is named Nginx and stored in the directory opt

docker save -o 文件名 镜像id或者镜像别名

[root@localhost ~] docker save -o /opt/nginx 7e4d58f0e5f3 
[root@localhost opt] docker save -o nginx1 nginx:latest 
[root@localhost ~]cd /opt
[root@localhost opt] ll
总用量 133636
drwx--x--x. 4 root root        28 9月  17 15:43 containerd
-rw-------. 1 root root 136841216 9月  19 19:04 nginx
drwxr-xr-x. 2 root root         6 10月 31 2018 rh

  • Import image

docker load --input export file name

docker load <export file name


[root@localhost opt] docker load --input nginx 
Loaded image ID: sha256:7e4d58f0e5f3b60077e9a5d96b4be1b974b5a484f54f9393000a99f3b6816e3d

[root@localhost opt] docker load < nginx
Loaded image ID: sha256:7e4d58f0e5f3b60077e9a5d96b4be1b974b5a484f54f9393000a99f3b6816e3d
[root@localhost opt] docker load --input nginx1
Loaded image: nginx:latest

Six, the use of docker container

  • Container creation

docker create -it nginx:latest /bin/bash

[root@localhost opt] docker create -it nginx:latest /bin/bash
59c4c2f2b6a00bceb196f1bbcfe02fc5a2e16edc66feb12310c9474bf939d833

  • -i: Interactive operation.
  • -t: terminal.
  • /bin/bash: After the image name is the command, here we want to have an interactive shell, so /bin/bash is used.
  • docker run: Create a new container and run a command
语法

docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

OPTIONS说明:

    -a stdin: 指定标准输入输出内容类型,可选 STDIN/STDOUT/STDERR 三项;

    -d: 后台运行容器,并返回容器ID;

    -i: 以交互模式运行容器,通常与 -t 同时使用;

    -P: 随机端口映射,容器内部端口随机映射到主机的端口

    -p: 指定端口映射,格式为:主机(宿主)端口:容器端口

    -t: 为容器重新分配一个伪输入终端,通常与 -i 同时使用;

    --name="nginx-lb": 为容器指定一个名称;

    --dns 8.8.8.8: 指定容器使用的DNS服务器,默认和宿主一致;

    --dns-search example.com: 指定容器DNS搜索域名,默认和宿主一致;

    -h "mars": 指定容器的hostname;

    -e username="ritchie": 设置环境变量;

    --env-file=[]: 从指定文件读入环境变量;

    --cpuset="0-2" or --cpuset="0,1,2": 绑定容器到指定CPU运行;

    -m :设置容器使用内存最大值;

    --net="bridge": 指定容器的网络连接类型,支持 bridge/host/none/container: 四种类型;

    --link=[]: 添加链接到另一个容器;

    --expose=[]: 开放一个端口或一组端口;

    --volume , -v: 绑定一个卷

实例

使用docker镜像nginx:latest以后台模式启动一个容器,并将容器命名为mynginx。

docker run --name mynginx -d nginx:latest

使用镜像nginx:latest以后台模式启动一个容器,并将容器的80端口映射到主机随机端口。

docker run -P -d nginx:latest

使用镜像 nginx:latest,以后台模式启动一个容器,将容器的 80 端口映射到主机的 80 端口,主机的目录 /data 映射到容器的 /data。

docker run -p 80:80 -v /data:/data -d nginx:latest

绑定容器的 8080 端口,并将其映射到本地主机 127.0.0.1 的 80 端口上。

$ docker run -p 127.0.0.1:80:8080/tcp ubuntu bash

使用镜像nginx:latest以交互模式启动一个容器,在容器内执行/bin/bash命令。

runoob@runoob:~$ docker run -it nginx:latest /bin/bash

  • View container
docker ps -a

[root@localhost opt] docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
59c4c2f2b6a0        nginx:latest        "/docker-entrypoint.…"   2 minutes ago       Created                                 pedantic_bose

//显示最近创建容器
docker ps -l

//显示最近创建的3个容器
docker ps -n 3

//不截断输出
docker ps --no-trunc 

//获取镜像redis的元信息
docker inspect redis

//获取正在运行的容器redis的 IP
docker inspect --format='{
    
    {range .NetworkSettings.Networks}}{
    
    {.IPAddress}}{
    
    {end}}' redis

//查看正在运行的容器
docker ps

//查看正在运行的容器的ID
docker ps -q

//查看正在运行+历史运行过的容器
docker ps -a

//显示运行容器总文件大小
docker ps -s

  • Start the container

docker start 59c4c2f2b6a0

查看镜像 up 状态
[root@localhost opt] docker start 59c4c2f2b6a0
59c4c2f2b6a0
[root@localhost opt] docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
59c4c2f2b6a0        nginx:latest        "/docker-entrypoint.…"   3 minutes ago       Up 9 seconds        80/tcp              pedantic_bose

  • Stop container
docker stop 容器ID
  • Restart container
docker restart 容器ID
  • Start the execution command to view the system root directory

docker pull centos 7
docker create it centos 7 /bin/bash
docker start 8c6dd3246eb4  

docker run nginx /usr/bin/bash -c ls 

  • Close immediately after the execution, the status is exited

  • Continuous execution in the background

  • Container entry


[root@localhost opt] docker exec -it 8c6dd3246eb4 /bin/bash

docker exec :在运行的容器中执行命令

    -d :分离模式: 在后台运行

    -i :即使没有附加也保持STDIN 打开

    -t :分配一个伪终端

 docker exec -i -t  mynginx /bin/bash

docker exec -it 9df70f9a0714 /bin/bash

exit   退出

  • Container export

 docker export 8c6dd3246eb4 > nginx_c
 
 8c6dd3246eb4:容器ID
 
 Nginx_c :导出容器文件名 
 
  • Container import (image will be generated, but container will not be created)

cat nginx_c | docker import - nginx:web

 nginx_c:导出的容器文件名
 
 nginx:web:新的容器名
 
  • Delete the container (the container must be stopped)

[root@localhost opt] docker rm 8c6dd3246eb4 
Error response from daemon: You cannot remove a running container 8c6dd3246eb42099dbf58e2730f348acc21b685a4f27c60185d9a427e1282f09. Stop the container before attempting removal or force remove
[root@localhost opt] docker stop 8c6dd3246eb4
8c6dd3246eb4
[root@localhost opt] docker rm 8c6dd3246eb4
8c6dd3246eb4

  • Delete containers in bulk

方法一:docker ps -a | awk '{print "docker rm $1"}' | bash

方法二:
[root@localhost opt]docker rm -f $(docker ps -aq)
395dab3d44df
2b52ff42681f
1627dc7213cd
960857ff1ba0
59c4c2f2b6a0
 

//强制杀死进程容器(处于运行状态才能杀死进程-docker start id)

docker kill  id

  • Delete a running container
docker rm -f redis
  • Delete multiple containers

docker rm -f $(docker ps -a -q)
docker ps -a -q | xargs docker rm

  • -l Remove the network connection between containers, the connection name is db
docker rm -l db 
  • -v delete the container and delete the data volume mounted by the container

docker rm -v redis

  • Delete none mirror

vim none.sh

docker ps -a | grep "Exited" | awk '{print $1}'|xargs docker stop
docker ps -a | grep "Exited" | awk '{print $1}'|xargs docker rm
docker images|grep none|awk '{print $3}'|xargs docker rmi

  • -f: Forcefully delete a running container through the SIGKILL signal.

  • -l: Remove the network connection between containers, not the container itself

  • -v: Delete the volume associated with the container.

  • Container process



//top支持 ps 命令参数,格式:docker top [OPTIONS] CONTAINER [ps OPTIONS]


//列出redis容器中运行进程

docker top redis(容器ID)


//查看所有运行容器的进程信息

for i in  `docker ps |grep Up|awk '{print $1}'`;do echo \ &&docker top $i; done

  • Container log

//查看redis容器日志,默认参数
docker logs rabbitmq

//查看redis容器日志,参数:-f  跟踪日志输出;-t   显示时间戳;--tail  仅列出最新N条容器日志;
docker logs -f -t --tail=20 redis

//查看容器redis从2019年05月21日后的最新10条日志。
docker logs --since="2019-05-21" --tail=10 redis

  • docker pause: Pause all processes in the container

  • docker unpause: Resume all processes in the container.


实例

暂停数据库容器db01提供服务。

docker pause db01

恢复数据库容器db01提供服务。

docker unpause db01

Seven, create a mirror

  • Create an image based on an existing image container

docker create -it jasonlix/docker-cobbler /bin/bash

docker commit -m "new" -a "daoke" c83aee844ae0 daoke:test

docker images | grep daoke

  • Create based on local template

将文件debian-7.0-x86-minimal.tar.gz拖至opt目录中

[root@localhost opt] cat debian-7.0-x86-minimal.tar.gz | docker import - daoke:new
sha256:6683b936f5574560c919751a6622d4131bb7fb4d88f7a9614c55fb7f554ef2c0

[root@localhost opt] docker images | grep new
daoke                       new                 6683b936f557        13 seconds ago      215MB
 

  • Build image based on dockerfile

mkdir apache

cd apache

vim Dockerfile

#基于的基础镜像
FROM centos
#维护镜像的用户信息
MAINTAINER The project <[email protected]>
#镜像操作指令安装Apache软件
RUN yum -y update
RUN yum -y install httpd
#开启80端口
EXPOSE 80
#复制网站首页文件
ADD index.html /var/www/html/index.html
#将执行脚本复制到镜像中
ADD run.sh /run.sh
RUN chmod 755 /run.sh
#启动容器时执行脚本
CMD ["/run.sh"]

vim run.sh

#!/bin/bash
rm -rf /run/httpd/*
exec /usr/sbin/apachectl -D FOREGROUND

echo "web test" > index.html

  • Production mirror

docker build -t httpd:centos1 .    (注意别忘了末尾有“.”)

  • New image running container

docker run -d -p 1216:80 httpd:centos1 

docker start 4fbc428fac3a  (开启容器)

[root@localhost apache]docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS                  NAMES
4fbc428fac3a        httpd:centos1       "/run.sh"                8 seconds ago       Up 7 seconds                0.0.0.0:1216->80/tcp   affectionate_lovelace
a4f43a12352e        registry            "/entrypoint.sh /etc…"   2 hours ago         Exited (2) 40 minutes ago                          goofy_bose
ba786a224305        registry            "/entrypoint.sh /bin…"   2 hours ago         Exited (127) 2 hours ago                           zen_hamilton

  • Test the real browser
  • http://192.168.75.200:1216/

Eight, docker data management

(1) Data management operation

  • Conveniently view the data generated in the container
  • Data sharing among multiple containers

(2) Two management methods

  • Data volume: shared between host and container
  • Data volume container: shared between container and container
  • Data volume: is a special directory for containers

(3) Create data volume


docker run -d -v /data1 -v /data2 --name web httpd:centos

  • Mount the host directory as a data volume (synchronize the host directory with the container directory)

docker run -d -v /var/www:/data1 --name web-1 httpd:centos

  • web-1 refers to the container name, httpd: centos is a mirror, it means to mount a directory and generate a container web-1 mirror as httpd and the label is centos

docker pull centos

//宿主机目录/var/www挂载容器中的/data1

docker run  -v /var/www:/data1 --name web1 -it centos /bin/bash

cd /data1
touch test123

//返回宿主机进行查看

ls /var/www

  • Data volume container

//数据卷容器

docker run --name web100 -v /data1 -v /data2 -it centos /bin/bash  ##(加/bin/bash 就是可以直接进入容器)

  • New container mount data volume container web100

docker run -it -volumes-from web100 --name db1 centos /bin/bash

注释:容器web100 和容器db1 所挂载的目录data1和data2 数据是同步运行的。

  • Port Mapping

docker run -d -p httpd:centos

docker run -d -p 49280:80 httpd:centos

docker ps -a

Nine, local private warehouse establishment


docker pull registry

[root@localhost /]# docker pull registry
Using default tag: latest
latest: Pulling from library/registry
cbdbe7a5bc2a: Pulling fs layer 
47112e65547d: Pulling fs layer 
46bcb632e506: Pulling fs layer 
c1cc712bcecd: Pulling fs layer 
3db6272dcbfa: Pulling fs layer 
latest: Pulling from library/registry
cbdbe7a5bc2a: Pulling fs layer 
47112e65547d: Pulling fs layer 
46bcb632e506: Pulling fs layer 
c1cc712bcecd: Pulling fs layer 
3db6272dcbfa: Pulling fs layer 
open /var/lib/docker/tmp/GetImageBlob684407966: no space left on device

---------------------------------------------------

vim /etc/docker/daemon.json
{
    
    
  "insecure-registries":["192.168.75.200:5000"],  //添加
  "registry-mirrors": ["https://1i3tpy0i.mirror.aliyuncs.com"]
}
~ 
systemctl restart docker.service  

docker create -it registry /bin/bash #新建容器

docker ps -a
[root@localhost docker]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS                    NAMES
ba786a224305        registry            "/entrypoint.sh /bin…"   44 minutes ago      Exited (127) 9 minutes ago                            zen_hamilton

docker start 231d40e811cd   ##开启(不是up是正确的)

##宿主机的/data/registry自动创建挂载容器中的/tmp/registry
docker run -d -p 5000:5000 -v /data/registry:/tmp/registry registry

docker pull httpd

##更改标记为192.168.75.200:5000/httpd  
docker tag httpd:latest 192.168.75.200:5000/httpd  (标记IP地址与私有仓库的地址和端口相一致)
docker push 192.168.75.200:5000/httpd  ##上传镜像

##获取私有仓库列表
curl -XGET http://192.168.75.200:500/v2/_catalog
docker pull 192.168.75.200:500/httpd ##测试私有仓库下载镜像

  • Port Mapping

docker run -d -P httpd:centos   ##随机分配外部的映射端口
docker run -d -p 43992:80 httpd:centos  ##指定端口映射
docker ps -a   ##查看

Ten, container interconnection

(1) Port mapping for container interconnection

  • Create and run the container named web1, the port number is automatically mapped
docker run -itd -P --name web1 ecntos /bin/bash 

  • Create and run the container named web2, connect to web1 and communicate with it

docker run -itd -P --name web2 --link web1:web1 centos /bin/bash

  • Into the web2 container ping web1

Port mapping is not the only way to connect docker to another container.

Docker has a connection system that allows multiple containers to be connected together and share connection information.

The docker connection creates a parent-child relationship, where the parent container can see the information of the child container.

(2) Network settings for container interconnection

新建网络
下面先创建一个新的 Docker 网络。

$ docker network create -d bridge test-net

参数说明:

-d:参数指定 Docker 网络类型,有 bridge、overlay。

其中 overlay 网络类型用于 Swarm mode,在本小节中你可以忽略它。
连接容器

运行一个容器并连接到新建的 test-net 网络:

$ docker run -itd --name test1 --network test-net ubuntu /bin/bash

打开新的终端,再运行一个容器并加入到 test-net 网络:

$ docker run -itd --name test2 --network test-net ubuntu /bin/bash

apt-get update
apt install iputils-ping

下面通过 ping 来证明 test1 容器和 test2 容器建立了互联关系。

如果 test1、test2 容器内中无 ping 命令,则在容器内执行以下命令安装 ping(即学即用:可以在一个容器里安装好,提交容器到镜像,在以新的镜像重新运行以上俩个容器)。

Insert picture description here

Insert picture description here

11. Summary

  1. Docker's container technology can easily create a lightweight, portable, and self-sufficient container for any application on a host.
  2. Mirror, container, and warehouse are the three core concepts of docker.
  3. Dockerfile is a script interpreted by the docker program. The dockerfile consists of multiple instructions, and each instruction corresponds to a command under Linux.
  4. Manage the main data volume and data volume container mode of data in docker container.

Guess you like

Origin blog.csdn.net/weixin_42099301/article/details/108723463