DevOps 之路 —— Docker基础

 

 

 

 

 

   Docker 是一个开源的应用容器引擎,让开发者能够打包他们的应用以及依赖包到一个可移植的镜像中,而后发布到任何流行的 Linux或Windows 机器上,也能够实现虚拟化。容器是彻底使用沙箱机制,相互之间不会有任何接口。html

   Docker 是 DevOps 的重要一个组成部分,不可缺乏,能够说云计算没法离开docker,或者说没法离开容器,容器已经成为云计算的重要基础设施。node

 
 

 

 

 

 

   Docker 是基于Linux 内核的一种虚拟化容器(Container),主要用到 CGroups,Namespace(ipc,network, user,pid,mount),UnionFileSystem 等技术封装成一种自定义的容器格式,用于提供一整套虚拟运行环境。python

   利用Docker容器技术,开发人员&运维 能够快速的对应用程序进行“集装箱化”封装,随时部署、分发应用程序,免去了传统运维带来的复杂性、不可控、结果不一致等问题。linux

集装箱化的优势:

   灵活:即便是复杂的应用程序也可封装。
   轻量级:容器利用并共享主机内核。
   便携式:您能够在本地构建,部署到云上并在任何地方运行。
   可扩展性:您能够增长和自动分发容器副本。
   可堆叠:您能够垂直堆叠服务并及时并及时堆叠服务。docker


虚拟机和容器对比:

 

 

 

   VM(VMware)在宿主机的硬件和操做系统基础上构建虚拟机,虚拟机会占用较多的CPU资源及内存,数据重量级的虚拟化,对于云计算而言最大的弊端就是启动缓慢,如须要启动突发实例,启动时间会很长,没法快速响应express

   Docker容器是共享操做系统内核,属于轻量级虚拟化技术,容器自己的资源开销极低,容器的启动也很是快(秒级)npm


Docker引擎的主要组成部分:

   Daemon :Docker进程守护 ,负责后台进程管理,镜像管理,容器管理以及数据卷json

   Client : 用于与Docker Daemon交互ubuntu

   Image :Docker容器运行的镜像文件,一般是一个linux系统,里面包含一个或多个可运行的服务,例如Nginx、Tomcat、Spring Boot 等。api

   Services :服务是docker swarm引入的概念,能够在多宿主机之间伸缩容器数目,支持负载均衡已经服务路由功能。


Docker 实践:

1.服务安装

更新安装源

apt-get update apt-get install -y apt-transport-https gnupg-agent software-properties-common 

添加阿里云安装源的密钥

curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo apt-key add - apt-get update apt-get install -y apt-transport-https gnupg-agent software-properties-common 

添加阿里云安装源

add-apt-repository "deb [arch=amd64] http://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"

安装最新版 docker engine

apt update
apt install docker-ce

配置 docker 加速镜像

cat <<EOF > /etc/docker/daemon.json { "registry-mirrors": [ "https://a35khyup.mirror.aliyuncs.com" ], "exec-opts": [ "native.cgroupdriver=systemd" ] } EOF 

重启 docker

service docker restart
1.基本命令 (ubuntu 18.04)
@查看docker 命令集
docker
@输出---------------------------------------------------------------------------------------------------------------------------------- Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers Options: --config string Location of client config files (default "/root/.docker") -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") -D, --debug Enable debug mode -H, --host list Daemon socket(s) to connect to -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") --tls Use TLS; implied by --tlsverify --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") --tlsverify Use TLS and verify the remote -v, --version Print version information and quit Management Commands: builder Manage builds config Manage Docker configs container Manage containers context Manage contexts engine Manage the docker engine image Manage images network Manage networks node Manage Swarm nodes plugin Manage plugins secret Manage Docker secrets service Manage services stack Manage Docker stacks swarm Manage Swarm system Manage Docker trust Manage trust on Docker images volume Manage volumes Commands: attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile commit Create a new image from a container's changes cp Copy files/folders between a container and the local filesystem create Create a new container diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server exec Run a command in a running container export Export a container's filesystem as a tar archive history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on Docker objects kill Kill one or more running containers load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container pause Pause all processes within one or more containers port List port mappings or a specific mapping for the container ps List containers pull Pull an image or a repository from a registry push Push an image or a repository to a registry rename Rename a container restart Restart one or more containers rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop one or more running containers tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE top Display the running processes of a container unpause Unpause all processes within one or more containers update Update configuration of one or more containers version Show the Docker version information wait Block until one or more containers stop, then print their exit codes 

