Linux容器篇-Docker容器的使用


前言

Docker 是一个开源的应用容器引擎,基于 Go 语言 并遵从 Apache2.0 协议开源。

Docker 可以让开发者打包他们的应用以及依赖包到一个轻量级、可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。

容器是完全使用沙箱机制,相互之间不会有任何接口,更重要的是容器性能开销极低。


一、Docker的安装

主机环境准备

我在这里介绍centos7及以上操作系统的docker-ce安装。

关闭防火墙

systemctl stop firewalld
systemctl disable firewalld

关闭selinux

将 SELinux 设置为 disabled 模式(相当于将其禁用)
sudo setenforce 0
sudo sed -i 's/^SELINUX=enforcing$/SELINUX=disabled/' /etc/selinux/config

时间同步

yum install chrony -y
systemctl start chronyd
systemctl enable chronyd
chronyc sources

关闭 swap

#临时关闭;关闭swap主要是为了性能考虑
swapoff -a
#可以通过这个命令查看swap是否关闭了
free
#永久关闭
sed -ri 's/.*swap.*/#&/' /etc/fstab

配置操作系统yum源

# CentOS 7 
mkdir /etc/yum.repos.d/repobak
mv /etc/yum.repos.d/* /etc/yum.repos.d/repobak
wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo
yum makecache

配置国内Docker-ce镜像源

这里配置阿里云镜像站的docker-ce镜像源

# step 1: 安装必要的一些系统工具
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: 添加软件源信息
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3
sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
# Step 4: 更新Docker-CE源
sudo yum makecache

注意

# 官方软件源默认启用了最新的软件,您可以通过编辑软件源的方式获取各个版本的软件包。例如官方并没有将测试版本的软件源置为可用,您可以通过以下方式开启。同理可以开启各种测试版本等。
# vim /etc/yum.repos.d/docker-ce.repo
#   将[docker-ce-test]下方的enabled=0修改为enabled=1
#
# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# yum list docker-ce.x86_64 --showduplicates | sort -r
#   Loading mirror speeds from cached hostfile
#   Loaded plugins: branch, fastestmirror, langpacks
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            docker-ce-stable
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            @docker-ce-stable
#   docker-ce.x86_64            17.03.0.ce-1.el7.centos            docker-ce-stable
#   Available Packages
# Step2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.0.ce.1-1.el7.centos)
# sudo yum -y install docker-ce-[VERSION]

二、安装docker-ce

# 安装指定版本的Docker-CE:
# Step 1: 查找Docker-CE的版本:
# yum list docker-ce.x86_64 --showduplicates | sort -r
#   Loading mirror speeds from cached hostfile
#   Loaded plugins: branch, fastestmirror, langpacks
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            docker-ce-stable
#   docker-ce.x86_64            17.03.1.ce-1.el7.centos            @docker-ce-stable
#   docker-ce.x86_64            17.03.0.ce-1.el7.centos            docker-ce-stable
#   Available Packages
# Step2: 安装指定版本的Docker-CE: (VERSION例如上面的17.03.0.ce.1-1.el7.centos)
# sudo yum -y install docker-ce-[VERSION]

设置docker开机自启动

systemctl enable docker --now

三、配置镜像加速器

(阿里云加速器)

针对Docker客户端版本大于 1.10.0 的用户

可以通过修改daemon配置文件/etc/docker/daemon.json来使用加速器

sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://5fid4glg.mirror.aliyuncs.com"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

阿里云镜像加速器生成

该地址为加速器地址
https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors
首先需要注册一个阿里云的账号,然后登陆上面的网址,生成自己的加速器配置。
在这里插入图片描述

四、Docker的使用

Docker 客户端

docker 客户端非常简单 ,我们可以直接输入 docker 命令来查看到 Docker 客户端的所有命令选项。

[root@localhost ~]# docker

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Common Commands:
  run         Create and run a new container from an image
  exec        Execute a command in a running container
  ps          List containers
  build       Build an image from a Dockerfile
  pull        Download an image from a registry
  push        Upload an image to a registry
  images      List images
  login       Log in to a registry
  logout      Log out from a registry
  search      Search Docker Hub for images
  version     Show the Docker version information
  info        Display system-wide information

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx
  checkpoint  Manage checkpoints
  compose*    Docker Compose
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  plugin      Manage plugins
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Swarm Commands:
  config      Manage Swarm configs
  node        Manage Swarm nodes
  secret      Manage Swarm secrets
  service     Manage Swarm services
  stack       Manage Swarm stacks
  swarm       Manage Swarm

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  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
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  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
  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
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  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
  wait        Block until one or more containers stop, then print their exit codes

Global Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket 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

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

For more help on how to use Docker, head to https://docs.docker.com/go/guides/

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

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

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

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

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

Aliases:
  docker container stats, docker stats

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Format output using a custom template:
                        'table':            Print output in table format with column headers (default)
                        'table TEMPLATE':   Print output in table format using the given Go template
                        'json':             Print in JSON format
                        'TEMPLATE':         Print output using the given Go template.
                        Refer to https://docs.docker.com/go/formatting/ for more information about formatting output with templates
      --no-stream       Disable streaming stats and only pull the first result
      --no-trunc        Do not truncate output

获取镜像

如果我们本地没有 ubuntu 镜像,我们可以使用 docker pull 命令来载入 ubuntu 镜像:
$ docker pull ubuntu

[root@localhost ~]# docker pull ubuntu
Using default tag: latest
latest: Pulling from library/ubuntu
7b1a6ab2e44d: Pull complete 
Digest: sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Status: Downloaded newer image for ubuntu:latest
docker.io/library/ubuntu:latest

启动容器

以下命令使用 ubuntu 镜像启动一个容器,参数为以命令行模式进入该容器:
$ docker run -it ubuntu /bin/bash

[root@localhost ~]# docker run -it ubuntu /bin/bash
root@3de025ab0dce:/# 

参数说明:

-i: 交互式操作。
-t: 终端。
ubuntu: ubuntu 镜像。
/bin/bash:放在镜像名后的是命令,这里我们希望有个交互式 Shell,因此用的是 /bin/bash。

要退出终端,直接输入 exit:

root@3de025ab0dce:/# cat /etc/os-release 
NAME="Ubuntu"
VERSION="20.04.3 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.3 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal
root@3de025ab0dce:/# 
root@3de025ab0dce:/# exit
exit
[root@localhost ~]# 

查看所有的容器:

$ docker ps -a

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                          PORTS     NAMES
3de025ab0dce   ubuntu    "/bin/bash"   2 minutes ago   Exited (0) About a minute ago             brave_jang

启动已停止运行的容器

使用 docker start 启动一个已停止的容器:

[root@localhost ~]# docker start 3de025ab0dce
3de025ab0dce

这时候查看容器状态就变成了up

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
3de025ab0dce   ubuntu    "/bin/bash"   4 minutes ago   Up 7 seconds             brave_jang

后台运行

在大部分的场景下,我们希望 docker 的服务是在后台运行的,我们可以过 -d 指定容器的运行模式。

[root@localhost ~]# docker run -itd --name ubuntu-test ubuntu /bin/bash
4e7aabc94c2ed9f60772a4fb4dd1518a97941f7f58540a7fa5cbf6c91c51a53e
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                      PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   4 seconds ago   Up 2 seconds                          ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   7 minutes ago   Exited (0) 22 seconds ago             brave_jang

:加了 -d 参数默认不会进入容器,想要进入容器需要使用指令 docker exec(下面会介绍到)。
停止一个容器
停止容器的命令如下:
$ docker stop <容器 ID或容器指定的名称>

[root@localhost ~]# docker stop ubuntu-test
ubuntu-test
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   2 minutes ago    Exited (0) 2 seconds ago             ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   10 minutes ago   Exited (0) 3 minutes ago             brave_jang

进入容器

在使用 -d 参数时,容器启动后会进入后台。此时想要进入容器,可以通过以下指令进入:

docker attach

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   6 minutes ago    Up 1 second                          ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   13 minutes ago   Exited (0) 6 minutes ago             brave_jang
[root@localhost ~]# docker attach 4e7aabc94c2e
root@4e7aabc94c2e:/# 
root@4e7aabc94c2e:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@4e7aabc94c2e:/# exit
exit
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   6 minutes ago    Exited (0) 1 second ago              ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   13 minutes ago   Exited (0) 7 minutes ago             brave_jang

注意: 如果从这个容器退出,会导致容器的停止。
docker exec:推荐大家使用 docker exec 命令,因为此命令会退出容器终端,但不会导致容器的停止。

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   6 minutes ago    Exited (0) 1 second ago              ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   13 minutes ago   Exited (0) 7 minutes ago             brave_jang
[root@localhost ~]# docker start 4e7aabc94c2e
4e7aabc94c2e
[root@localhost ~]# docker exec -it 4e7aabc94c2e /bin/bash
root@4e7aabc94c2e:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@4e7aabc94c2e:/# exit
exit
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   8 minutes ago    Up 26 seconds                        ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   15 minutes ago   Exited (0) 8 minutes ago             brave_jang

导出容器

如果要导出本地某个容器,可以使用 docker export 命令。

[root@localhost ~]# docker export 4e7aabc94c2e > ubuntu.tar
[root@localhost ~]# ls
ubuntu.tar

导入容器快照

可以使用 docker import 从容器快照文件中再导入为镜像,以下实例将快照文件 ubuntu.tar 导入到镜像 test/ubuntu:v1:

[root@localhost ~]# docker import ubuntu.tar test/ubuntu:v1
sha256:f67ec2cf190888fc605c17d84dce9019feb48a3a61b97e47d9d99f9c09e1d218
[root@localhost ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED          SIZE
test/ubuntu   v1        f67ec2cf1908   24 seconds ago   72.8MB
ubuntu        latest    ba6acccedd29   2 years ago      72.8MB

此外,也可以通过指定 URL 或者某个目录来导入,例如:

$ docker import http://example.com/exampleimage.tgz example/imagerepo

删除容器

删除容器使用 docker rm 命令:

[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   18 minutes ago   Exited (0) 5 minutes ago              ubuntu-test
3de025ab0dce   ubuntu    "/bin/bash"   26 minutes ago   Exited (0) 19 minutes ago             brave_jang
[root@localhost ~]# docker rm 3de025ab0dce
3de025ab0dce
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4e7aabc94c2e   ubuntu    "/bin/bash"   19 minutes ago   Exited (0) 6 minutes ago             ubuntu-test

注意:删除容器时,容器必须是停止状态,否则会报如错
下面的命令可以清理掉所有处于终止状态的容器。

$ docker container prune

查看网络端口

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

$ docker port ID 或者名字
5000/tcp -> 0.0.0.0:5000

查看应用程序日志

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

$ docker logs -f bf08b7f2cd89
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
192.168.239.1 - - [09/May/2016 16:30:37] "GET / HTTP/1.1" 200 -
192.168.239.1 - - [09/May/2016 16:30:37] "GET /favicon.ico HTTP/1.1" 404 -

-f: 让 docker logs 像使用 tail -f 一样来输出容器内部的标准输出。
从上面,我们可以看到应用程序使用的是 5000 端口并且能够查看到应用程序的访问日志。

查看应用程序容器的进程

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

$ docker top bf08b7f2cd89
UID     PID         PPID          ...       TIME                CMD
root    23245       23228         ...       00:00:00            python app.py

检查应用程序

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

$ docker inspect bf08b7f2cd89
[
    {
        "Id": "bf08b7f2cd897b5964943134aa6d373e355c286db9b9885b1f60b6e8f82b2b85",
        "Created": "2018-09-17T01:41:26.174228707Z",
        "Path": "python",
        "Args": [
            "app.py"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 23245,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-09-17T01:41:26.494185806Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
......

总结

随手分享,没什么技术含量,希望可以给入坑容器的小伙伴们提供一些帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秣宇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值