zoukankan      html  css  js  c++  java
  • docker环境搭建

        Docker 包括三个基本概念
        1.镜像(Image)
        2.容器(Container)
        3.仓库(Repository)
    
        docker的特性:
        1.文件系统隔离:每个进程容器运行在完全独立的根文件系统里。
        2.资源隔离:可以使用cgroup为每个进程容器分配不同的系统资源,例如CPU和内存。
        3.网络隔离:每个进程容器运行在自己的网络命名空间里,拥有自己的虚拟接口和IP地址。
        4.写时复制:采用写时复制方式创建根文件系统,这让部署变得极其快捷,并且节省内存和硬盘空间。
        5.日志记录:Docker将会收集和记录每个进程容器的标准流(stdout/stderr/stdin),用于实时检索或批量检索。
        6.变更管理:容器文件系统的变更可以提交到新的映像中,并可重复使用以创建更多的容器。无需使用模板或手动配置。
        7.交互式Shell:Docker可以分配一个虚拟终端并关联到任何容器的标准输入上,例如运行一个一次性交互shell。
        docker安装与启动
    
    yum install -y epel-release
    yum install docker   //安装的版本比较老。
    • 1
    • 2
    使用该方法在线安装最新版本的docker
    
    [root@soft Desktop]#  curl -fsSL https://get.docker.com/ | sh
    + sh -c 'sleep 3; yum -y -q install docker-engine'
    docker-engine-1.12.1-1.el7.centos.x86_64.rpm             |  19 MB     04:11     
    No Presto metadata available for docker-experimental-repo
    
    If you would like to use Docker as a non-root user, you should now consider
    adding your user to the "docker" group with something like:
    
      sudo usermod -aG docker your-user
    
    Remember that you will have to log out and back in for this to take effect!
    安装完docker后可用以下命令查看相关的docker信息:
    
    [root@localhost /]# docker version
    Client:
     Version:         1.10.3
     API version:     1.22
     Package version: docker-common-1.10.3-46.el7.centos.10.x86_64
     Go version:      go1.6.3
     Git commit:      d381c64-unsupported
     Built:           Thu Aug  4 13:21:17 2016
     OS/Arch:         linux/amd64
    
    Server:
     Version:         1.10.3
     API version:     1.22
     Package version: docker-common-1.10.3-46.el7.centos.10.x86_64
     Go version:      go1.6.3
     Git commit:      d381c64-unsupported
     Built:           Thu Aug  4 13:21:17 2016
     OS/Arch:         linux/amd64
    
    [root@localhost /]# docker info   //本地已有一个docker镜像
    Containers: 2
     Running: 1
     Paused: 0
     Stopped: 1
    Images: 1
    Server Version: 1.10.3
    Storage Driver: devicemapper
     Pool Name: docker-253:0-1792087-pool
     Pool Blocksize: 65.54 kB
     Base Device Size: 10.74 GB
     Backing Filesystem: xfs
     Data file: /dev/loop0
     Metadata file: /dev/loop1
     Data Space Used: 1.083 GB
     Data Space Total: 107.4 GB
     Data Space Available: 25.5 GB
     Metadata Space Used: 1.278 MB
     Metadata Space Total: 2.147 GB
     Metadata Space Available: 2.146 GB
     Udev Sync Supported: true
     Deferred Removal Enabled: false
     Deferred Deletion Enabled: false
     Deferred Deleted Device Count: 0
     Data loop file: /var/lib/docker/devicemapper/devicemapper/data
     WARNING: Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
     Metadata loop file: /var/lib/docker/devicemapper/devicemapper/metadata
     Library Version: 1.02.107-RHEL7 (2016-06-09)
    Execution Driver: native-0.2
    Logging Driver: journald
    Plugins: 
     Volume: local
     Network: bridge null host
    Kernel Version: 3.10.0-327.28.2.el7.x86_64
    Operating System: CentOS Linux 7 (Core)
    OSType: linux
    Architecture: x86_64
    Number of Docker Hooks: 2
    CPUs: 16
    Total Memory: 15.66 GiB
    Name: localhost.localdomain
    ID: TWV7:7OXE:GGAN:MYFO:ERWM:FC2G:KCWJ:LSU6:TA4Y:Q6J6:ZK3I:GDB4
    WARNING: bridge-nf-call-iptables is disabled
    WARNING: bridge-nf-call-ip6tables is disabled
    Registries: docker.io (secure)
    docker镜像下载
    搜索可用的centos的docker镜像
    
    [root@localhost /]#  docker search centos//搜索centos镜像
    INDEX       NAME                                    DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
    docker.io   docker.io/centos                        The official build of CentOS.                   2531      [OK]       
    docker.io   docker.io/ansible/centos7-ansible       Ansible on Centos7                              82                   [OK]
    docker.io   docker.io/jdeathe/centos-ssh            CentOS-6 6.8 x86_64 / CentOS-7 7.2.1511 x8...   27                   [OK]
    docker.io   docker.io/nimmis/java-centos            This is docker images of CentOS 7 with dif...   13                   [OK]
    docker.io   docker.io/million12/centos-supervisor   Base CentOS-7 with supervisord launcher, h...   12                   [OK]
    docker.io   docker.io/gluster/gluster-centos        Official GlusterFS Image [ CentOS7 +  Glus...   11                   [OK]
    docker.io   docker.io/torusware/speedus-centos      Always updated official CentOS docker imag...   8                    [OK]
    docker.io   docker.io/nickistre/centos-lamp         LAMP on centos setup                            4                    [OK]
    docker.io   docker.io/nathonfowlie/centos-jre       Latest CentOS image with the JRE pre-insta...   3                    [OK]
    docker.io   docker.io/consol/sakuli-centos-xfce     Sakuli end-2-end testing and monitoring co...   2                    [OK]
    docker.io   docker.io/blacklabelops/centos          CentOS Base Image! Built and Updates Daily!     1                    [OK]
    docker.io   docker.io/darksheer/centos              Base Centos Image -- Updated hourly             1                    [OK]
    docker.io   docker.io/harisekhon/centos-java        Java on CentOS (OpenJDK, tags jre/jdk7-8)       1                    [OK]
    docker.io   docker.io/timhughes/centos              Centos with systemd installed and running       1                    [OK]
    docker.io   docker.io/aguamala/centos               CentOS base image                               0                    [OK]
    docker.io   docker.io/dmglab/centos                 CentOS with some extras - This is for the ...   0                    [OK]
    docker.io   docker.io/grayzone/centos               auto build for centos.                          0                    [OK]
    docker.io   docker.io/grossws/centos                CentOS 6 and 7 base images with gosu and l...   0                    [OK]
    docker.io   docker.io/harisekhon/centos-scala       Scala + CentOS (OpenJDK tags 2.10-jre7 - 2...   0                    [OK]
    docker.io   docker.io/januswel/centos               yum update-ed CentOS image                      0                    [OK]
    docker.io   docker.io/jsmigel/centos-epel           Docker base image of CentOS w/ EPEL installed   0                    [OK]
    docker.io   docker.io/kz8s/centos                   Official CentOS plus epel-release               0                    [OK]
    docker.io   docker.io/repositoryjp/centos           Docker Image for CentOS.                        0                    [OK]
    docker.io   docker.io/smartentry/centos             CentOS with smartentry                          0                    [OK]
    docker.io   docker.io/ustclug/centos                 USTC centos                                    0                    [OK]

    构建docker镜像:

    docker pull centos:laster

    慢慢的等待镜像文件的下载。下载完可以通过如下命令查看镜像

    # docker images  //查看镜像信息
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    docker.io/centos    7.2.1511            686672a1d0cc        5 weeks ago         194.6 MB

    通过docker run来启动镜像,同时会创建一个容器,看下docker run的启动命令:

    [root@localhost /]# docker run --help
    
    Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
    
    Run a command in a new container
    
      -a, --attach=[]                 Attach to STDIN, STDOUT or STDERR
      --add-host=[]                   Add a custom host-to-IP mapping (host:ip)
      --blkio-weight                  Block IO (relative weight), between 10 and 1000
      --blkio-weight-device=[]        Block IO weight (relative device weight)
      --cpu-shares                    CPU shares (relative weight)
      --cap-add=[]                    Add Linux capabilities
      --cap-drop=[]                   Drop Linux capabilities
      --cgroup-parent                 Optional parent cgroup for the container
      --cidfile                       Write the container ID to the file
      --cpu-period                    Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota                     Limit CPU CFS (Completely Fair Scheduler) quota
      --cpuset-cpus                   CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems                   MEMs in which to allow execution (0-3, 0,1)
      -d, --detach                    Run container in background and print container ID
      --detach-keys                   Override the key sequence for detaching a container
      --device=[]                     Add a host device to the container
      --device-read-bps=[]            Limit read rate (bytes per second) from a device
      --device-read-iops=[]           Limit read rate (IO per second) from a device
      --device-write-bps=[]           Limit write rate (bytes per second) to a device
      --device-write-iops=[]          Limit write rate (IO per second) to a device
      --disable-content-trust=true    Skip image verification
      --dns=[]                        Set custom DNS servers
      --dns-opt=[]                    Set DNS options
      --dns-search=[]                 Set custom DNS search domains
      -e, --env=[]                    Set environment variables
      --entrypoint                    Overwrite the default ENTRYPOINT of the image
      --env-file=[]                   Read in a file of environment variables
      --expose=[]                     Expose a port or a range of ports
      --group-add=[]                  Add additional groups to join
      -h, --hostname                  Container host name
      --help                          Print usage
      -i, --interactive               Keep STDIN open even if not attached
      --ip                            Container IPv4 address (e.g. 172.30.100.104)
      --ip6                           Container IPv6 address (e.g. 2001:db8::33)
      --ipc                           IPC namespace to use
      --isolation                     Container isolation level
      --kernel-memory                 Kernel memory limit
      -l, --label=[]                  Set meta data on a container
      --label-file=[]                 Read in a line delimited file of labels
      --link=[]                       Add link to another container
      --log-driver                    Logging driver for container
      --log-opt=[]                    Log driver options
      -m, --memory                    Memory limit
      --mac-address                   Container MAC address (e.g. 92:d0:c6:0a:29:33)
      --memory-reservation            Memory soft limit
      --memory-swap                   Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness=-1          Tune container memory swappiness (0 to 100)
      --name                          Assign a name to the container
      --net=default                   Connect a container to a network
      --net-alias=[]                  Add network-scoped alias for the container
      --oom-kill-disable              Disable OOM Killer
      --oom-score-adj                 Tune host's OOM preferences (-1000 to 1000)
      -P, --publish-all               Publish all exposed ports to random ports
      -p, --publish=[]                Publish a container's port(s) to the host
      --pid                           PID namespace to use
      --privileged                    Give extended privileges to this container
      --read-only                     Mount the container's root filesystem as read only
      --restart=no                    Restart policy to apply when a container exits
      --rm                            Automatically remove the container when it exits
      --security-opt=[]               Security Options
      --shm-size                      Size of /dev/shm, default value is 64MB
      --sig-proxy=true                Proxy received signals to the process
      --stop-signal=SIGTERM           Signal to stop a container, SIGTERM by default
      --sysctl=map[]                  Sysctl options
      -t, --tty                       Allocate a pseudo-TTY
      --tmpfs=[]                      Mount a tmpfs directory
      -u, --user                      Username or UID (format: <name|uid>[:<group|gid>])
      --ulimit=[]                     Ulimit options
      --uts                           UTS namespace to use
      -v, --volume=[]                 Bind mount a volume
      --volume-driver                 Optional volume driver for the container
      --volumes-from=[]               Mount volumes from the specified container(s)
      -w, --workdir                   Working directory inside the container

    启动并创建一个交互式的docker容器:

    [root@localhost /]# docker run -ti -d 686672a1d0cc
    //-d为后台启动

    通过docker ps 来查看当前运行的容器,看下docker ps的相关指令:

    [root@localhost /]# docker ps --help
    
    Usage:  docker ps [OPTIONS]
    
    List containers
    
      -a, --all          Show all containers (default shows just running)
      -f, --filter=[]    Filter output based on conditions provided
      --format           Pretty-print containers using a Go template
      --help             Print usage
      -l, --latest       Show the latest created container (includes all states)
      -n=-1              Show n last created containers (includes all states)
      --no-trunc         Don't truncate output
      -q, --quiet        Only display numeric IDs
      -s, --size         Display total file sizes
    
    [root@localhost /]# docker ps//查看当前正在运行的容器
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    7d95b3df8674        686672a1d0cc        "/bin/bash"         5 hours ago         Up About an hour                        admiring_kowalevski
    
    [root@localhost /]# docker ps -a//查看所有的容器信息
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                           PORTS               NAMES
    7d95b3df8674        686672a1d0cc        "/bin/bash"         5 hours ago         Up About an hour                                     admiring_kowalevski
    1b4ac575eda0        686672a1d0cc        "/bin/bash"         23 hours ago        Exited (137) About an hour ago                       elated_turing

    通过dockerstart,docker stop来启动和停止容器:

    [root@localhost /]# docker start --help
    
    Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]
    
    Start one or more stopped containers
    
      -a, --attach         Attach STDOUT/STDERR and forward signals
      --detach-keys        Override the key sequence for detaching a container
      --help               Print usage
      -i, --interactive    Attach container's STDIN
    [root@localhost /]# docker stop --help
    
    Usage:  docker stop [OPTIONS] CONTAINER [CONTAINER...]
    
    Stop a running container.
    Sending SIGTERM and then SIGKILL after a grace period
    
      --help             Print usage
      -t, --time=10      Seconds to wait for stop before killing it
    [root@localhost /]# docker restart --help
    
    Usage:  docker restart [OPTIONS] CONTAINER [CONTAINER...]
    
    Restart a container
    
      --help             Print usage
      -t, --time=10      Seconds to wait for stop before killing the container

    使用docker exec 可以进入到已经启动的容器中,低版本的docker可能不行。

    [root@localhost Desktop]# docker exec -ti 7d95b3df8674 /bin/bash
    [root@7d95b3df8674 /]# 
       容器的工作是建立在镜像的基础之上的,如果需要删除镜像的话,需要先删除使用该镜像的容器,然后才能删除镜像,否则删除镜像的时候,会有如下的类似的错误信息提示:Failed to remove image (e7b): Error response from daemon: conflict: unable to delete e7b2de517efa (must be forced) - image is being used by stopped container 4fbc3cd00987,可以通过docker rm删除容器,docker rmi 删除镜像。
    
    [root@localhost /]# docker rm --help
    
    Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
    
    Remove one or more containers
    
      -f, --force        Force the removal of a running container (uses SIGKILL)
      --help             Print usage
      -l, --link         Remove the specified link
      -v, --volumes      Remove the volumes associated with the container
    [root@localhost /]# docker rmi --help
    
    Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]
    
    Remove one or more images
    
      -f, --force        Force removal of the image
      --help             Print usage
      --no-prune         Do not delete untagged parents
       删除停止的容器
       docker rm $(docker ps --all -q -f status=exited)
       删除没有使用的镜像
       docker rmi -f $(docker images | grep "<none>" | awk "{print $3}")
       批量删除容器
       docker ps -a | awk '{print $1}' | xargs docker rm
       批量删除镜像
       docker images | awk '{print $3}' | xargs docker rmi
       持久化容器与镜像
       1.通过容器生成新的镜像
       运行中的镜像称为容器。你可以修改容器(比如删除一个文件),但这些修改不会影响到镜像。不过,你使用docker commit <container-id> <image-name>命令可以把一个正在运行的容器变成一个新的镜像。
       docker commit <container> [repo:tag] 将一个container固化为一个新的image,后面的repo:tag可选。
       2.持久化容器
       docker export用于持久化容器。
    
    [root@localhost /]# docker export --help
    
    Usage:  docker export [OPTIONS] CONTAINER
    
    Export a container's filesystem as a tar archive
    
      --help             Print usage
      -o, --output       Write to a file, instead of STDOUT
    
     [root@localhost /]# docker export <CONTAINER ID>  container.tar 
       3.持久化镜像
       docker save用于持久化镜像:
    
    [root@localhost /]# docker save --help
    
    Usage:  docker save [OPTIONS] IMAGE [IMAGE...]
    
    Save an image(s) to a tar archive (streamed to STDOUT by default)
    
      --help             Print usage
      -o, --output       Write to a file, instead of STDOUT
    [root@localhost /]# docker save <CONTAINER ID>  image.tar 
       4.导入持久化镜像,容器:
       使用docker import,docker load导入镜像容器:
    
    [root@localhost /]#  docker import --help
    
    Usage:  docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
    
    Import the contents from a tarball to create a filesystem image
    
      -c, --change=[]    Apply Dockerfile instruction to the created image
      --help             Print usage
      -m, --message      Set commit message for imported image
    [root@localhost /]#  docker load --help
    
    Usage:  docker load [OPTIONS]
    
    Load an image from a tar archive or STDIN
    
      --help             Print usage
      -i, --input        Read from a tar archive file, instead of STDIN
       5.对镜像打tag
    
    [root@localhost /]# docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    docker.io/centos    7.2.1511            686672a1d0cc        5 weeks ago         194.6 MB
    [root@localhost /]# docker tag 686672a1d0cc centos:base
    [root@localhost /]# docker images
    REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
    centos              base                686672a1d0cc        5 weeks ago         194.6 MB
    docker.io/centos    7.2.1511            686672a1d0cc        5 weeks ago         194.6 MB
       6.export-import与save-load的区别
       导出后再导入(export-import)的镜像会丢失所有的历史,而保存后再加载(save-load)的镜像没有丢失历史和层(layer)。这意味着使用导出后再导入的方式,你将无法回滚到之前的层(layer),同时,使用保存后再加载的方式持久化整个镜像,就可以做到层回滚。(可以执行docker tag <LAYER ID> <IMAGE NAME>来回滚之前的层)。
       docker logs $CONTAINER_ID #查看docker实例运行日志,确保正常运行
       docker inspect $CONTAINER_ID #docker inspect <image|container> 查看image或container的底层信息
       docker build <path> 寻找path路径下名为的Dockerfile的配置文件,使用此配置生成新的image
       docker build -t repo[:tag] 同上,可以指定repo和可选的tag
       docker build - < <dockerfile> 使用指定的dockerfile配置文件,docker以stdin方式获取内容,使用此配置生成新的image
       docker port <container> <container port> 查看本地哪个端口映射到container的指定端口,其实用docker ps 也可以看到。
       7.docker文件存放目录
       Docker实际上把所有东西都放到/var/lib/docker路径下了。 
       至此一个简单干净的docker环境搭建完毕。
    

    参考:http://www.server110.com/docker/201411/11105.html 
    http://blog.csdn.net/fgf00/article/details/51893771 
    http://www.cnblogs.com/wangjiyong/p/5416960.html 
    https://github.com/docker/docker/releases 
    https://docs.docker.com/engine/installation/linux/centos/

    http://m.blog.csdn.net/article/details?id=52184285

  • 相关阅读:
    JAVA周二学习总结
    2019春总结作业
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业
    第八周作业
    第七周作业
    第六周作业
    第四周课程总结&试验报告(二)
  • 原文地址:https://www.cnblogs.com/Eilen/p/6751687.html
Copyright © 2011-2022 走看看