这里介绍几个经常使用命令

@查看docker版本
docker -v @输出------------------------------------------------------------------------------------------------- Docker version 19.03.8, build afacb8b7f0 @搜索公有镜像 (来自docker hub) docker search ubuntu @输出--------------------------------------------------------------------------------------------------- ubuntu Ubuntu is a Debian-based Linux operating sys… 10699 [OK] dorowu/ubuntu-desktop-lxde-vnc Docker image to provide HTML5 VNC interface … 410 [OK] rastasheep/ubuntu-sshd Dockerized SSH service, built on top of offi… 245 [OK] consol/ubuntu-xfce-vnc Ubuntu container with "headless" VNC session… 212 [OK] ubuntu-upstart Upstart is an event-based replacement for th… 107 [OK] neurodebian NeuroDebian provides neuroscience research s… 67 省略更多.... @这里会显示出符合搜索关键词的镜像 ,更多的镜像信息能够去docker hub 查看 @ https://hub.docker.com @ 
 

 

 

@拉取镜像到本地
docker pull ubuntu:latest #指定ubuntu镜像的 指定版本latest ,版本信息能够去docker hub查看 或者向做者、机构获取版本信息 @也能够不指定版本,docker或默认补全 latest 标签,注意并非全部的镜像都存在latest标签 @这是docker的建议规范,通常约定最后一个发行版的镜像都打latest标签 docker pull ubuntu @输出------------------------------------------------------------------------------------------------------- root@iZuf6hi3nax526o9nirdj6Z:~# docker pull ubuntu Using default tag: latest latest: Pulling from library/ubuntu 5bed26d33875: Pull complete f11b29a9c730: Pull complete 930bda195c84: Pull complete 78bf9a5ad49e: Pull complete Digest: sha256:bec5a2727be7fff3d308193cfde3491f8fba1a2ba392b7546b43a051853a341d Status: Downloaded newer image for ubuntu:latest docker.io/library/ubuntu:latest 
@查看本地镜像
docker images
@输出------------------------------------------------------------------------------------------------------- REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 4e5021d210f6 11 days ago 64.2MB @这里能够看到刚刚拉取到本地的镜像信息 @其中 IMAGE ID 是镜像的惟一ID,SHA256的短ID 
@运行刚刚拉取的镜像 
@语法 docker run [OPTIONS] IMAGE [COMMAND] [ARG...] @更多命令介绍 https://www.runoob.com/docker/docker-run-command.html docker run -i -t ubuntu:latest /bin/bash @输出------------------------------------------------------------------------------------------------------- root@a8ac444cb316:/# @这是一个基本的镜像运行命令,输出的结果表明容器已经运行并进入了容器内部的控制台 @ a8ac444cb316 是启动镜像后获得的容器ID ,能够理解为咱们启动一个程序后获得的一个进程ID,它是随机的且惟一的 
@查看运行中的容器列表
docker ps
@输出------------------------------------------------------------------------------------------------------- CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a8ac444cb316 ubuntu:latest "/bin/bash" 12 seconds ago Up 11 seconds epic_austin @核心内容 @CONTAINER ID:容器的ID @IMAGE 当前运行的镜像 @COMMAND 容器运行的命令 !相当重要 后面讲解 --------------------------------------------------------------------------------------------------------------------- @查看所有容器 docker ps -a @输出------------------------------------------------------------------------------------------------------- CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4d758b7ac995 ubuntu:latest "/bin/bash" 5 minutes ago Up 5 minutes epic_austin a8ac444cb316 ubuntu:latest "/bin/bash" 9 minutes ago Exited (0) 5 minutes ago peaceful_hawking 498ad167c4a1 ubuntu:latest "/bin/bash" 12 minutes ago Exited (130) 9 minutes ago condescending_fermat @-a 参数 表明查看所有容器,其中包括中止运行的容器 @STATUS 会显示容器当前的状态 
@删除docker容器
docker rm a8ac444cb316
@输出------------------------------------------------------------------------------------------------------- a8ac444cb316 @此时 容器已经被删除 当容器正在运行时若是但愿删除 须要先中止容器 或者可使用强制删除命令 docker rm -f a8ac444cb316 
@中止容器
docker stop 8d81396dfadc @输出------------------------------------------------------------------------------------------------------- 8d81396dfadc @此时 容器已经中止运行 
@启动容器
docker start 8d81396dfadc @输出------------------------------------------------------------------------------------------------------- 8d81396dfadc @此时 容器已经启动 
@容器日志打印
@咱们建立一个容器,并在控制台打印
echo  hello docker !
而后运行如下命令
docker logs 8d81396dfadc @输出------------------------------------------------------------------------------------------------------- hello docker ! @该命令会打印出容器内部 输出到控制台的数据流 方便咱们排查应用程序的问题 
@自定义镜像的打包
当咱们基于基础镜像构建好咱们须要的运行环境镜像后,能够把容器打包成自定义镜像
@命令格式 docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] docker commit 5049f83f54b9 my:latest @输出------------------------------------------------------------------------------------------------------- sha256:8345052a53ae56bb66abfbbe0824f95c688d05af134b2af60d69a18f2c49abe1 @结果表明 咱们自定义镜像已经打包成功 @使用 docker images 能够查看镜像 REPOSITORY TAG IMAGE ID CREATED SIZE my latest 8345052a53ae 57 seconds ago 64.2MB ubuntu latest 4e5021d210f6 11 days ago 64.2MB 
@镜像删除
docker rmi 8345052a53ae docker rmi -f 8345052a53ae @当镜像存在正在运行的容器或被其余镜像依赖时 @输出------------------------------------------------------------------------------------------------------- Deleted: sha256:d4698426aef8771602326388fcf3969767e4568dd3d4717f2565d87efdf2584f Deleted: sha256:83dbd6a7e45889b72231fed7acc3850bd8784369bd5c1c22e3e85ee3faabeeee Deleted: sha256:8eb22b722d8da23dde1a066e5a5dc2c70ab3324d670b0ba3b2c673669c868f1c Deleted: sha256:86eda152af5ac59c56a28ab0a7e9cc36009661c42b21e4c2e00af39ec019192c @这里看到输出了4条Deleted信息,表示这个镜像有4个层 

