Docker简介

docker 是一个linux 上的LXC 容器项目,是很轻量级的虚拟化技术。

docker虽然基于lxc技术(cgroup、namespace等),但是思路完全和lxc不一样。

lxc看起来更像是一个虚拟机,多用于操作系统级别的虚拟化,背后的哲学是 IAAS;

而docker看起来是一个程序,跑在沙箱里的程序,属于应用程序级别的虚拟化,背后的哲学是 PAAS。

RHEL 6.5 开始提供docker 支持,我们使用 CentOS 6.6 x64 进行实验。


安装

yum install docker-io
如果提示:no package docker-io available
请先安装如下的rpm包,添加仓库地址:
rpm -iUvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm


命令

查看版本:docker -v

查看帮助信息:docker

在官方仓库搜寻镜像:docker search centos

查看本地镜像:docker images

下载仓库镜像到本地:docker pull centos:latest

上传本地镜像到仓库:docker push NAME[:TAG]

将镜像保存为tar文件:docker save -o tar文件 镜像ID/镜像tag

将tar文件加载为镜像:docker load -i tar文件

修改镜像tag:docker tag 镜像ID 镜像tag

删除镜像:docker rmi 镜像ID/镜像tag

制作镜像:docker build -t centos:autosshd - < dockerfile.txt

dockerfile.txt:

FROM centos
MAINTAINER YH, http://yuanhuan.blog.51cto.com
RUN yum install passwd openssl openssh-server -y
RUN echo '123456' | passwd --stdin root
RUN ssh-keygen -q -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ''
RUN ssh-keygen -q -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ''
RUN sed -i '/^session\s\+required\s\+pam_loginuid.so/s/^/#/' /etc/pam.d/sshd
RUN mkdir -p /root/.ssh && chown root.root /root && chmod 700 /root/.ssh
EXPOSE 22
CMD ip addr ls eth0 | awk '{print $2}' | egrep -o '([0-9]+\.){3}[0-9]+';/usr/sbin/sshd -D

查看镜像历史:docker history 镜像ID/镜像tag


创建容器:docker run -d --name=容器名称 镜像ID/镜像tag

将宿主机的80端口映射为容器的80端口:docker run -d -p 80:80 --name=容器名称 镜像ID/镜像tag

启动容器:docker start 容器名称/容器ID

查看容器:docker ps

重启容器:docker restart 容器名称/容器ID

停止容器:docker stop 容器名称/容器ID

删除容器:docker rm 容器名称/容器ID

暂停容器:docker pause 容器名称/容器ID

恢复容器:docker unpause 容器名称/容器ID

执行命令:docker exec -ti 容器名称/容器ID /bin/bash

获取容器日志:docker logs 容器名称/容器ID


典型应用场景

1. 应用打包:RPM打包,Tomcat应用服务器打包,Web服务器打包等;

2. 多版本混合部署:只用部署多个docker容器,每个版本一个容器,再通过hosting主机和容器做端口映射;

3. 升级回滚:升级时,只需停掉原有docker容器,新建一个新版本的容器即可,如有问题将旧版本容器重启即可;

4. 多租户资源隔离:docker容器充分利用linux内核的namespaces提供资源隔离功能,结合cgroup,可以方便的设置某个容器的资源配额。 既能满足资源隔离的需求,又能方便的为不同级别的用户设置不同级别的配额限制

5. 内部开发环境:不必像以往一样为每个开发人员分配一个或多个虚拟机,只用分配docker容器即可,资源利用率将会大幅上升;


附完整的docker-1.4.1命令:

Usage: docker [OPTIONS] COMMAND [arg...]

A self-sufficient runtime for linux containers.

