如來神掌第四式第一招----Docker基礎用法

 

###############################################################################
# Name : Mahavairocana                                                                                                                                           
# Author : Mahavairocana                                                                                                                                         
# QQ : 10353512                                                                                                                                                    
# WeChat : shenlan-qianlan                                                                                                                                      
# Blog : http://www.cnblogs.com/Mahavairocana/                                                                                                       
# Description : You are welcome to reprint, or hyperlinks to indicate the                                                                        
#                    source of the article, as well as author information.                                                                                
###############################################################################
php

 

 

什麼是Docker?

Docker 是世界領先的軟件容器平臺。開發人員利用 Docker 能夠消除協做編碼時「在個人機器上可正常工做」的問題。運維人員利用 Docker 能夠在隔離容器中並行運行和管理應用,得到更好的計算密度。企業利用 Docker 能夠構建敏捷的軟件交付管道,以更快的速度、更高的安全性和可靠的信譽爲 Linux 和 Windows Server 應用發佈新功能。html

Docker 屬於 Linux 容器的一種封裝,提供簡單易用的容器使用接口。它是目前最流行的 Linux 容器解決方案。Docker 將應用程序與該程序的依賴,打包在一個文件裏面。運行這個文件,就會生成一個虛擬容器。程序在這個虛擬容器裏運行,就好像在真實的物理機上運行同樣。有了 Docker,就不用擔憂環境問題。python

整體來講,Docker 的接口至關簡單,用戶能夠方便地建立和使用容器,把本身的應用放入容器。容器還能夠進行版本管理、複製、分享、修改,就像管理普通的代碼同樣。mysql

Docker 最初是 dotCloud 公司創始人 Solomon Hykes 在法國期間發起的一個公司內部項目,它是基於 dotCloud 公司多年雲服務技術的一次革新,並於 2013 年 3 月以 Apache 2.0 受權協議開源,主要項目代碼在 GitHub 上進行維護。Docker 項目後來還加入了 Linux 基金會,併成立推進 開放容器聯盟(OCI)。linux

Docker 自開源後受到普遍的關注和討論,至今其 GitHub 項目已經超過 4 萬 6 千個星標和一萬多個 fork。甚至因爲 Docker 項目的火爆,在 2013 年末,dotCloud 公司決定更名爲 Docker。Docker 最初是在 Ubuntu 12.04 上開發實現的;Red Hat 則從 RHEL 6.5 開始對 Docker 進行支持;Google 也在其 PaaS 產品中普遍應用 Docker。nginx

爲何要使用Docker

容器除了運行其中應用外,基本不消耗額外的系統資源,使得應用的性能很高,同時系統的開銷儘可能小。傳統虛擬機方式運行 10 個不一樣的應用就要起 10 個虛擬機,而Docker 只須要啓動 10 個隔離的應用便可。git

具體說來,Docker 在以下幾個方面具備較大的優點。github

一、更快速的交付和部署web

對開發和運維(devop)人員來講,最但願的就是一次建立或配置,能夠在任意地方正常運行。sql

開發者可使用一個標準的鏡像來構建一套開發容器,開發完成以後,運維人員能夠直接使用這個容器來部署代碼。 Docker 能夠快速建立容器,快速迭代應用程序,並讓整個過程全程可見,使團隊中的其餘成員更容易理解應用程序是如何建立和工做的。 Docker 容器很輕很快!容器的啓動時間是秒級的,大量地節約開發、測試、部署的時間。

二、更高效的虛擬化

Docker 容器的運行不須要額外的 hypervisor 支持,它是內核級的虛擬化,所以能夠實現更高的性能和效率。

三、更輕鬆的遷移和擴展

Docker 容器幾乎能夠在任意的平臺上運行,包括物理機、虛擬機、公有云、私有云、我的電腦、服務器等。 這種兼容性可讓用戶把一個應用程序從一個平臺直接遷移到另一個。

四、更簡單的管理

