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

相關文章
相關標籤/搜索