频道栏目
首页 > 资讯 > 云计算 > 正文

docker学习笔记

17-05-22        来源:[db:作者]  
收藏   我要投稿

docker

Docker 是一个开源的应用容器引擎。作用是让开发者打包自己的应用软件和依赖环境到一个可移植的容器中。然后发布出来。
Docker是典型的PaaS平台业务,和IaaS的Openstack相比较。除了一个达到了应用级别,一个只是达到操作系统级别之外。在虚拟化的方面,Docker并没有传统虚拟化的Hypervisor层。因为Docker只是基于容器的轻量级虚拟化,其虚拟化技术是基于内核的Cgroup和Namespace技术,处理逻辑和内核深度融合,所以在许多方面,Docker都与真机性能十分接近。
可能有人懵了,Hypervisor是什么,Cgroup和Namespace又是什么。
Hypervisor:一种运行在物理服务器和操作系统之间的中间软件层,可允许多个操作系统和应用共享一套基础物理硬件,因此也可以看作是虚拟环境中的“元”操作系统,它可以协调访问服务器上的所有物理设备和虚拟机,也叫虚拟机监视器(Virtual Machine Monitor)
至于Cgroup和Namespace在之后会介绍
在通信上,Docker并不会直接与内核交互,他是通过一个更为底层的工具Libcontainer与内核交互。Libcontainer是真正意义上的容器引擎,他通过clone系统调用直接创建容器。
传统虚拟机的架构
Docker 的架构图

Docker的功能与组件

Docker的组成:
1.Docker 客户端
2.Docker daemon
3.Docker容器
4.Docker镜像
5.Registry


一. Docker客户端

Docker客户端一般通过Docker command来发起请求。
功能:就是发起请求

二.Docker daemon

Docker daemon也可以被理解为Docker server,或者说是Docker Engine 来描述,因为它实际驱动整个Docker功能的核心。
功能:接收客户端的请求并返回结果,实现上涉及了容器,镜像,存储等多个方面。

三.Docker容器

Docker容器是核心内容,在概念上,容器很好的诠释了Docker集装箱的概念。集装箱可以存放任何货物,并且通过邮轮将货物运往世界各地,并不用关心集装箱里到底装了什么,他只要运行起来就好了。
功能:Docker通过Libcontainer实现对容器整个生命周期的管理,信息的设置等等,而容器是对镜像的完美诠释,容器以镜像为基础,同时又给镜像提供了一个标准和隔离的环境。

四.Docker镜像

与容器相对应,容器是一个完整的,隔离的运行环境。而镜像就是运行环境的静态体现,是一个还没有运行的环境。
功能:提供镜像

五.Registry

Registry(注册表)提供的是存放镜像的仓库,通常被部署到云端,在镜像的传输过程中,Registry就是这个传输的中转站,假如在公司将一个软件运行环境制作成镜像,并且上传到Regsitry中,这时在家里也可以方便的下载运行了。
Docker公司提供的官方是Registry叫Docker Hub。

安装Docker

这个看官网是最权威的了,可以在Centos,Ubuntu上等等上部署。
https://docs.docker.com/engine/installation/linux/centos/
官方的资料是最好的学习资料,而且从安装到入门再到进阶都有详细的资料,还是应该从官方网站上学习。
# docker --help

Usage:	docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -D, --debug              Enable debug mode
      --help               Print usage
  -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:
  container   Manage containers
  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
  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。

容器组成

Cgroup:资源控制
Namespace:访问隔离
rootfs:文件系统隔离
容器引擎:生命周期控制


Cgroup介绍

是Control group的简称,属于Linux的特性。用于隔离和限制一组进程对系统资源的调用,这些资源包括CPU,内存,block/IO 和网络带宽。
  • 资源限制(Resource Limitation):cgroups可以对进程组使用的资源总额进行限制。如设定应用运行时使用内存的上限,一旦超过这个配额就发出OOM(Out of Memory)。
  • 优先级分配(Prioritization):通过分配的CPU时间片数量及硬盘IO带宽大小,实际上就相当于控制了进程运行的优先级。
  • 资源统计(Accounting): cgroups可以统计系统的资源使用量,如CPU使用时长、内存用量等等,这个功能非常适用于计费。
  • 进程控制(Control):cgroups可以对进程组执行挂起、恢复等操作。

Namespace介绍

是将全局资源做封装,使得每个Namespace都有一份独立的资源,就是各个空间的资源互相不影响,比如在A空间定义了一个防火墙规则,并不会影响B空间的防火墙规则, 在A中的IP地址也是独立的,内核规则也是不互相影响的。
  • IPC:隔离system V IPC 和POSIX消息队列
  • Network:隔离网络资源。
  • Mount:隔离文件系统的挂载点。
  • PID:隔离进程的ID
  • UTS:隔离主机名
  • User:隔离用户ID和组ID