使用 Docker,只須要小小的修改,就能夠替代以往大量的更新工做。全部的修改都以增量的方式被分發和更新,從而實現自動化而且高效的管理。

Docker vs VM

從下圖能夠看出,VM是一個運行在宿主機之上的完整的操做系統,VM運行自身操做系統會佔用較多的CPU、內存、硬盤資源。Docker不一樣於VM,只包含應用程序以及依賴庫,基於libcontainer運行在宿主機上,並處於一個隔離的環境中,這使得Docker更加輕量高效,啓動容器只需幾秒鐘以內完成。因爲Docker輕量、資源佔用少,使得Docker能夠輕易的應用到構建標準化的應用中。但Docker目前還不夠完善,好比隔離效果不如VM,共享宿主機操做系統的一些基礎庫等;網絡配置功能相對簡單,主要以橋接方式爲主;查看日誌也不夠方便靈活。

Docker(一):Docker入門教程

Docker 在容器的基礎上,進行了進一步的封裝,從文件系統、網絡互聯到進程隔離等等,極大的簡化了容器的建立和維護。使得 Docker 技術比虛擬機技術更爲輕便、快捷。

做爲一種新興的虛擬化方式,Docker 跟傳統的虛擬化方式相比具備衆多的優點。Docker 容器的啓動能夠在秒級實現,這相比傳統的虛擬機方式要快得多;Docker 對系統資源的利用率很高,一臺主機上能夠同時運行數千個 Docker 容器。

相關概念

Docker是CS架構,主要有兩個概念:

  • Docker daemon: 運行在宿主機上,Docker守護進程,用戶經過Docker client(Docker命令)與Docker daemon交互
  • Docker client: Docker 命令行工具,是用戶使用Docker的主要方式,Docker client與Docker daemon通訊並將結果返回給用戶,Docker client也能夠經過socket或者RESTful api訪問遠程的Docker daemon

Docker(一):Docker入門教程

瞭解了Docker的組成,再來了解一下Docker的三個主要概念:

  • Docker image:鏡像是隻讀的,鏡像中包含有須要運行的文件。鏡像用來建立container,一個鏡像能夠運行多個container;鏡像能夠經過Dockerfile建立,也能夠從Docker hub/registry上下載。
  • Docker container:容器是Docker的運行組件,啓動一個鏡像就是一個容器,容器是一個隔離環境,多個容器之間不會相互影響,保證容器中的程序運行在一個相對安全的環境中。
  • Docker hub/registry: 共享和管理Docker鏡像,用戶能夠上傳或者下載上面的鏡像,官方地址爲https://registry.hub.docker.com/,也能夠搭建本身私有的Docker registry。

鏡像就至關於打包好的版本,鏡像啓動以後運行在容器中,倉庫就是裝存儲鏡像的地方。

 

Docker 是一個開源的應用容器引擎,基於 Go 語言 並聽從Apache2.0協議開源。

Docker 可讓開發者打包他們的應用以及依賴包到一個輕量級、可移植的容器中,而後發佈到任何流行的 Linux 機器上,也能夠實現虛擬化。

容器是徹底使用沙箱機制,相互之間不會有任何接口(相似 iPhone 的 app),更重要的是容器性能開銷極低。

 

Docker-ce:
    Docker CE是免費的Docker產品的新名稱,Docker CE包含了完整的Docker平臺,很是適合開發人員和運維團隊構建容器APP。事實上,Docker CE 17.03,可理解爲Docker 1.13.1的Bug修復版本。所以,從Docker 1.13升級到Docker CE 17.03風險相對是較小的。
    你們可前往Docker的RELEASE log查看詳情https://github.com/docker/docker/releases 。
    Docker公司認爲,Docker CE和EE版本的推出爲Docker的生命週期、可維護性以及可升級性帶來了巨大的改進。
    
Containers:啓動容器:基於鏡像啓動,在鏡像基礎上,爲一個容器建立一個專用可寫層。
Images: 須要加載到本地,(經過HTTP,HTTPS加載),下載速度,取決於網速,dockerhub存放在國外,國內有阿里雲(須要註冊專用加速帳號) 、中科大、清華等。

