docker-容器即服务

1 docker历史

学习一门技术首先要了解它的历史。这是很必要的。docker现在是一门非常火的技术,无论是对于开发还是运维都应该掌握。
在这里插入图片描述
Docker 公司位于旧金山,由法裔美籍开发者和企业家 Solumon Hykes 创立;Docker 公司起初是一家名为 dotCloud 的平台即服务(Platform-as-a-Service, PaaS)提供商;

底层技术上,dotCloud 平台利用了 Linux 容器技术。为了方便创建和管理这些容器,dotCloud 开发了一套内部工具,之后被命名为“Docker”。Docker就是这样诞生的!

2013年,dotCloud 的 PaaS 业务并不景气,公司需要寻求新的突破。于是他们聘请了 Ben Golub 作为新的 CEO,将公司重命名为“Docker”,放弃dotCloud PaaS 平台,怀揣着“将 Docker 和容器技术推向全世界”的使命,开启了一段新的征程。

如今 Docker 公司被普遍认为是一家创新型科技公司,据说其市场价值约为 10 亿美元。Docker 公司已经通过多轮融资,吸纳了来自硅谷的几家风投公司的累计超过 2.4 亿美元的投资。

几乎所有的融资都发生在公司更名为“Docker”之后。

“Docker”一词来自英国口语,意为码头工人(Dock Worker),即从船上装卸货物的人。

了解完历史之后,学习一门技术最重要的是官方网站,docker的官方文档真的超级详细
docker官方文档链接:https://docs.docker.com/reference/

2 docker架构

Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的Linux机器或Windows 机器上,也可以实现虚拟化,容器是完全使用沙箱机制,相互之间不会有任何接口。
一个完整的Docker有以下几个部分组成:

  • DockerClient客户端
  • Docker Daemon守护进程
  • Docker Image镜像
  • DockerContainer容器
    在这里插入图片描述
    Docker采用 C/S架构 Docker daemon 作为服务端接受来自客户的请求,并处理这些请求(创建、运行、分发容器)。 客户端和服务端既可以运行在一个机器上,也可通过 socket 或者RESTful API 来进行通信。
    Docker daemon 一般在宿主主机后台运行,等待接收来自客户端的消息。 Docker 客户端则为用户提供一系列可执行命令,用户用这些命令实现跟 Docker daemon 交互。
    Docker类比面向对象:
Docker面向对象
镜像
容器对象

虚拟机对比Docker:
在这里插入图片描述

Docker虚拟机
隔离性较强
资源开销
镜像大小MBGB
启动速度秒级分钟级

3 安装docker

docker可以安装在linux多个发行版、windows和macOS,
安装过程不细节描述,如果读者需要的话请自行百度。

4 docker命令

博主的机器版本

[root@localhost ~]# uname -r
3.10.0-1160.el7.x86_64
# 查看docker是否启动
[root@localhost ~]# systemctl status docker
# 操作docker服务的其他命令
systemctl start docker    # 启动docker服务
systemctl stop docker     # 停止docker服务
systemctl restart docker  # 重启docker服务
systemctl enable docker   # 使能docker开机自启动
systemctl disable docker  # 停止docker开机自启动

在这里插入图片描述

# 查看docker版本信息
[root@localhost ~]# docker --version
Docker version 1.13.1, build 0be3e21/1.13.1
# 查看docker信息
[root@localhost ~]# docker info

在这里插入图片描述

# 帮助命令
[root@localhost ~]# 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 (default [])
  -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 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 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

5 docker常用命令

在这里插入图片描述

5.1 镜像常用命令

镜像由远程仓库托管,用户可以搜索、拉取、打包、删除镜像