Options:
  --api-enable-cors=false                Enable CORS headers in the remote API
  -b, --bridge=""                        Attach containers to a pre-existing network bridge
                                           use 'none' to disable container networking
  --bip=""                               Use this CIDR notation address for the network bridge's IP, not compatible with -b
  -D, --debug=false                      Enable debug mode
  -d, --daemon=false                     Enable daemon mode
  --dns=[]                               Force Docker to use specific DNS servers
  --dns-search=[]                        Force Docker to use specific DNS search domains
  -e, --exec-driver="native"             Force the Docker runtime to use a specific exec driver
  --fixed-cidr=""                        IPv4 subnet for fixed IPs (ex: 10.20.0.0/16)
                                           this subnet must be nested in the bridge subnet (which is defined by -b or --bip)
  -G, --group="docker"                   Group to assign the unix socket specified by -H when running in daemon mode
                                           use '' (the empty string) to disable setting of a group
  -g, --graph="/var/lib/docker"          Path to use as the root of the Docker runtime
  -H, --host=[]                          The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.
  --icc=true                             Allow unrestricted inter-container and Docker daemon host communication
  --insecure-registry=[]                 Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)
  --ip=0.0.0.0                           Default IP address to use when binding container ports
  --ip-forward=true                      Enable net.ipv4.ip_forward
  --ip-masq=true                         Enable IP masquerading for bridge's IP range
  --iptables=true                        Enable Docker's addition of iptables rules
  -l, --log-level="info"                 Set the logging level
  --label=[]                             Set key=value labels to the daemon (displayed in `docker info`)
  --mtu=0                                Set the containers network MTU
                                           if no value is provided: default to the default route MTU or 1500 if no default route is available
  -p, --pidfile="/var/run/docker.pid"    Path to use for daemon PID file
  --registry-mirror=[]                   Specify a preferred Docker registry mirror
  -s, --storage-driver=""                Force the Docker runtime to use a specific storage driver
  --selinux-enabled=false                Enable selinux support. SELinux does not presently support the BTRFS storage driver
  --storage-opt=[]                       Set storage driver options
  --tls=false                            Use TLS; implied by --tlsverify flag
  --tlscacert="/etc/docker/ca.pem"       Trust only remotes providing a certificate signed by the CA given here
  --tlscert="/etc/docker/cert.pem"       Path to TLS certificate file
  --tlskey="/etc/docker/key.pem"         Path to TLS key file
  --tlsverify=false                      Use TLS and verify the remote (daemon: verify client, client: verify daemon)
  -v, --version=false                    Print version information and quit

Commands:
    attach    Attach 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 from a container's filesystem to the host path
    create    Create a new container
    diff      Inspect changes on a container's filesystem
    events    Get real time events from the server
    exec      Run a command in a running container
    export    Stream the contents of a container as a tar archive
    history   Show the history of an image
    images    List images
    import    Create a new filesystem image from the contents of a tarball
    info      Display system-wide information
    inspect   Return low-level information on a container
    kill      Kill a running container
    load      Load an image from a tar archive
    login     Register or log in to a Docker registry server
    logout    Log out from a Docker registry server
    logs      Fetch the logs of a container
    port      Lookup the public-facing port that is NAT-ed to PRIVATE_PORT
    pause     Pause all processes within a container
    ps        List containers
    pull      Pull an image or a repository from a Docker registry server
    push      Push an image or a repository to a Docker registry server
    restart   Restart a running container
    rm        Remove one or more containers
    rmi       Remove one or more images
    run       Run a command in a new container
    save      Save an image to a tar archive
    search    Search for an image on the Docker Hub
    start     Start a stopped container
    stop      Stop a running container
    tag       Tag an image into a repository
    top       Lookup the running processes of a container
    unpause   Unpause a paused container
    version   Show the Docker version information
    wait      Block until a container stops, then print its exit code

Run 'docker COMMAND --help' for more information on a command.


Usage: docker attach [OPTIONS] CONTAINER

Attach to a running container

  --no-stdin=false    Do not attach STDIN
  --sig-proxy=true    Proxy all received signals to the process (non-TTY mode only). SIGCHLD, SIGKILL, and SIGSTOP are not proxied.


Usage: docker build [OPTIONS] PATH | URL | -

Build a new image from the source code at PATH

  --force-rm=false     Always remove intermediate containers, even after unsuccessful builds
  --no-cache=false     Do not use cache when building the image
  --pull=false         Always attempt to pull a newer version of the image
  -q, --quiet=false    Suppress the verbose output generated by the containers
  --rm=true            Remove intermediate containers after a successful build
  -t, --tag=""         Repository name (and optionally a tag) to be applied to the resulting image in case of success


Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

  -a, --author=""     Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -m, --message=""    Commit message
  -p, --pause=true    Pause container during commit


Usage: docker cp CONTAINER:PATH HOSTPATH

Copy files/folders from the PATH to the HOSTPATH



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