Docker 組成部分

 

Docker 對象:

  Docker Objects:
When you use docker, you are creating and using images containers, networks, volumes,plugins, and other objects.
    IMAGES:
        An imagesis a read-only template with instructions for creating a docker container.
        Often,an image is based on another image ,with some additional custimaization.
        You might create your own images or you might only use those created by others and published in a registry.
    CONTAINERS:
        A container is a runnable insance of an image.
        You cancreate, run ,stop move or delete a container using the docker apii or cli.
You can connect a container to one or more networks, attach storage to It ,or even create a new image based on its current state.

Docker 的優勢

    • 一、簡化程序:
      Docker 讓開發者能夠打包他們的應用以及依賴包到一個可移植的容器中,而後發佈到任何流行的 Linux 機器上,即可以實現虛擬化。Docker改變了虛擬化的方式,使開發者能夠直接將本身的成果放入Docker中進行管理。方便快捷已是 Docker的最大優點,過去須要用數天乃至數週的 任務,在Docker容器的處理下,只須要數秒就能完成。

    • 二、避免選擇恐懼症:
      若是你有選擇恐懼症,仍是資深患者。Docker 幫你 打包你的糾結!好比 Docker 鏡像;Docker 鏡像中包含了運行環境和配置,因此 Docker 能夠簡化部署多種應用實例工做。好比 Web 應用、後臺應用、數據庫應用、大數據應用好比 Hadoop 集羣、消息隊列等等均可以打包成一個鏡像部署。

    • 三、節省開支:
      一方面,雲計算時代到來,使開發者沒必要爲了追求效果而配置高額的硬件,Docker 改變了高性能必然高價格的思惟定勢。Docker 與雲的結合,讓雲空間獲得更充分的利用。不只解決了硬件管理的問題,也改變了虛擬化的方式。

namespace 對內核要求(centos7系列基本知足需求)

 

 

 

安裝

1、修改默認站點,加快安裝速度

[root@docker--0001 yum.repos.d]# yum -y install wget
[root@docker--0001 yum.repos.d]# wget https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
[root@docker--0001 yum.repos.d]# sed -i s@https://download.docker.com/@https://mirrors.tuna.tsinghua.edu.cn/docker-ce/@g /etc/yum.repos.d/docker-ce.repo    ### 替換清華的加速站點。
2、查看是否正常加載
[root@docker--0001 yum.repos.d]# yum repolist
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
repo id                                                                               repo name                                                                               status
docker-ce-stable/x86_64                                                               Docker CE Stable - x86_64                                                               33
repolist: 33
3、查看安裝包
[root@docker--0001 yum.repos.d]# yum install docker-ce
Installed:
  docker-ce.x86_64 3:18.09.2-3.el7                                                                                                                                                  

Dependency Installed:
  container-selinux.noarch 2:2.55-1.el7         containerd.io.x86_64 0:1.2.2-3.3.el7         docker-ce-cli.x86_64 1:18.09.2-3.el7         libseccomp.x86_64 0:2.3.1-3.el7        
  libtool-ltdl.x86_64 0:2.4.2-22.el7_3         

Dependency Updated:
  libselinux.x86_64 0:2.5-12.el7              libselinux-python.x86_64 0:2.5-12.el7                libselinux-utils.x86_64 0:2.5-12.el7  libsemanage.x86_64 0:2.5-11.el7            
  libsemanage-python.x86_64 0:2.5-11.el7      libsepol.x86_64 0:2.5-8.1.el7                        policycoreutils.x86_64 0:2.5-22.el7   policycoreutils-python.x86_64 0:2.5-22.el7 
  selinux-policy.noarch 0:3.13.1-192.el7_5.3  selinux-policy-targeted.noarch 0:3.13.1-192.el7_5.3  setools-libs.x86_64 0:3.3.8-2.el7    