关于网络的namespace相关博客:http://blog.csdn.net/ghost_leader/article/details/71075551

Docker镜像

下来先快点接触一下Docker,按照官网上的介绍使用步骤,运行了第一个实例。
# docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://cloud.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/engine/userguide/

 
docker的官网上举了这样一个例子。当使用python应用时,因为没有python的运行环境,而造成无法运行。所以可以使用docker来封装一个环境。
首先创建一个空目录。
# mkdir Docker
进入Docker目录
# vim Dockerfile

# Use an official Python runtime as a base image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

# Copy the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]

 
创建配置文件,配置所需的Python库。
# vim requirements.txt
Flask
Redis

 
创建python代码
# vim app.py
from flask import Flask
from redis import Redis, RedisError
import os
import socket

# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)

app = Flask(__name__)

@app.route("/")
def hello():
    try:
        visits = redis.incr('counter')
    except RedisError:
        visits = "cannot connect to Redis, counter disabled"

    html = "

Hello {name}!

" \ "Hostname: {hostname}
" \ "Visits: {visits}" return html.format(name=os.getenv('NAME', "world"), hostname=socket.gethostname(), visits=visits) if __name__ == "__main__": app.run(host='0.0.0.0', port=80)
 
构建应用。
# ls
app.py  Dockerfile  requirements.txt
# docker build -t friendlyhello .
Sending build context to Docker daemon  4.608kB
Step 1/7 : FROM python:2.7-slim
...
运行
# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
friendlyhello       latest              93423083d7ee        3 minutes ago       195MB
python              2.7-slim            1c7128a655f6        5 days ago          183MB
hello-world         latest              48b5124b2768        4 months ago        1.84kB
# docker run -d -p 4000:80 friendlyhello
2c5de434a914af2cc7b6a6b6a3bb4813e61d9d69682ea736b646b907f7847e22

 
此时4000端口已经被监听
# lsof -i :4000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
docker-pr 12445 root 4u IPv6 229078 0t0 TCP *:terabase (LISTEN)
访问试试
停止运行容器
# docker stop 2c
(2c就可以代表2c5de434a914了)
分享我的镜像
首先按照官网的提示,在cloud.docker.com上注册了一个账号。
然后
# docker login 登录
标记相关的镜像。
# docker tag friendlyhello 454041823/hello:tag
上传
# docker push 454041823/hello:tag
The push refers to a repository [docker.io/454041823/hello]
7fe3e2095f40: Pushing [==>                                                ]  512.5kB/11.82MB
268907610fca: Pushing [==================================================>]   5.12kB
802dd921ccea: Pushed 
7b7f69d6236f: Pushing [=========>                                         ]  1.113MB/5.737MB
667e68ed0db3: Pushing [=>                                                 ]  934.4kB/45.71MB
5eac2de68a97: Pushing [>                                                  ]  77.82kB/7.749MB
8d4d1ab5ff74: Waiting 

 
一旦完成,就可以直接运行了。
# docker run -d -p 4000:80 454041823/hello:tag
下面介绍一下docker的相关简单命令。
docker run <容器名字> 运行一个新的容器
docker images 列出所有的镜像
docker build -t friendlyname . 利用目录中的文件创建一个镜像
运行相关
docker run -p 4000:80 friendlyname 运行一个镜像,并且端口映射
docker run -d -p 4000:80 friendlyname 独立模式运行
管理镜像/容器相关
docker ps 列出当前正在运行的容器
docker ps -a 列出所有在运行的容器
docker stop <容器名字> 停止一个容器
docker kill <容器名字> 强制停止一个容器
docker rm <容器名字> 删除一个容器
docker rm $(docker ps -a -q) 删除所有的容器
docker rmi <镜像名字> 删除一个镜像
docker rmi $(docker images -q) 删除所有镜像
分享镜像相关
docker login 登录cloud.docker.com
docker tag username/repository:tag 标记容器
docker push username/repository:tag 上传容器
docker run -p 4000:80 username/repository 运行远端的容器
但是,访问docker 的官网太慢了。
这就需要一个docker加速器了。
daocloud提供的加速器用起来很方便啊!!!!
什么事docker加速器呢,就是使用docker时,经常需要从官方拉取镜像,但是网络问题,操作很慢。
这样就出现了加速器,极大的提升了国内访问docker hub的速度。
配置方法。
# curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://c99cdc9f.m.daocloud.io
# systemctl restart docker
这节就写到这,更多的再后面再写。
相关TAG标签
上一篇:Squid代理
下一篇:一些CSS小结
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站