Create a new container

  -a, --attach=[]            Attach to STDIN, STDOUT or STDERR.
  --add-host=[]              Add a custom host-to-IP mapping (host:ip)
  -c, --cpu-shares=0         CPU shares (relative weight)
  --cap-add=[]               Add Linux capabilities
  --cap-drop=[]              Drop Linux capabilities
  --cidfile=""               Write the container ID to the file
  --cpuset=""                CPUs in which to allow execution (0-3, 0,1)
  --device=[]                Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)
  --dns=[]                   Set custom DNS servers
  --dns-search=[]            Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)
  -e, --env=[]               Set environment variables
  --entrypoint=""            Overwrite the default ENTRYPOINT of the image
  --env-file=[]              Read in a line delimited file of environment variables
  --expose=[]                Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host
  -h, --hostname=""          Container host name
  -i, --interactive=false    Keep STDIN open even if not attached
  --ipc=""                   Default is to create a private IPC namespace (POSIX SysV IPC) for the container
                               'container:<name|id>': reuses another container shared memory, semaphores and message queues
                               'host': use the host shared memory,semaphores and message queues inside the container.  Note: the host mode gives the container full access to local shared memory and is therefore considered insecure.
  --link=[]                  Add link to another container in the form of name:alias
  --lxc-conf=[]              (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
  -m, --memory=""            Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
  --mac-address=""           Container MAC address (e.g. 92:d0:c6:0a:29:33)
  --name=""                  Assign a name to the container
  --net="bridge"             Set the Network mode for the container
                               'bridge': creates a new network stack for the container on the docker bridge
                               'none': no networking for this container
                               'container:<name|id>': reuses another container network stack
                               'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
  -P, --publish-all=false    Publish all exposed ports to the host interfaces
  -p, --publish=[]           Publish a container's port to the host
                               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
                               (use 'docker port' to see the actual mapping)
  --privileged=false         Give extended privileges to this container
  --restart=""               Restart policy to apply when a container exits (no, on-failure[:max-retry], always)
  --security-opt=[]          Security Options
  -t, --tty=false            Allocate a pseudo-TTY
  -u, --user=""              Username or UID
  -v, --volume=[]            Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)
  --volumes-from=[]          Mount volumes from the specified container(s)
  -w, --workdir=""           Working directory inside the container


Usage: docker diff CONTAINER

Inspect changes on a container's filesystem



Usage: docker events [OPTIONS] 

Get real time events from the server

  -f, --filter=[]    Provide filter values (i.e. 'event=stop')
  --since=""         Show all events created since timestamp
  --until=""         Stream events until this timestamp


Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

  -d, --detach=false         Detached mode: run command in the background
  -i, --interactive=false    Keep STDIN open even if not attached
  -t, --tty=false            Allocate a pseudo-TTY


Usage: docker export CONTAINER

Export the contents of a filesystem as a tar archive to STDOUT



Usage: docker history [OPTIONS] IMAGE

Show the history of an image

  --no-trunc=false     Don't truncate output
  -q, --quiet=false    Only show numeric IDs


Usage: docker images [OPTIONS] [REPOSITORY]

List images

  -a, --all=false      Show all images (by default filter out the intermediate image layers)
  -f, --filter=[]      Provide filter values (i.e. 'dangling=true')
  --no-trunc=false     Don't truncate output
  -q, --quiet=false    Only show numeric IDs


Usage: docker import URL|- [REPOSITORY[:TAG]]

Create an empty filesystem image and import the contents of the tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then optionally tag it.



Usage: docker info 

Display system-wide information



Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]

Return low-level information on a container or image

  -f, --format=""    Format the output using the given go template.


Usage: docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill a running container using SIGKILL or a specified signal

  -s, --signal="KILL"    Signal to send to the container


Usage: docker load [OPTIONS] 

Load an image from a tar archive on STDIN

  -i, --input=""     Read from a tar archive file, instead of STDIN


Usage: docker login [OPTIONS] [SERVER]

Register or log in to a Docker registry server, if no server is specified "https://index.docker.io/v1/" is the default.

  -e, --email=""       Email
  -p, --password=""    Password
  -u, --username=""    Username


Usage: docker logout [SERVER]

Log out from a Docker registry, if no server is specified "https://index.docker.io/v1/" is the default.



Usage: docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

  -f, --follow=false        Follow log output
  -t, --timestamps=false    Show timestamps
  --tail="all"              Output the specified number of lines at the end of logs (defaults to all logs)


Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]]

List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT



Usage: docker pause CONTAINER

Pause all processes within a container



Usage: docker ps [OPTIONS] 

List containers

  -a, --all=false       Show all containers. Only running containers are shown by default.
  --before=""           Show only container created before Id or Name, include non-running ones.
  -f, --filter=[]       Provide filter values. Valid filters:
                          exited=<int> - containers with exit code of <int>
                          status=(restarting|running|paused|exited)
  -l, --latest=false    Show only the latest created container, include non-running ones.
  -n=-1                 Show n last created containers, include non-running ones.
  --no-trunc=false      Don't truncate output
  -q, --quiet=false     Only display numeric IDs
  -s, --size=false      Display total file sizes
  --since=""            Show only containers created since Id or Name, include non-running ones.