Complete!
ocker默認配置文件/etc/docker/daemon.json ##須要本身建立
[root@docker--0001 docker]# ls
daemon.json  
添加加速器
[root@docker--0001 docker]# vim daemon.json 
{
        "registry-mirrors": ["https://registry.docker-cn.com"]
}


啓動docker
[root@docker--0001 docker]# systemctl start docker.service
[root@docker--0001 docker]# systemctl status docker.service
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; disabled; vendor preset: disabled)
   Active: active (running) since Sat 2019-02-23 14:25:49 CST; 11s ago
     Docs: https://docs.docker.com
 Main PID: 13466 (dockerd)
   Memory: 51.6M
   CGroup: /system.slice/docker.service
           ├─13466 /usr/bin/dockerd -H fd://
           └─13488 containerd --config /var/run/docker/containerd/containerd.toml --log-level info

Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.728771457+08:00" level=info msg="pickfirstBalancer: HandleSubConnStateChange: 0xc42016...odule=grpc
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.758203345+08:00" level=info msg="Graph migration to content-addressability took 0.00 seconds"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.758658814+08:00" level=info msg="Loading containers: start."
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.853024184+08:00" level=info msg="Default bridge (docker0) is assigned with an IP addre...P address"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.887691637+08:00" level=info msg="Loading containers: done."
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904029319+08:00" level=warning msg="Not using native diff for overlay2, this may cause...r=overlay2
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904179876+08:00" level=info msg="Docker daemon" commit=6247962 graphdriver(s)=overlay2...on=18.09.2
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.904286929+08:00" level=info msg="Daemon has completed initialization"
Feb 23 14:25:49 docker--0001.novalocal dockerd[13466]: time="2019-02-23T14:25:49.921887529+08:00" level=info msg="API listen on /var/run/docker.sock"
Feb 23 14:25:49 docker--0001.novalocal systemd[1]: Started Docker Application Container Engine.
Hint: Some lines were ellipsized, use -l to show in full.


Docker 命令

[root@docker--0001 docker]# docker version   #查詢版本信息
Client:
 Version:           18.09.2
 API version:       1.39
 Go version:        go1.10.6
 Git commit:        6247962
 Built:             Sun Feb 10 04:13:27 2019
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          18.09.2
  API version:      1.39 (minimum version 1.12)
  Go version:       go1.10.6
  Git commit:       6247962
  Built:            Sun Feb 10 03:47:25 2019
  OS/Arch:          linux/amd64
  Experimental:     false


[root@docker--0001 docker]# docker info  #查詢詳細信息
Containers: 0  #容器數量
 Running: 0        #運行狀態數量
 Paused: 0        #暫停狀態數量
 Stopped: 0        #中止狀態數量
Images: 0        #鏡像個數
Server Version: 18.09.2
Storage Driver: overlay2  ##存儲文件系統
 Backing Filesystem: extfs
 Supports d_type: true
 Native Overlay Diff: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:   #支持插件
 Volume: local  #存儲插件
 Network: bridge host macvlan null overlay  #網絡插件
 Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog  #日誌插件
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 9754871865f7fe2f4e74d43e2fc7ccd237edcbce
runc version: 09c8266bf2fcf9519a651b04ae54c967b9ab86ec
init version: fec3683
Security Options:
 seccomp
  Profile: default
Kernel Version: 3.10.0-514.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 7.639GiB
Name: docker--0001.novalocal
ID: 34DE:NHPU:BAYB:UZAR:ZDZX:T73W:7DZQ:J4YD:AMVR:NUNY:UCSL:JL2W
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
 127.0.0.0/8
Registry Mirrors:
 https://registry.docker-cn.com/  #本身配置加速鏡像地址
Live Restore Enabled: false
Product License: Community Engine

經常使用操做:
docker search: 根據名稱搜索本身須要的鏡像
docker pull:根據名稱下載本身須要的鏡像
docker push:根據名稱上傳本身須要的鏡像
docker create: 建立容器
docker start/stop/restart :啓動一個或者多個容器
docker run: 運行一個或者多個容器
docker attach:鏈接到一個運行的容器
docker ps:列車當前容器
docker kill:殺掉一個或者多個容器,強制關閉
docker logs:獲取容器日誌
docker rm :刪除一個或者多個容器
docker rmi: 刪除鏡像  == docker image rm 
docker pause(unpause):掛起或者取消掛起容器

