docker安装及使用

1、环境检测

docker对linux目前支持的版本
CentOS 7 (64-bit)
CentOS 6.5 (64-bit) 或更高的版本
目前,CentOS 仅发行版本中的内核支持 Docker。
Docker 运行在 CentOS 7 上,要求系统为64位、系统内核版本为 3.10 以上。
Docker 运行在 CentOS-6.5 或更高的版本的 CentOS 上,要求系统为64位、系统内核版本为 2.6.32-431 或者更高版本。

检测系统内核

通过 uname -r 命令查看你当前的内核版本

[root@localhost app]# uname -r
3.10.0-229.el7.x86_64

2、安装docker

分为两个分支版本: Docker CE 和 Docker EE。

移除旧的版本:

[root@localhost etc]# yum remove docker \
>                   docker-client \
>                   docker-client-latest \
>                   docker-common \
>                   docker-latest \
>                   docker-latest-logrotate \
>                   docker-logrotate \
>                   docker-selinux \
>                   docker-engine-selinux \
>                   docker-engine
Loaded plugins: fastestmirror, langpacks
No Match for argument: docker
No Match for argument: docker-client
No Match for argument: docker-client-latest
No Match for argument: docker-common
No Match for argument: docker-latest
No Match for argument: docker-latest-logrotate
No Match for argument: docker-logrotate
No Match for argument: docker-selinux
No Match for argument: docker-engine-selinux
No Match for argument: docker-engine
No Packages marked for removal

安装一些必要的系统工具:

[root@localhost etc]# yum install -y yum-utils device-mapper-persistent-data lvm2
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package device-mapper-persistent-data.x86_64 0:0.4.1-2.el7 will be updated
---> Package device-mapper-persistent-data.x86_64 0:0.7.3-3.el7 will be an update
---> Package lvm2.x86_64 7:2.02.115-3.el7 will be updated
---> Package lvm2.x86_64 7:2.02.180-10.el7_6.7 will be an update

添加软件源信息:

[root@localhost etc]# yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Loaded plugins: fastestmirror, langpacks
adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
grabbing file http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo

更新yum缓存:

[root@localhost app]# yum makecache fast
Loaded plugins: fastestmirror, langpacks
base                                                                                                                                                | 3.6 kB  00:00:00     
docker-ce-stable                                                                                                                                    | 3.5 kB  00:00:00     
extras                                                                                                                                              | 3.4 kB  00:00:00     
updates                                                                                                                                             | 3.4 kB  00:00:00     
(1/2): docker-ce-stable/x86_64/updateinfo                                                                                                           |   55 B  00:00:00     
(2/2): docker-ce-stable/x86_64/primary_db                                                                                                           |  28 kB  00:00:02     
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Metadata Cache Created

安装docker-ce:

[root@localhost app]# yum -y install docker-ce
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirrors.aliyun.com
Resolving Dependencies
--> Running transaction check
---> Package docker-ce.x86_64 3:18.09.6-3.el7 will be installed
--> Processing Dependency: container-selinux >= 2.9 for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Processing Dependency: containerd.io >= 1.2.2-3 for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Processing Dependency: libseccomp >= 2.3 for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Processing Dependency: docker-ce-cli for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Processing Dependency: libsystemd.so.0(LIBSYSTEMD_209)(64bit) for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Processing Dependency: libsystemd.so.0()(64bit) for package: 3:docker-ce-18.09.6-3.el7.x86_64
--> Running transaction check
......

启动 Docker 后台服务

[root@localhost app]# systemctl start docker

如果docker run hello-world因代理问题跑不起来,则设置docker的代理上网

[root@localhost /]# mkdir -p /etc/systemd/system/docker.service.d
[root@localhost /]# vim  /etc/systemd/system/docker.service.d/http-proxy.conf
[Service]
Environment="HTTP_PROXY=http://xxx.xxx.xxx:8080" "HTTPS_PROXY=http://xxx.xxx.xxx:8080" "NO_PROXY=localhost,127.0.0.1"

保存后重启docker容器

[root@localhost /]# systemctl restart docker
[root@localhost /]# systemctl daemon-reload

查看docker代理环境

[root@localhost /]# systemctl show --property=Environment docker

测试hello-world

[root@localhost app]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete 
Digest: sha256:0e11c388b664df8a27a901dce21eb89f11d8292f7fca1b3e3c4321bf7897bffe
Status: Downloaded newer image for hello-world:latest

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.
    (amd64)
 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://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

由于本地没有hello-world这个镜像,所以会下载一个hello-world的镜像,并在容器内运行。

镜像加速