Usage: docker pull [OPTIONS] NAME[:TAG]

Pull an image or a repository from the registry

  -a, --all-tags=false    Download all tagged images in the repository


Usage: docker push NAME[:TAG]

Push an image or a repository to the registry



Usage: docker restart [OPTIONS] CONTAINER [CONTAINER...]

Restart a running container

  -t, --time=10      Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.


Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...]

Remove one or more containers

  -f, --force=false      Force the removal of a running container (uses SIGKILL)
  -l, --link=false       Remove the specified link and not the underlying container
  -v, --volumes=false    Remove the volumes associated with the container


Usage: docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

  -f, --force=false    Force removal of the image
  --no-prune=false     Do not delete untagged parents


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)
  -c, --cpu-shares=0         CPU shares (relative weight)
  --cap-add=[]               Add Linux capabilities
  --cap-drop=[]              Drop Linux capabilities
  --cidfile=""               Write the container ID to the file
  --cpuset=""                CPUs in which to allow execution (0-3, 0,1)
  -d, --detach=false         Detached mode: run the container in the background and print the new container ID
  --device=[]                Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)
  --dns=[]                   Set custom DNS servers
  --dns-search=[]            Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)
  -e, --env=[]               Set environment variables
  --entrypoint=""            Overwrite the default ENTRYPOINT of the image
  --env-file=[]              Read in a line delimited file of environment variables
  --expose=[]                Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host
  -h, --hostname=""          Container host name
  -i, --interactive=false    Keep STDIN open even if not attached
  --ipc=""                   Default is to create a private IPC namespace (POSIX SysV IPC) for the container
                               'container:<name|id>': reuses another container shared memory, semaphores and message queues
                               'host': use the host shared memory,semaphores and message queues inside the container.  Note: the host mode gives the container full access to local shared memory and is therefore considered insecure.
  --link=[]                  Add link to another container in the form of name:alias
  --lxc-conf=[]              (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"
  -m, --memory=""            Memory limit (format: <number><optional unit>, where unit = b, k, m or g)
  --mac-address=""           Container MAC address (e.g. 92:d0:c6:0a:29:33)
  --name=""                  Assign a name to the container
  --net="bridge"             Set the Network mode for the container
                               'bridge': creates a new network stack for the container on the docker bridge
                               'none': no networking for this container
                               'container:<name|id>': reuses another container network stack
                               'host': use the host network stack inside the container.  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
  -P, --publish-all=false    Publish all exposed ports to the host interfaces
  -p, --publish=[]           Publish a container's port to the host
                               format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
                               (use 'docker port' to see the actual mapping)
  --privileged=false         Give extended privileges to this container
  --restart=""               Restart policy to apply when a container exits (no, on-failure[:max-retry], always)
  --rm=false                 Automatically remove the container when it exits (incompatible with -d)
  --security-opt=[]          Security Options
  --sig-proxy=true           Proxy received signals to the process (non-TTY mode only). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.
  -t, --tty=false            Allocate a pseudo-TTY
  -u, --user=""              Username or UID
  -v, --volume=[]            Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)
  --volumes-from=[]          Mount volumes from the specified container(s)
  -w, --workdir=""           Working directory inside the container


Usage: docker save [OPTIONS] IMAGE [IMAGE...]

Save an image(s) to a tar archive (streamed to STDOUT by default)

  -o, --output=""    Write to a file, instead of STDOUT


Usage: docker search [OPTIONS] TERM

Search the Docker Hub for images

  --automated=false    Only show automated builds
  --no-trunc=false     Don't truncate output
  -s, --stars=0        Only displays with at least x stars


Usage: docker start [OPTIONS] CONTAINER [CONTAINER...]

Restart a stopped container

  -a, --attach=false         Attach container's STDOUT and STDERR and forward all signals to the process
  -i, --interactive=false    Attach container's STDIN


Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...]

Stop a running container by sending SIGTERM and then SIGKILL after a grace period

  -t, --time=10      Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.


Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]

Tag an image into a repository

  -f, --force=false    Force


Usage: docker top CONTAINER [ps OPTIONS]

Display the running processes of a container



Usage: docker unpause CONTAINER

Unpause all processes within a container



Usage: docker version 

Show the Docker version information.



Usage: docker wait CONTAINER [CONTAINER...]

Block until a container stops, then print its exit code.