三個命令能夠替換爲docker image search pull push

運行docker:
[root@docker--0001 docker]# docker search nginx
NAME                                                   DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
nginx   ##頂級倉庫 通常爲官方                                                Official build of Nginx.                        10956               [OK]                
jwilder/nginx-proxy      ##用戶倉庫、項目倉庫                              Automated Nginx reverse proxy for docker con…   1538                                    [OK]
richarvey/nginx-php-fpm                                Container running Nginx + PHP-FPM capable of…   685                                     [OK]
jrcs/letsencrypt-nginx-proxy-companion                 LetsEncrypt container to use with nginx as p…   485                                     [OK]
webdevops/php-nginx                                    Nginx with PHP-FPM                              123                                     [OK]
kitematic/hello-world-nginx                            A light-weight nginx container that demonstr…   121                                     
zabbix/zabbix-web-nginx-mysql                          Zabbix frontend based on Nginx web-server wi…   91                                      [OK]
bitnami/nginx                                          Bitnami nginx Docker Image                      62                                      [OK]
linuxserver/nginx                                      An Nginx container, brought to you by LinuxS…   55                                      
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5   ubuntu-16-nginx-php-phpmyadmin-mysql-5          49                                      [OK]
zabbix/zabbix-web-nginx-pgsql                          Zabbix frontend based on Nginx with PostgreS…   28                                      [OK]
tobi312/rpi-nginx                                      NGINX on Raspberry Pi / armhf                   24                                      [OK]
nginx/nginx-ingress                                    NGINX Ingress Controller for Kubernetes         17                                      
blacklabelops/nginx                                    Dockerized Nginx Reverse Proxy Server.          12                                      [OK]
wodby/drupal-nginx                                     Nginx for Drupal container image                12                                      [OK]
nginxdemos/hello                                       NGINX webserver that serves a simple page co…   11                                      [OK]
schmunk42/nginx-redirect                               A very simple container to redirect HTTP tra…   11                                      [OK]
centos/nginx-18-centos7                                Platform for running nginx 1.8 or building n…   10                                      
centos/nginx-112-centos7                               Platform for running nginx 1.12 or building …   7                                       
1science/nginx                                         Nginx Docker images that include Consul Temp…   4                                       [OK]
mailu/nginx                                            Mailu nginx frontend                            3                                       [OK]
travix/nginx                                           NGinx reverse proxy                             2                                       [OK]
toccoag/openshift-nginx                                Nginx reverse proxy for Nice running on same…   1                                       [OK]
wodby/nginx                                            Generic nginx                                   0                                       [OK]
ansibleplaybookbundle/nginx-apb                        An APB to deploy NGINX                          0                                       [OK]
You have new mail in /var/spool/mail/root


alpine 版本:體積小,可以提供基礎環境,下載內容量比較小,缺點:缺乏調試工具
建議本身作鏡像,添加相關調試工具,dockerhub作法不必定能知足咱們須要。

下載鏡像
[root@docker--0001 docker]# docker image pull nginx:1.14-alpine 
1.14-alpine: Pulling from library/nginx
6c40cc604d8e: Pull complete 
76679ad9f124: Pull complete 
389a52582f93: Pull complete 
496e2dd2b91a: Pull complete 
Digest: sha256:b96aeeb1687703c49096f4969358d44f8520b671da94848309a3ba5be5b4c632
Status: Downloaded newer image for nginx:1.14-alpine

[root@docker--0001 docker]# docker pull busybox
Using default tag: latest
latest: Pulling from library/busybox
697743189b6d: Pull complete 
Digest: sha256:061ca9704a714ee3e8b80523ec720c64f6209ad3f97c0ff7cb9ec7d19f15149f
Status: Downloaded newer image for busybox:latest