建立自定义镜像

首先以nodejs为例,准备一个可运行的应用程序

cat <<EOF > index.js var express =require("express"); var app = express(); app.get("/",function(req,res){ res.send("hello express @ docker"); }) app.listen(3333,function(){ console.log("running...."); }) EOF ------------------------------------------------------------------------------------------------------------------------------ cat <<EOF > package.json { "dependencies": { "express": "^4.17.1" } } EOF ------------------------------------------------------------------------------------------------------------------------------ @安装依赖模块 npm install -save 

准备Dockerfile 文件

cat <<EOF >  Dockerfile
#基础镜像
FROM node:latest
#指定工做目录      
WORKDIR /app
#复制当前目录下全部的文件到工做目录
COPY . /app
#暴露3333端口(能够暴露多个)
EXPOSE 3333
#设置启动点 这里的意思是 执行 node 这个程序 指定 index.js 这个参数
#等效  node  index.js
#也能够经过CMD 命令设置启动 例如: CMD node index.js
ENTRYPOINT ["node", "index.js"]
EOF

开始构建Docker镜像

@语法 docker build [OPTIONS] PATH | URL | - @具体参数说明 https://www.runoob.com/docker/docker-build-command.html docker build -t nodetest:v1 . @输出------------------------------------------------------------------------------------------------------- Sending build context to Docker daemon 2.052MB Step 1/5 : FROM node:latest ---> c31fbeb964cc Step 2/5 : WORKDIR /app ---> Using cache ---> 23a635ce2e33 Step 3/5 : COPY . /app ---> Using cache ---> 46589ea72f4b Step 4/5 : EXPOSE 3333 ---> Using cache ---> 1e60f8f80f38 Step 5/5 : ENTRYPOINT ["node", "index.js"] ---> Using cache ---> eee6a2aa57d7 Successfully built eee6a2aa57d7 Successfully tagged nodetest:v1 