鉴于国内网络问题,后续拉取 Docker 镜像十分缓慢,网易的镜像地址:http://hub-mirror.c.163.com
新版的 Docker 使用 /etc/docker/daemon.json(Linux) 或者 %programdata%\docker\config\daemon.json(Windows) 来配置 Daemon。
请在该配置文件中加入(没有该文件的话,请先建一个):

{
  "registry-mirrors": ["http://hub-mirror.c.163.com"]
}

删除 Docker CE

执行以下命令来删除 Docker CE:

[root@localhost app]# yum remove docker-ce
[root@localhost app]# rm -rf /var/lib/docker

3、docker容器使用

Docker 允许你在容器内运行应用程序, 使用 docker run 命令来在容器内运行一个应用程序。

输出Hello world

[root@localhost app]# docker run ubuntu:15.10 /bin/echo "Hello world"
Unable to find image 'ubuntu:15.10' locally
15.10: Pulling from library/ubuntu
7dcf5a444392: Pull complete 
759aa75f3cee: Pull complete 
3fa871dc8a2b: Pull complete 
224c42ae46e7: Pull complete 
Digest: sha256:02521a2d079595241c6793b2044f02eecf294034f31d6e235ac4b2b54ffc41f3
Status: Downloaded newer image for ubuntu:15.10
Hello world

各个参数解析:

docker: Docker 的二进制执行文件。

run:与前面的 docker 组合来运行一个容器。

ubuntu:15.10指定要运行的镜像,Docker首先从本地主机上查找镜像是否存在,如果不存在,Docker 就会从镜像仓库 Docker Hub 下载公共镜像。

/bin/echo “Hello world”: 在启动的容器里执行的命令

以上命令完整的意思可以解释为:Docker 以 ubuntu15.10 镜像创建一个新容器,然后在容器里执行 bin/echo “Hello world”,然后输出结果。

运行交互式的容器

我们通过docker的两个参数 -i -t,让docker运行的容器实现"对话"的能力

[root@localhost app]# docker run -i -t ubuntu:15.10 /bin/bash
root@565c294c676f:/# 

各个参数解析:

-t:在新容器内指定一个伪终端或终端。

-i:允许你对容器内的标准输入 (STDIN) 进行交互。

此时我们已进入一个 ubuntu15.10系统的容器

我们尝试在容器中运行命令 cat /proc/version和ls分别查看当前系统的版本信息和当前目录下的文件列表

[root@localhost app]# docker run -i -t ubuntu:15.10 /bin/bash
root@bb346149c604:/# cat /etc/os-release 
NAME="Ubuntu"
VERSION="15.10 (Wily Werewolf)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 15.10"
VERSION_ID="15.10"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
root@bb346149c604:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@bb346149c604:/# 

启动容器(后台模式)

使用以下命令创建一个以进程方式运行的容器

[root@localhost app]# docker run -d ubuntu:15.10 /bin/sh -c "while true;do echo hello world;sleep 1;done"
cc66f2c692d8d2fb3a105e5daab8fea285896236d5a2c3ef5d21deb98a6b2c8a

在输出中,我们没有看到期望的"hello world",而是一串长字符

2b1b7a428627c51ab8810d541d759f072b4fc75487eed05812646b8534a2fe63

这个长字符串叫做容器ID,对每个容器来说都是唯一的,我们可以通过容器ID来查看对应的容器发生了什么。

首先,我们需要确认容器有在运行,可以通过 docker ps 来查看

[root@localhost app]# docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES
cc66f2c692d8        ubuntu:15.10        "/bin/sh -c 'while t…"   33 seconds ago      Up 31 seconds                           quirky_babbage

CONTAINER ID:容器ID

NAMES:自动分配的容器名称

在容器内使用docker logs命令,查看容器内的标准输出

[root@localhost app]# docker logs cc66f2c692d8
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
......
[root@localhost app]# docker logs quirky_babbage
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
......

停止容器

我们使用 docker stop 命令来停止容器,通过docker ps查看,容器已经停止工作:

[root@localhost app]# docker stop cc66f2c692d8
cc66f2c692d8
[root@localhost app]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@localhost app]# 

Docker 客户端

可以通过命令 docker command --help 更深入的了解指定的 Docker 命令使用方法。

例如我们要查看 docker stats 指令的具体使用方法:

[root@localhost app]# docker

Usage:	docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -D, --debug              Enable debug mode
  -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:
  builder     Manage builds
  config      Manage Docker configs
  container   Manage containers
  engine      Manage the docker engine
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  secret      Manage Docker secrets

[root@localhost app]# docker stats --help

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

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output
[root@localhost app]# 

4、运行一个web应用

前面我们运行的容器并没有一些什么特别的用处。

接下来让我们尝试使用 docker 构建一个 web 应用程序。