列出當前鏡像
[root@docker--0001 docker]# docker image ls
REPOSITORY倉庫名稱 TAG 標籤             IMAGE ID 鏡像ID    CREATED建立時間      SIZE 大小
busybox             latest              d8233ab899d4        8 days ago          1.2MB
nginx               1.14-alpine         66952fd0a8ef        3 weeks ago         16MB

[root@docker--0001 docker]# docker run --name b1 -it busybox:latest   ##運行一個b1名稱的容器
/ # hostname 
82dda7c9d5c0  #查看容器名稱
/ # httpd -h  #查看httpd命令帶的選項
httpd: option requires an argument -- h
BusyBox v1.30.1 (2019-02-14 18:58:02 UTC) multi-call binary.

Usage: httpd [-ifv[v]] [-c CONFFILE] [-p [IP:]PORT] [-u USER[:GRP]] [-r REALM] [-h HOME]
or httpd -d/-e/-m STRING

Listen for incoming HTTP requests

        -i              Inetd mode
        -f              Don't daemonize
        -v[v]           Verbose
        -p [IP:]PORT    Bind to IP:PORT (default *:80)
        -u USER[:GRP]   Set uid/gid after binding to port
        -r REALM        Authentication Realm for Basic Authentication
        -h HOME         Home directory (default .)
        -c FILE         Configuration file (default {/etc,HOME}/httpd.conf)
        -m STRING       MD5 crypt STRING
        -e STRING       HTML encode STRING
        -d STRING       URL decode STRING
建立一個目錄並啓動
/ # mkdir /data/html -p
/ # vi /data/html/index.html
/ # httpd  -f -h /data/html/


[root@docker--0001 ~]# docker ps  #查看運行中的容器
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
82dda7c9d5c0        busybox:latest      "sh"                3 minutes ago       Up 3 minutes                            b1
      
[root@docker--0001 ~]# docker inspect b1 查看B1詳細信息。
[
    {
        "Id": "82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e",
        "Created": "2019-02-23T07:02:30.424416599Z",
        "Path": "sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 14227,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-02-23T07:02:30.694772084Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:d8233ab899d419c58cf3634c0df54ff5d8acc28f8173f09c21df4a07229e1205",
        "ResolvConfPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/hostname",
        "HostsPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/hosts",
        "LogPath": "/var/lib/docker/containers/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e/82dda7c9d5c09da884ce8d615e7e563871236f7de639ef2aa78f6fdaff713c2e-json.log",
        "Name": "/b1",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca-init/diff:/var/lib/docker/overlay2/9e66a9e007a10a0f5816aff408cac730931e31c694fee0ce058441400ddbda4a/diff",
                "MergedDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/merged",
                "UpperDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/diff",
                "WorkDir": "/var/lib/docker/overlay2/867fc50ea1c6c597dcdf504e8ddab221bacb7e31df4b720d54feab66176b0eca/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "82dda7c9d5c0",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "sh"
            ],
            "ArgsEscaped": true,
            "Image": "busybox:latest",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "cae35f9169432abe87730bd9027ccbd9e3477bf25a7309878abfed0ab348f117",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/cae35f916943",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "06b5ca3f68c11278b721c2ccf0096c0b038529ca916bbe1d9a3d353be3d4f0f6",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "7cdf0e083ccf918fb3a9832a74ebad24b58f026cfad7f36ecbfec163e895ca8f",
                    "EndpointID": "06b5ca3f68c11278b721c2ccf0096c0b038529ca916bbe1d9a3d353be3d4f0f6",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
[root@docker--0001 ~]# curl 172.17.0.2
liuqi test

/ # httpd  -f -h /data/html/
^C  ##ctrl 結束運行狀態
/ # exit #退出容器
You have new mail in /var/spool/mail/root
[root@docker--0001 docker]# docker ps #查詢無運行中的容器,不運行默認不顯示
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@docker--0001 docker]# docker ps -a #查看全部狀態容器= docker container ls -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
82dda7c9d5c0        busybox:latest      "sh"                8 minutes ago       Exited (130) 12 seconds ago                       b1