运行咱们打包的镜像

@运行咱们打包的镜像时无需指定最后 "/bin/bash" 相似这部分的运行参数 ,由于ENTRYPOINT已经为咱们完成了这个工做 docker run -d -p 4444:3333 -m 512m --name my-node-test nodetest:v1 @这里简单介绍几个关键参数 -d: 后台运行容器,并返回容器ID -p: 指定端口映射,格式为:主机(宿主)端口:容器端口 ,若是容器内的程序须要对外提供服务,须要经过宿主机的网络对外提供 -m :设置容器使用内存最大值 --name="my-node-test": 为容器指定一个名称 nodetest:v1 表明须要运行的镜像 @输出------------------------------------------------------------------------------------------------------- 73e6e8efa49a8643344f98621608adc80d438ef78d3db06f951bae2f6a9bbc49 @这个ID就是容器实例的ID 如今这个简单node express 程序已经能够对外提供服务了 执行命令验证 curl http://127.0.0.1:4444 && echo 输出:hello express @ docker 

镜像打标签 (tag)

@咱们须要提交docker镜像到docker hub 或者到私有的镜像仓库时,须要按照docker仓储标准定义镜像名称
@可使用tag命令对镜像名称重现定义

docker tag nodetest:v1 jogbbs/nodetest:v1 @ jogbbs/nodetest:v1 是一个docker hub的命名 @ jogbbs是docker hub的帐号 @ nodetest:v1 是镜像的名称和tag 当咱们使用私有镜像时,命名每每是 {host}/{project}/{image}:{tag} 例如 dtg.com/netcore/openapi:v20200401_v1 或者 10.101.2.1/netcore/openapi:v20200401_v1 

镜像推送

docker push jogbbs/nodetest:v1 @输出------------------------------------------------------------------------------------------------------- The push refers to repository [docker.io/jogbbs/nodetest] ea27352f53ab: Pushed 0a9f7ba4985e: Pushed c058eaf748c8: Mounted from library/node eb58d2440516: Mounted from library/node 66cf06b2e874: Mounted from library/node 45ac74adb5b4: Mounted from library/node d485cbbe6a5e: Mounted from library/node 391c89959588: Mounted from library/node 588545a7a2a3: Mounted from library/node 8452468a5e50: Mounted from library/node 55b19a5e648f: Mounted from library/node v1: digest: sha256:5aaa69e65ecefdb2a50891c060ba35479cf5aeeb1c743df839d7fbb6e5339d5c size: 2632 @这里的每一行表明一个层,观察看出,有2个层pushed @其余 Mounted 表明 远程的容器仓库中有相同的层 ,能够直接复用,无需提交 @这也是docker镜像分层技术带来的优点,节省了存储空间,提升了镜像push的速度 

以上是Docker的基本知识点,更多内容期待后续..


本文大部份内容来自网络,欢迎转载,转载请注明出处

学习在于积累,本文主要参考如下连接:

https://www.cnblogs.com/hwlong/p/9158982.html
https://www.jianshu.com/p/ef41503b8f87
https://www.cnblogs.com/dudu/p/12155869.html

相关文章
相关标签/搜索