# 搜索mysql
[root@localhost ~]# docker search mysql
______________________________________________________________________________________
INDEX       NAME                                        DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
docker.io   docker.io/mysql                             MySQL is a widely used, open-source relati...   10970     [OK]       
docker.io   docker.io/mariadb                           MariaDB Server is a high performing open s...   4148      [OK]       
docker.io   docker.io/mysql/mysql-server                Optimized MySQL Server Docker images. Crea...   814                  [OK]
docker.io   docker.io/percona                           Percona Server is a fork of the MySQL rela...   540       [OK]       
docker.io   docker.io/centos/mysql-57-centos7           MySQL 5.7 SQL database server                   88                   
docker.io   docker.io/mysql/mysql-cluster               Experimental MySQL Cluster Docker images. ...   85                   
docker.io   docker.io/centurylink/mysql                 Image containing mysql. Optimized to be li...   59                   [OK]
docker.io   docker.io/bitnami/mysql                     Bitnami MySQL Docker Image                      52                   [OK]
docker.io   docker.io/databack/mysql-backup             Back up mysql databases to... anywhere!         44                   
docker.io   docker.io/deitch/mysql-backup               REPLACED! Please use http://hub.docker.com...   41                   [OK]
docker.io   docker.io/prom/mysqld-exporter                                                              39                   [OK]
docker.io   docker.io/tutum/mysql                       Base docker image to run a MySQL database ...   35                   
docker.io   docker.io/linuxserver/mysql                 A Mysql container, brought to you by Linux...   30                   
docker.io   docker.io/schickling/mysql-backup-s3        Backup MySQL to S3 (supports periodic back...   29                   [OK]
docker.io   docker.io/centos/mysql-56-centos7           MySQL 5.6 SQL database server                   20                   
docker.io   docker.io/circleci/mysql                    MySQL is a widely used, open-source relati...   20                   
docker.io   docker.io/mysql/mysql-router                MySQL Router provides transparent routing ...   19                   
docker.io   docker.io/arey/mysql-client                 Run a MySQL client from a docker container      17                   [OK]
docker.io   docker.io/fradelg/mysql-cron-backup         MySQL/MariaDB database backup using cron t...   13                   [OK]
docker.io   docker.io/yloeffler/mysql-backup            This image runs mysqldump to backup data u...   7                    [OK]
docker.io   docker.io/openshift/mysql-55-centos7        DEPRECATED: A Centos7 based MySQL v5.5 ima...   6                    
docker.io   docker.io/devilbox/mysql                    Retagged MySQL, MariaDB and PerconaDB offi...   3                    
docker.io   docker.io/ansibleplaybookbundle/mysql-apb   An APB which deploys RHSCL MySQL                2                    [OK]
docker.io   docker.io/jelastic/mysql                    An image of the MySQL database server main...   1                    
docker.io   docker.io/widdpim/mysql-client              Dockerized MySQL Client (5.7) including Cu...   1                    [OK]
# search指令帮助
[root@localhost ~]# docker search --help
______________________________________________________________________________________
Usage:	docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   Filter output based on conditions provided
      --help            Print usage
      --limit int       Max number of search results (default 25)
      --no-index        Don't truncate output
      --no-trunc        Don't truncate output
# 按照指定条件过滤
[root@localhost ~]# docker search -f stars=3000 mysql
______________________________________________________________________________________
INDEX       NAME                DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
docker.io   docker.io/mysql     MySQL is a widely used, open-source relati...   10970     [OK]       
docker.io   docker.io/mariadb   MariaDB Server is a high performing open s...   4148      [OK]      
# 查看目前所有的镜像
[root@localhost ~]# docker images
______________________________________________________________________________________
REPOSITORY           TAG                 IMAGE ID            CREATED             SIZE
docker.io/redis      latest              7f33e76fcb56        2 months ago        105 MB
docker.io/nginx      latest              7ce4f91ef623        2 months ago        133 MB
docker.io/mysql      5.7                 cd0f0b1e283d        2 months ago        449 MB
docker.io/postgres   9.4                 ed5a45034282        16 months ago       251 MB
# 

# 删除一个镜像,当这个镜像有运行的容器时,会提示删除失败
[root@localhost ~]# docker rmi 7f33e76fcb56
______________________________________________________________________________________
Error response from daemon: conflict: unable to delete 7f33e76fcb56 (must be forced) - image is being used by stopped container 092bba0f9933

# 查看rmi命令的可选参数
[root@localhost ~]# docker rmi --help
______________________________________________________________________________________
Usage:	docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Options:
  -f, --force      Force removal of the image
      --help       Print usage
      --no-prune   Do not delete untagged parents

# 强力删除镜像,不管是否有这个镜像的容器在运行
[root@localhost ~]# docker rmi -f docker_ID

# 强力递归删除所有镜像
[root@localhost ~]# docker rmi -f $(docker images)

# 拉取镜像,从远程仓库下载到本地
docker pull 镜像名[:Tag] #Tag是版本号

5.2 容器常用命令

# 查看docker ps --help
[root@localhost ~]# docker ps --help
______________________________________________________________________________________
Usage:	docker ps [OPTIONS]

List containers

Options:
  -a, --all             Show all containers (default shows just running)
  -f, --filter filter   Filter output based on conditions provided
      --format string   Pretty-print containers using a Go template
      --help            Print usage
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (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 -a
______________________________________________________________________________________
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
092bba0f9933        7f33e76fcb56        "docker-entrypoint..."   2 months ago        Exited (0) 2 months ago                         redis-test
b3b652ece004        7ce4f91ef623        "/docker-entrypoin..."   2 months ago        Exited (0) 2 months ago                         dockernginx
e48c6bbcad77        ed5a45034282        "docker-entrypoint..."   2 months ago        Exited (0) 2 months ago                         pgsql
e7067011b293        cd0f0b1e283d        "docker-entrypoint..."   2 months ago        Exited (0) 18 minutes ago                       dockermysql

# 查看所有的容器 只显示ID
[root@localhost ~]# docker ps -aq
______________________________________________________________________________________
092bba0f9933
b3b652ece004
e48c6bbcad77
e7067011b293

# 查看正在运行的容器
[root@localhost ~]# docker ps
______________________________________________________________________________________
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
e7067011b293        cd0f0b1e283d        "docker-entrypoint..."   2 months ago        Up 3 seconds        33060/tcp, 0.0.0.0:3307->3306/tcp   dockermysql

# 删除一个容器(not running)
[root@localhost ~]# docker rm docker_ID

# 强制删除一个容器
[root@localhost ~]# docker rm -f docker_ID

# 递归删除所有容器
[root@localhost ~]# docker rm $(docker ps -aq)
092bba0f9933
b3b652ece004
e48c6bbcad77

# 运行一个容器(还没有实例化)
[root@localhost ~]# docker run 镜像名
______________________________________________________________________________________

# 启动一个已经实例化的容器
[root@localhost ~]# docker start 容器ID

[root@localhost ~]# docker start dockermysql
dockermysql
[root@localhost ~]# docker ps
______________________________________________________________________________________
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
e7067011b293        cd0f0b1e283d        "docker-entrypoint..."   2 months ago        Up 3 seconds        33060/tcp, 0.0.0.0:3307->3306/tcp   dockermysql
[root@localhost ~]# docker stop dockermysql
dockermysql

# 停止一个正在运行的容器
[root@localhost ~]# docker stop 容器ID

5.3 docker run 命令

docker run也是一种容器命令,为什么单独拿出来说,就是因为太重要。

# 查看docker run命令的帮助
[root@localhost ~]# 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) (default [])
  -a, --attach list                           Attach to STDIN, STDOUT or STDERR (default [])
      --blkio-weight uint16                   Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device weighted-device   Block IO weight (relative device weight) (default [])
      --cap-add list                          Add Linux capabilities (default [])
      --cap-drop list                         Drop Linux capabilities (default [])
      --cgroup-parent string                  Optional parent cgroup for the container
      --cidfile string                        Write the container ID to the file
      --cpu-count int                         CPU count (Windows only)
      --cpu-percent int                       CPU percent (Windows only)
      --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 (default 0.000)
      --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)
      --credentialspec string                 Credential spec for managed service account (Windows only)
  -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 (default [])
      --device-read-bps throttled-device      Limit read rate (bytes per second) from a device (default [])
      --device-read-iops throttled-device     Limit read rate (IO per second) from a device (default [])
      --device-write-bps throttled-device     Limit write rate (bytes per second) to a device (default [])
      --device-write-iops throttled-device    Limit write rate (IO per second) to a device (default [])
      --disable-content-trust                 Skip image verification (default true)
      --dns list                              Set custom DNS servers (default [])
      --dns-option list                       Set DNS options (default [])
      --dns-search list                       Set custom DNS search domains (default [])
      --entrypoint string                     Overwrite the default ENTRYPOINT of the image
  -e, --env list                              Set environment variables (default [])
      --env-file list                         Read in a file of environment variables (default [])
      --expose list                           Expose a port or a range of ports (default [])
      --group-add list                        Add additional groups to join (default [])
      --health-cmd string                     Command to run to check health
      --health-interval duration              Time between running the check (ns|us|ms|s|m|h) (default 0s)
      --health-retries int                    Consecutive failures needed to report unhealthy
      --health-timeout duration               Maximum time to allow one check to run (ns|us|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
      --init-path string                      Path to the docker-init binary
  -i, --interactive                           Keep STDIN open even if not attached
      --io-maxbandwidth string                Maximum IO bandwidth limit for the system drive (Windows only)
      --io-maxiops uint                       Maximum IOps limit for the system drive (Windows only)
      --ip string                             Container IPv4 address (e.g. 172.30.100.104)
      --ip6 string                            Container IPv6 address (e.g. 2001:db8::33)
      --ipc string                            IPC namespace to use
      --isolation string                      Container isolation technology
      --kernel-memory string                  Kernel memory limit
  -l, --label list                            Set meta data on a container (default [])
      --label-file list                       Read in a line delimited file of labels (default [])
      --link list                             Add link to another container (default [])
      --link-local-ip list                    Container IPv4/IPv6 link-local addresses (default [])
      --log-driver string                     Logging driver for the container
      --log-opt list                          Log driver options (default [])
      --mac-address string                    Container MAC address (e.g. 92:d0:c6:0a:29:33)
  -m, --memory string                         Memory limit
      --memory-reservation string             Memory soft limit
      --memory-swap string                    Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int                 Tune container memory swappiness (0 to 100) (default -1)
      --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 (default [])
      --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 (default [])
  -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 (default [])
      --shm-size string                       Size of /dev/shm, default value is 64MB
      --sig-proxy                             Proxy received signals to the process (default true)
      --stop-signal string                    Signal to stop a container, SIGTERM by default (default "SIGTERM")
      --stop-timeout int                      Timeout (in seconds) to stop a container
      --storage-opt list                      Storage driver options for the container (default [])
      --sysctl map                            Sysctl options (default map[])
      --tmpfs list                            Mount a tmpfs directory (default [])
  -t, --tty                                   Allocate a pseudo-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 (default [])
      --volume-driver string                  Optional volume driver for the container
      --volumes-from list                     Mount volumes from the specified container(s) (default [])
  -w, --workdir string                        Working directory inside the container

MySQL为例说明run命令的实际应用
确保本地已经拉取到了mysql的镜像

docker run --name docker5.7.1 -p 3310:3306  -e MYSQL_ROOT_PASSWORD=root -d  mysql:5.7
		   --name # 给实例起一个名字
		   -p  	  # 端口映射 宿主机端口:容器端口
		   -e     # 环境变量
		   -d     # 后台启动

在这里插入图片描述
通过宿主机IP:PORT连接到docker镜像的mysql服务器

通过挂载将镜像中的数据同步到宿主机中,比如mysql的配置文件和数据文件,可以在宿主机中做配置,并且把数据备份到宿主机中。

-v 宿主机文件目录:容器文件目录

6 docker-compose

6.1 安装

Linux系统安装操作步骤

下载

curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

添加权限

chmod +x /usr/local/bin/docker-compose

添加软连接

ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

查看版本,如果安装成功会出现版本信息

docker-compose --version

其他操作系统安装请参考官方链接:
https://docs.docker.com/compose/install/

6.2 卸载重装

如果出现下面所示的报错

[root@localhost composetest]# docker-compose up
Building web
unknown flag: --iidfile
See 'docker build --help'.
ERROR: Service 'web' failed to build : Build failed

卸载1.29.1 版本 下载1.26.2版本

[root@localhost composetest]# rm -f /usr/local/bin/docker-compose
[root@localhost composetest]# curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose && chmod +x /usr/local/bin/docker-compose
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   633  100   633    0     0    588      0  0:00:01  0:00:01 --:--:--   588
100 11.6M  100 11.6M    0     0   216k      0  0:00:55  0:00:55 --:--:-- 1182k
[root@localhost composetest]# docker-compose --version
docker-compose version 1.26.2, build eefe0d31
[root@localhost composetest]# docker-compose up
Building web
Step 1/10 : FROM python:3.7-alpine
 ---> 0217c3d2f165
Step 2/10 : WORKDIR /code
# 解决问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kobe_OKOK_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值