如何在 Centos 7 中安装和使用 Docker
前言
Docker 是一个开源的应用容器引擎。Docker 可以让开发者打包他们创建的应用以及相应的依赖包到一个可移植、轻量级的容器中。Docker 可大大简化在容器中管理应用程序的过程。容器使用沙盒机制,运行在其中的应用与主系统相互分离,类似与虚拟机。但容器比虚拟机有更棒的可移植性、占用计算机资源更小。
有关 Docker 容器的不同组件的详细介绍,请看这篇《 Docker 生态系统:通用组件》(正在撰写中,稍后上线)。
有两种方法可以在 CentOS 7 上安装 Docker。一种方法是将其安装在现有的操作系统安装上。另一个是 Docker Machine 来安装。
在本教程中,我们学习如何在 CentOS 7 中安装和使用 Docker 。
准备工作
要根据本教程学习,首先要准备好以下几点。
- 安装好 CentOS 7 的服务器
- 有 sudo 的 root 用户权限,大家可根据《 CentOS 7 初始服务器设置》(撰写中,稍后上线)指南来配置自己的服务器。
提示:Docker 需要CentOS 7 的 64 位版本以及高于 3.10 的内核版本。默认的 64 位 CentOS 7 Droplet 满足这些要求。
第1步:安装 Docker
官方 CentOS 7 存储库中可用的Docker 安装软件包可能不是最新版本。要获得最新和最好的版本,请从官方Docker存储库安装Docker。本节向您展示如何做到这一点。
但首先,让我们更新软件包数据库:
sudo yum check-update
现在运行此命令。它将添加官方Docker存储库,下载最新版本的Docker并进行安装:
curl -fsSL https://get.docker.com/ | sh
安装完成后,启动Docker守护程序:
sudo systemctl start docker
让我们来确认一下 Docker 的运行状态:
sudo systemctl status docker
我们可以看到输出结果类似以下内容。说明 Docker 已经在激活并运行的状态了。
● docker.service - Docker Application Container Engine
Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2020-07-24 06:53:52 CST; 59s ago
Docs: https://docs.docker.com
Main PID: 749 (docker)
最后,让每次重启服务器时,Docker 都能自动启动。
sudo systemctl enable docker
输出结果类似以下内容:
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
好了,我们现在我们已经完成 docker
的安装,并且在系统中启动了守护进程。
接下来,我们来学习docker
的具体命令。
第 2 步:在不使用 sudo 的情况下执行 Docker 命令
(此步不影响 Docker 使用,可选择跳过)
默认情况下,docker
命令只能由 root 用户或由 docker 组中的用户运行,docker 组用户是在Docker安装过程中自动创建的。
如果你在执行docker
命令时,没有用 sudo ,并且使用的用户也不是 docker 组成员,那么结果会显示:
Output
docker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.
See 'docker run --help'.
如果要避免sudo
在运行docker
命令时键入任何内容,请将用户名添加到docker
组中:
如果不想用 sudo 来执行 docker 命令,那么我们只需要把对应的用户添加到 docker 组中即可。
sudo usermod -aG docker $(whoami)
使用新组成员身份执行命令,需要注销后重新登录。
如果你需要添加一个用户到docker
组,而你又不是以该用户的身份登录的,可使用此命令来添加:
sudo usermod -aG docker username
本教程接下来会假定大家使用的用户已经在 docker 组中,并使用此用户执行docker
命令。如果你没有添加正在使用的用户到 docker 组中,那么请在执行命令前加上sudo
好了,到这里我们已经万事俱备。让我们开始探索docker
的使用方法吧
第3步—如何使用 Docker 命令
我们可以向docker
命令传送一系列选项、参数等。
语法格式如下:
docker [option] [command] [arguments]
要查看所有可用的子命令,请键入:
docker
输入docker
会输出完整的命令列表:
[kalasearch@localhost ~]$ docker
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default
"/home/chuan/.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(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
"/home/chuan/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default
"/home/chuan/.docker/cert.pem")
--tlskey string Path to TLS key file (default
"/home/chuan/.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
context Manage contexts
engine Manage the docker engine
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
trust Manage trust on Docker images
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
deploy Deploy a new stack or update an existing stack
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
Run 'docker COMMAND --help' for more information on a command.
[chuan@localhost ~]$ docker
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Options:
--config string Location of client config files (default
"/home/chuan/.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(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
"/home/chuan/.docker/ca.pem")
--tlscert string Path to TLS certificate file (default
"/home/chuan/.docker/cert.pem")
--tlskey string Path to TLS key file (default
"/home/chuan/.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
context Manage contexts
engine Manage the docker engine
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
trust Manage trust on Docker images
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
deploy Deploy a new stack or update an existing stack
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
Run 'docker COMMAND --help' for more information on a command.
要查看特定命令可用的选项,请键入:
docker ${docker-subcommand} --help
要查看有关 Docker 的系统信息,请使用:
docker info
棒,到这里你已经学会了 docker 的基本运行命令,接下来,让我们来看看 docker 最重要的功能,如何使用镜像。
第4步:如何在 Docker 中使用镜像
Docker 容器(containers)是从 Docker 镜像生成出来的。默认情况下,Docker 从Docker Hub下载这些镜像,Docker 公司在运营这个Docker Hub。
任何人都可以在 Docker Hub 上托管自己的 Docker 镜像。因此,我们大多数需要的应用程序和 Linux 发行版都能在这里找到。
要检查是否可以访问 Docker Hub 和从这个网站下载镜像,请输入:
docker run hello-world
如果你得到以下结果,说明你的机器访问 Docker hub 一切顺畅:
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/
执行此命令时,Docker 首先在本地查找hello-world
,如没有,它会从 Docker Hub(默认版本库)下载了该镜像。下载镜像后,Docker 会根据镜像创建一个容器,并执行该容器中的应用程序。
您可以通过将docker
命令与search
子命令配合使用来搜索 Docker Hub 上可用的镜像。
例如,要搜索 centos
的镜像,请输入:
docker search centos
此命令会在 Docker Hub 上搜索并返回名称与搜索字符串匹配的所有镜像列表。
执行后显示的结果如下:
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 6101 [OK]
ansible/centos7-ansible Ansible on Centos7 132 [OK]
consol/centos-xfce-vnc Centos container with "headless" VNC session… 117 [OK]
jdeathe/centos-ssh OpenSSH / Supervisor / EPEL/IUS/SCL Repos - … 115 [OK]
centos/systemd systemd enabled base container. 86 [OK]
centos/mysql-57-centos7 MySQL 5.7 SQL database server 78
imagine10255/centos6-lnmp-php56 centos6-lnmp-php56 58 [OK]
tutum/centos Simple CentOS docker image with SSH access 47
centos/postgresql-96-centos7 PostgreSQL is an advanced Object-Relational … 46
kinogmt/centos-ssh CentOS with SSH 29 [OK]
pivotaldata/centos-gpdb-dev CentOS image for GPDB development. Tag names… 12
guyton/centos6 From official centos6 container with full up… 10 [OK]
drecom/centos-ruby centos ruby 6 [OK]
centos/tools Docker image that has systems administration… 6 [OK]
pivotaldata/centos Base centos, freshened up a little with a Do… 4
pivotaldata/centos-gcc-toolchain CentOS with a toolchain, but unaffiliated wi… 3
pivotaldata/centos-mingw Using the mingw toolchain to cross-compile t… 3
darksheer/centos Base Centos Image -- Updated hourly 3 [OK]
mamohr/centos-java Oracle Java 8 Docker image based on Centos 7 3 [OK]
...
“ OFFICIAL” 列(即官方)对应的镜像,就是出自官方的镜像了,大家可放心使用。
接下来,我们可以用pull
子命令,将你需要的镜像下载到计算机。
本教程我们使用centos
的官方镜像。
docker pull centos
镜像下载完成后,我们可以使用run
命令把刚下载的镜像运行起来变成容器。
docker run centos
使用run
来执行本地不存在的centos
镜像时, docker
发现本地没有这个镜像,会直接在 Docker hub 上查找并下载对应的镜像。
要查看已下载到计算机的镜像:
docker images
输出结果如下:
kalasearch@localhost ~]$ sudo docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos latest 831691599b88 5 weeks ago 215MB
hello-world latest bf756fb1ae65 6 months ago 13.3kB
第5步:运行 Docker 容器
在上一步的例子中,我们执行了hello-world
并学习了如何查看镜像和容器。但其实容器并不仅仅是这样,它可比这有用的多。接下来我们来看看容器能做些什么。
作为示例,让我们用 centos 最新镜像来运行。使用-i -t 这两个参数,可以让你通过 shell 来方面他们。
docker run -it centos
执行命令后,提示符会变为你正在使用镜像的容器id:
[root@45021efbd889 /]#
注意:这个容器ID,在此例中,为45021efbd889
。我们可以使用这个ID来识别和删除这个容器。
现在,我们可以在容器内执行任何命令了。例如,让我们来安装MariaDB server。
我们在容器内是以 root 用户身份进行操作的,所有不需要使用sudo
yum install mariadb-server
第6步-管理 Docker 容器
在使用 Docker 一段时间后,我们的计算机上会有许多活动(运行)和非活动容器。
要查看这些活动中的容器对象,请使用:
docker ps
输出内容如下:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
在本教程中,我们启动了两个容器。一个是hello-world
镜像,另一个是centos镜像。这两个容器目前都没有在运行,但是它们仍然保存在计算机里。
要查看所有容器(活动和非活动),请docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45021efbd889 centos "/bin/bash" 3 hours ago Exited (130) 3 hours ago practical_goldstine
5d03da8fcd53 hello-world "/hello" 3 hours ago Exited (0) 3 hours ago vigorous_lamarr
要查看最后创建的容器,可使用:
docker ps -l
输出结果如下:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45021efbd889 centos "/bin/bash" 3 hours ago Exited (130) 3 hours ago practical_goldstine
要启动已停止的容器,请使用docker start
命令+容器ID或容器名。
我们来启动刚刚关掉的容器45021efbd889
docker start 45021efbd889
容器启动,我们可以docker ps
用来查看其状态:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45021efbd889 centos "/bin/bash" 4 hours ago Up 24 seconds practical_goldstine
要停止正在运行的容器,请使用docker stop
命令+容器 ID 或容器名。这次,我们将使用 Docker 分配的容器名称,即practical_goldstine
:
docker stop practical_goldstine
当某些容器我们不会再使用,我们可以通过容器 ID 或名称来轻松删除它们。我们可以通过docker rm
命令来删除不用的容器。
docker rm practical_goldstine
使用docker ps -a
命令查找与hello-world
镜像关联的容器的容器ID或名称,然后将其删除。
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
45021efbd889 centos "/bin/bash" 4 hours ago Up 8 minutes practical_goldstine
5d03da8fcd53 hello-world "/hello" 5 hours ago Exited (0) 5 hours ago vigorous_lamarr
根据这个列表,可以看到我们这台机器上hello-world
容器名称为vigorous_lamarr
docker rm vigorous_lamarr
我们可以启动一个新容器,并使用--name
为其命名。还可以使用--rm
创建一个容器并让这个容器在结束时自动删除。
等多命令和参数可用docker run help
来查看。
我们添加了各种软件的容器,还可以转换为镜像,我们可以用它们创建建新的容器。让我们看看它是如何工作的。
第7步:将容器中的更改提交给 Docker Hub
启动 Docker 镜像时,可以像使用虚拟机一样创建,修改和删除文件。我们所做的更改将仅应用于在这个容器里。我们可以启动和关闭这个容器,用docker rm
命令来删除不用的容器。
接下来,我们来谈谈当我们在容器中安装好各种软件,我们想把它保存成一个新镜像时,我们应该怎么做。
刚刚我们在 CentOS 的容器中安装 mariaDB server,此时,这个容器里的内容已经不同于生成它的镜像。如果以后我们想直接打开镜像就预装 mariaDB 的话,我们可以把这个容器生成为新的镜像。
首先,我们先退出容器。
exit
然后用以下命令将更改提交到 Docker hub。
docker commit -m "What did you do to the image" -a "Author Name" container-id repository/new_image_name
参数 -m 是提交镜像的备注,让我们知道此镜像有哪些不同之处。参数 -a 用于指定作者名。
这除非你在 Docker Hub 上创建了其他repository
,一般来说container_id
是 Docker Hub 上你的用户名。
例如:
我们在 Docker 上的用户名是 kalasearch ,我们将刚刚创建的容器45021efbd889
上传至Docker Hub。
具体到我们教程的实例,我们这么写:
docker commit -m "added mariadb-server" -a "kalasearch" 45021efbd889 centos-mariadb
当我们提交新镜像时,新生成的镜像也会在我们的计算机上本地保存。在本教程的后面,我们可以学到如何将镜像推送到 Docker Hub,以便其他人可以访问它。
我们用 docker images
命令查看本地镜像:
docker images
输出如下,可以发现刚刚的新镜像已经在其中了:
[kalasearch@localhost ~]$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
centos-mariadb latest bff2ede0f077 40 seconds ago 215MB
centos latest 831691599b88 5 weeks ago 215MB
在此例中,centos-mariadb 是新镜像,它是我们从 Docker hub 下载的官方 CentOS 镜像派生的。它们的镜像大小差异,反映了所做的更改。在此例中,我们安装了 mariaDB server 。因此,下次我们需要使用已预安装 mariaDB server 的 CentOS 运行容器时,就可以直接使用新镜像。现在,现在我们可以把我们创建的新镜像共享给需要的人啦,下面我们谈谈如何共享创建的镜像。
步骤8 :将 Docker 镜像推送到Docker hub
从现有镜像里创建新镜像后,下一步是与我们的朋友共享。我们可以在 Docker Hub 上来共享我们的镜像。要将我们的镜像推送到 Docker Hub,我们必须要有docker帐户。
本节介绍如何将 Docker 镜像推送到 Docker Hub。
要推送镜像,请首先登录 Docker Hub。
docker login -u ${docker-registry-username}
输入账号对应的密码后,即可登录成功。
Login Succeeded
注意:如果你在 Docker 注册用户名与用于创建镜像的本地用户名不同,要在备注中记录 Docker 用户名:
docker centos-mariadb kalasearch/centos-mariadb
然后,我们就可以推送镜像到 Docker hub 上了,命令如下:
docker push docker-registry-username/docker-image-name
如果我们要把centos-mariadb
镜像推送到kalasearch
的版本库,命令如下:
docker push kalasearch/centos-mariadb
[kalasearch@localhost ~]$ docker push kalasearch/centos-mariadb
The push refers to repository [docker.io/kalasearch/centos-mariadb]
eb29745b8228: Mounted from library/centos
latest: digest: sha256:a9c577403dfc56a6c2f6f4e584200fb09da1a76a72ff04469a91dfaf5ceca49a size: 529
登录docker login
并重新提交。然后就能在 Docker Hub 上看到你到镜像啦。
现在,我们可以docker pull kalasearch/centos-mariadb
命令在任意一台机器上使用我们自己创建的镜像啦。
总结
本教程中,我们学会了如何安装 Docker,在 Docker 中使用镜像和容器,并将修改后的镜像推送到 Docker Hub。
我们已经掌握了 Docker 的入门基础知识,如果想深入学习 Docker 可在 kalasearch 程序员社区中找到更多 Docker 教程。