我们将在docker容器中运行一个 Python Flask 应用来运行一个web应用。

[root@localhost app]# docker pull training/webapp
Using default tag: latest
latest: Pulling from training/webapp
e190868d63f8: Pull complete 
909cd34c6fd7: Pull complete 
0b9bfabab7c1: Pull complete 
a3ed95caeb02: Pull complete 
10bbbc0fc0ff: Pull complete 
fca59b508e9f: Pull complete 
e7ae2541b15b: Pull complete 
9dd97ef58ce9: Pull complete 
a4c1b0cb7af7: Pull complete 
Digest: sha256:06e9c1983bd6d5db5fba376ccd63bfa529e8d02f23d5079b8f74a616308fb11d
Status: Downloaded newer image for training/webapp:latest

[root@localhost app]# docker run -d -P training/webapp python app.py
8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214

参数说明:

-d:让容器在后台运行。

-P:将容器内部使用的网络端口映射到我们使用的主机上。

查看 WEB 应用容器

使用 docker ps 来查看我们正在运行的容器:

8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214
[root@localhost app]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS                     NAMES
8dc3381de095        training/webapp     "python app.py"     About a minute ago   Up 57 seconds       0.0.0.0:32768->5000/tcp   friendly_driscoll

这里多了端口信息。

Docker 开放了 5000 端口(默认 Python Flask 端口)映射到主机端口 32769 上。
这时我们可以通过浏览器访问WEB应用
在这里插入图片描述
我们也可以通过 -p 参数来设置不一样的端口:

[root@localhost app]# docker run -d -p 5000:5000 training/webapp python app.py
a5617356c1fb01712c7fb21a87faf4c9e39d4e0897860ce76ac00a2b86259c0b
[root@localhost app]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                     NAMES
a5617356c1fb        training/webapp     "python app.py"     2 minutes ago       Up 2 minutes        0.0.0.0:5000->5000/tcp    gifted_yalow
8dc3381de095        training/webapp     "python app.py"     15 minutes ago      Up 15 minutes       0.0.0.0:32768->5000/tcp   friendly_driscoll

网络端口的快捷方式

通过 docker ps 命令可以查看到容器的端口映射,docker 还提供了另一个快捷方式 docker port,使用 docker port 可以查看指定 (ID 或者名字)容器的某个确定端口映射到宿主机的端口号。

[root@localhost app]# docker port    a5617356c1fb
5000/tcp -> 0.0.0.0:5000
[root@localhost app]# docker port  8dc3381de095
5000/tcp -> 0.0.0.0:32768

查看 WEB 应用程序日志

docker logs [ID或者名字] 可以查看容器内部的标准输出。

[root@localhost app]# docker logs -f a5617356c1fb
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
192.168.163.1 - - [11/Jun/2019 07:52:42] "GET / HTTP/1.1" 200 -
192.168.163.1 - - [11/Jun/2019 07:52:43] "GET /favicon.ico HTTP/1.1" 404 -

查看WEB应用程序容器的进程

我们还可以使用 docker top 来查看容器内部运行的进程

[root@localhost app]# docker top 8dc3381de095
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                63970               63947               0                   00:35               ?                   00:00:00            python app.py

检查 WEB 应用程序

使用 docker inspect 来查看 Docker 的底层信息。它会返回一个 JSON 文件记录着 Docker 容器的配置和状态信息。

[root@localhost app]# docker inspect 8dc3381de095
[
    {
        "Id": "8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214",
        "Created": "2019-06-11T07:35:50.666598845Z",
        "Path": "python",
        "Args": [
            "app.py"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 63970,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-06-11T07:35:55.501456665Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:6fae60ef344644649a39240b94d73b8ba9c67f898ede85cf8e947a887b3e6557",
        "ResolvConfPath": "/var/lib/docker/containers/8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214/hostname",
        "HostsPath": "/var/lib/docker/containers/8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214/hosts",
        "LogPath": "/var/lib/docker/containers/8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214/8dc3381de095642477ceaf0631f1ddd93d511e306ed6638c17a57231f632a214-json.log",
        "Name": "/friendly_driscoll",
        "RestartCount": 0,
        "Driver": "devicemapper",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
         

停止、重启 WEB 应用容器

[root@localhost app]# docker stop 8dc3381de095
[root@localhost app]# docker start 8dc3381de095

docker ps -l 查询最后一次创建的容器:

[root@localhost app]# docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
a5617356c1fb        training/webapp     "python app.py"     24 minutes ago      Up 24 minutes       0.0.0.0:5000->5000/tcp   gifted_yalow

移除WEB应用容器(必须是已停止的容器)

[root@localhost app]# docker rm gifted_yalow
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值