[root@docker--0001 docker]#docker start -ai b1 ##啓動
[root@docker--0001 docker]# docker rm b1 ##刪除
b1
[root@docker--0001 docker]# docker ps -a          #刪除後查詢
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES


[root@docker--0001 docker]# docker run --name web1 -d nginx:1.14-alpine #運行一個nginx容器
48594db2a06ac8a9bf093cb0e44d3141dabf72c6f44310efeb734ae50f98461c
[root@docker--0001 docker]# docker ps 查看運行狀態 端口爲默認開放
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
48594db2a06a        nginx:1.14-alpine   "nginx -g 'daemon of…"   7 seconds ago       Up 6 seconds        80/tcp              web1
[root@docker--0001 docker]# docker
docker        dockerd       dockerd-ce    docker-init   docker-proxy  


進入docker執行命令
[root@docker--0001 docker]# docker exec -it web1 /bin/sh 
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 nginx: master process nginx -g daemon off;
    6 nginx     0:00 nginx: worker process
    7 root      0:00 /bin/sh
   12 root      0:00 ps


獲取容器日誌:
[root@docker--0001 docker]# docker logs web1
172.17.0.1 - - [23/Feb/2019:07:18:12 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"
172.17.0.1 - - [23/Feb/2019:07:19:14 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.29.0" "-"

 Docker run 參數

[root@docker--0001 docker]# docker run --help

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

Run a command in a new container

Options:
      --add-host list                  Add a custom host-to-IP mapping (host:ip)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list       Block IO weight (relative device weight) (default [])
      --cap-add list                   Add Linux capabilities
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cidfile string                 Write the container ID to the file
      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int              Limit CPU real-time period in microseconds
      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int                 CPU shares (relative weight)
      --cpus decimal                   Number of CPUs
      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                         Run container in background and print container ID 
      --detach-keys string             Override the key sequence for detaching a container
      --device list                    Add a host device to the container
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])
      --device-read-iops list          Limit read rate (IO per second) from a device (default [])
      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])
      --device-write-iops list         Limit write rate (IO per second) to a device (default [])
      --disable-content-trust          Skip image verification (default true)
      --dns list                       Set custom DNS servers
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)
      --help                           Print usage
  -h, --hostname string                Container host name
      --init                           Run an init inside the container that forwards signals and reaps processes
  -i, --interactive                    Keep STDIN open even if not attached
      --ip string                      IPv4 address (e.g., 172.30.100.104)
      --ip6 string                     IPv6 address (e.g., 2001:db8::33)
      --ipc string                     IPC mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes                   Memory limit
      --memory-reservation bytes       Memory soft limit
      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network string                 Connect a container to a network (default "default")
      --network-alias list             Add network-scoped alias for the container
      --no-healthcheck                 Disable any container-specified HEALTHCHECK
      --oom-kill-disable               Disable OOM Killer
      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)
      --pid string                     PID namespace to use
      --pids-limit int                 Tune container pids limit (set -1 for unlimited)
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --read-only                      Mount the container's root filesystem as read only
      --restart string                 Restart policy to apply when a container exits (default "no")
      --rm                             Automatically remove the container when it exits
      --runtime string                 Runtime to use for this container
      --security-opt list              Security Options
      --shm-size bytes                 Size of /dev/shm
      --sig-proxy                      Proxy received signals to the process (default true)
      --stop-signal string             Signal to stop a container (default "SIGTERM")
      --stop-timeout int               Timeout (in seconds) to stop a container
      --storage-opt list               Storage driver options for the container
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -t, --tty                            Allocate a pseudo-TTY  ##當虛擬機加入一個tty
      --ulimit ulimit                  Ulimit options (default [])
  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])
      --userns string                  User namespace to use
      --uts string                     UTS namespace to use
  -v, --volume list                    Bind mount a volume
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

 Docker 生命週期管理

相關文章
相關標籤/搜索