当前位置:首页 » 《休闲阅读》 » 正文

如何在 Ubuntu 20.04 上安装和使用 Docker

2 人参与  2024年04月18日 14:38  分类 : 《休闲阅读》  评论

点击全文阅读


前些天发现了一个人工智能学习网站,通俗易懂,风趣幽默,最重要的屌图甚多,忍不住分享一下给大家。点击跳转到网站。

如何在 Ubuntu 20.04 上安装和使用 Docker

介绍

Docker是一个可以简化容器中应用程序进程管理过程的应用程序。容器允许你在资源隔离的进程中运行应用程序。它们与虚拟机类似,但容器更可移植,更资源友好,并且更依赖于主机操作系统。

下来将在 Ubuntu 20.04 上安装和使用 Docker Community Edition (CE)。将安装 Docker 本身,使用容器和镜像,并将镜像推送到 Docker 存储库。

笔记

本文将引导完成在 Ubuntu 服务器上安装 Docker。如果想要一键式方式将 Docker 应用程序部署到实时服务器,请等下一期~

先决条件

需要以下内容:

按照 Ubuntu 20.04初始服务器设置指南设置一台 Ubuntu 20.04 服务器,包括 sudo 非 root 用户和防火墙。

第 1 步 — 安装 Docker

Ubuntu 官方存储库中提供的 Docker 安装包可能不是最新版本。为了确保我们获得最新版本,我们将从官方 Docker 存储库安装 Docker。为此,我们将添加一个新的包源,添加来自 Docker 的 GPG 密钥以确保下载有效,然后安装该包。

首先,更新现有的软件包列表:

sudo apt update

接下来,安装一些必备包,以便apt通过 HTTPS 使用包:

sudo apt install apt-transport-https ca-certificates curl software-properties-common

然后将官方 Docker 存储库的 GPG 密钥添加到你的系统中:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

将 Docker 存储库添加到 APT 源:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable"

这还将使用新添加的存储库中的 Docker 包更新我们的包数据库。

确保要从 Docker 存储库而不是默认的 Ubuntu 存储库进行安装:

apt-cache policy docker-ce

尽管 Docker 的版本号可能不同,但将看到如下输出:

apt-cache 策略 docker-ce 的输出

docker-ce:  Installed: (none)  Candidate: 5:19.03.9~3-0~ubuntu-focal  Version table:     5:19.03.9~3-0~ubuntu-focal 500        500 https://download.docker.com/linux/ubuntu focal/stable amd64 Packages

请注意,docker-ce尚未安装,但安装候选来自 Ubuntu 20.04 的 Docker 存储库 ( focal)。

最后,安装 Docker:

sudo apt install docker-ce

Docker 现在应该已安装,守护进程已启动,并且该进程可以在启动时启动。检查它是否正在运行:

sudo systemctl status docker

输出应类似于以下内容,表明服务处于活动状态并正在运行:

Output● docker.service - Docker Application Container Engine     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)     Active: active (running) since Tue 2020-05-19 17:00:41 UTC; 17s agoTriggeredBy: ● docker.socket       Docs: https://docs.docker.com   Main PID: 24321 (dockerd)      Tasks: 8     Memory: 46.4M     CGroup: /system.slice/docker.service             └─24321 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

现在安装 Docker 不仅提供 Docker 服务(守护进程),还提供docker命令行实用程序或 Docker 客户端。我们将在本教程后面探讨如何使用该docker命令。

第 2 步 — 不使用 Sudo 执行 Docker 命令(可选)

默认情况下,该命令只能由root用户或****docker组中的用户docker运行,该组是在 Docker 安装过程中自动创建的。如果尝试运行该命令而不添加前缀(无论是否在docker组中),将得到如下输出:docker``sudo

Outputdocker: Cannot connect to the Docker daemon. Is the docker daemon running on this host?.See 'docker run --help'.

如果想避免sudo在运行docker命令时输入内容,请将你的用户名添加到docker组中:

sudo usermod -aG docker ${USER}

要应用新的组成员身份,请注销服务器并重新登录,或输入以下内容:

su - ${USER}

系统将提示输入用户密码以继续。

通过输入以下内容确认用户现已添加到docker组:

groups
Outputsammy sudo docker

如果需要将用户添加到你未登录的组中,请使用以下方式显式声明该用户名:

sudo usermod -aG docker username

本文的其余部分假设你以dockerdocker组中的用户身份运行该命令。如果你选择没有,请在命令前面加上sudo`

第 3 步 — 使用 Docker 命令

使用docker包括向其传递一系列选项和命令,后跟参数。语法采用以下形式:

docker [option] [command] [arguments]

要查看所有可用的子命令,请输入:

docker

从 Docker 19 开始,可用子命令的完整列表包括:

Output  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-subcommand --help

要查看有关 Docker 的系统范围信息,请使用:

docker info

第 4 步 — 使用 Docker 镜像

Docker 容器是从 Docker 镜像构建的。默认情况下,Docker 从Docker Hub中提取这些镜像,Docker Hub 是由 Docker 项目背后的公司 Docker 管理的 Docker 注册表。任何人都可以在 Docker Hub 上托管其 Docker 镜像,因此需要的大多数应用程序和 Linux 发行版都会在那里托管镜像。

要检查是否可以从 Docker Hub 访问和下载镜像,请输入:

docker run hello-world

输出将表明 Docker 工作正常:

OutputUnable to find image 'hello-world:latest' locallylatest: Pulling from library/hello-world0e03bdcc26d7: Pull completeDigest: sha256:6a65f928fb91fcfbc963f7aa6d57c8eeb426ad9a20c7ee045538ef34847f44f1Status: Downloaded newer image for hello-world:latestHello from Docker!This message shows that your installation appears to be working correctly....

Docker 最初无法在本地找到该hello-world镜像,因此它从 Docker Hub(默认存储库)下载了该镜像。下载镜像后,Docker 从镜像创建一个容器,并执行容器内的应用程序并显示消息。

可以使用带有子命令docker的命令search来搜索 Docker Hub 上可用的镜像。例如,要搜索 Ubuntu 镜像,输入:

docker search ubuntu

该脚本将抓取 Docker Hub 并返回名称与搜索字符串匹配的所有镜像的列表。在这种情况下,输出将类似于以下内容:

OutputNAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATEDubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   10908               [OK]dorowu/ubuntu-desktop-lxde-vnc                            Docker image to provide HTML5 VNC interface …   428                                     [OK]rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   244                                     [OK]consol/ubuntu-xfce-vnc                                    Ubuntu container with "headless" VNC session…   218                                     [OK]ubuntu-upstart                                            Upstart is an event-based replacement for th…   108                 [OK]ansible/ubuntu14.04-ansible                               Ubuntu 14.04 LTS with...

确定要使用的镜像后,可以使用pull子命令将其下载到计算机。

执行以下命令将官方ubuntu镜像下载到计算机上:

docker pull ubuntu

将看到以下输出:

OutputUsing default tag: latestlatest: Pulling from library/ubuntud51af753c3d3: Pull completefc878cd0a91c: Pull complete6154df8ff988: Pull completefee5db0ff82f: Pull completeDigest: sha256:747d2dbbaaee995098c9792d99bd333c6783ce56150d1b11e333bbceed5c54d7Status: Downloaded newer image for ubuntu:latestdocker.io/library/ubuntu:latest

下载镜像后,可以通过run子命令使用下载的镜像运行容器。如上所示,如果使用子命令执行hello-world时尚未下载镜像,则 Docker 客户端将首先下载镜像,然后运行容器。

要查看已下载到计算机的镜像,请输入:

docker images

输出将类似于以下内容:

OutputREPOSITORY          TAG                 IMAGE ID            CREATED             SIZEubuntu              latest              1d622ef86b13        3 weeks ago         73.9MBhello-world         latest              bf756fb1ae65        4 months ago        13.3kB

用于运行容器的镜像可以被修改并用于生成新镜像,然后可以将其上传(技术术语*“推送”)到 Docker Hub 或其他 Docker 注册表。*

第 5 步 — 运行 Docker 容器

上一步中运行的hello-world容器是在发出测试消息后运行并退出的容器示例。

作为示例,我们可以使用最新的 Ubuntu 镜像运行一个容器:

docker run -it ubuntu

命令提示符应更改以反映你现在正在容器内工作的事实,并且应采用以下形式:

Outputroot@d9b100f2f636:/#

本文命令提示符中的容器 ID 是d9b100f2f636。之后想要删除容器时,将需要D 来识别该容器。

我们可以在容器内运行任何命令。例如,更新容器内的包数据库:

apt update

接着在其中安装任何应用程序。比如安装 Node.js:

apt install nodejs

这个将从官方 Ubuntu 存储库将 Node.js 安装到容器中。安装完成后,验证 Node.js 是否已安装:

node -v

将看到终端中显示的版本号:

Outputv10.19.0

在容器内所做的任何更改仅适用于该容器。

要退出容器,输入exit即可。

第 6 步 — 管理 Docker 容器

使用 Docker 一段时间后,计算机上将有许多活动(正在运行)和非活动容器。要查看活动的,请使用:

docker ps

将看到类似于以下内容的输出:

OutputCONTAINER ID        IMAGE               COMMAND             CREATED

在本教程中,启动了两个容器;一个来自hello-world镜像,另一个来自ubuntu镜像。两个容器都不再运行,但它们仍然存在于你的系统上。

要查看所有容器(活动和非活动),请使用docker ps -a

docker ps -a

将看到与此类似的输出:

1c08a7a0d0e4        ubuntu              "/bin/bash"         2 minutes ago       Exited (0) 8 seconds ago                       quizzical_mcnultya707221a5f6c        hello-world         "/hello"            6 minutes ago       Exited (0) 6 minutes ago                       youthful_curie

要查看创建的最新容器:

docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES1c08a7a0d0e4        ubuntu              "/bin/bash"         2 minutes ago       Exited (0) 40 seconds ago                       quizzical_mcnulty

要启动已停止的容器,使用docker start,后跟容器 ID 或容器名称:

docker start 1c08a7a0d0e4

容器将启动,可以使用以下docker ps命令查看其状态:

OutputCONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES1c08a7a0d0e4        ubuntu              "/bin/bash"         3 minutes ago       Up 5 seconds                            quizzical_mcnulty

要停止正在运行的容器,使用docker stop,后跟容器 ID 或名称。

docker stop quizzical_mcnulty

一旦决定不再需要容器,使用删除命令docker rm,再次使用容器 ID 或名称。

docker rm youthful_curie

第 7 步 — 将容器中的更改提交到 Docker 镜像

启动 Docker 镜像时,可以像使用虚拟机一样创建、修改和删除文件。我们所做的更改将仅应用于该容器。我们可以启动和停止它,但是一旦使用docker rm命令之前所作的更改将永远丢失。

下来说明如何将容器的状态保存为新的 Docker 镜像。

在 Ubuntu 容器中安装 Node.js 后,我们现在拥有一个运行镜像的容器,但该容器与你用于创建它的镜像不同。但你可能希望稍后重用此 Node.js 容器作为新镜像的基础。

然后使用以下命令将更改提交到新的 Docker 镜像实例。

docker commit -m "What you did to the image" -a "Author Name" container_id repository/new_image_name

-m用于提交消息,帮助你和其他人了解你所做的更改,-a用于指定作者。container_id是在本教程前面启动交互式 Docker 会话时注意到的那个。除非你在 Docker Hub 上创建了其他存储库,否则repository通常是你的 Docker Hub 用户名。

例如,对于用户sammy,容器 ID 为d9b100f2f636,命令将为:

docker commit -m "added Node.js" -a "sammy" d9b100f2f636 sammy/ubuntu-nodejs

当你提交镜像时,新镜像将保存在你的计算机本地。

再次列出 Docker 镜像将显示新镜像及其派生自的旧镜像:

docker images

将看到如下输出:

OutputREPOSITORY               TAG                 IMAGE ID            CREATED             SIZEsammy/ubuntu-nodejs   latest              7c1f35226ca6        7 seconds ago       179MB...

在此示例中,ubuntu-nodejs是新镜像,它源自ubuntuDocker Hub 的现有镜像。大小差异反映了所做的更改。在这个例子中,唯一的变化是安装了 NodeJS。因此,下次你需要使用预装 NodeJS 的 Ubuntu 来运行容器时,你可以只使用新镜像。

还可以从 Dockerfile构建镜像,这使你可以在新镜像中自动安装软件。(本章不做解释说明)

第 8 步 — 将 Docker 镜像推送到 Docker 存储库

要将镜像推送到 Docker Hub 或任何其他 Docker 注册表,你必须有一个帐户。

要推送你的镜像,请首先登录 Docker Hub。

docker login -u docker-registry-username

系统将提示你使用 Docker Hub 密码进行身份验证。如果你指定了正确的密码,身份验证应该会成功。

**注意:**如果你的 Docker 注册表用户名与用于创建镜像的本地用户名不同,则必须使用你的注册表用户名来标记你的镜像。对于最后一步中给出的示例,你可以输入:

docker tag sammy/ubuntu-nodejs docker-registry-username/ubuntu-nodejs

然后可以使用以下方式推送你自己的镜像:

docker push docker-registry-username/docker-image-name

要将镜像推ubuntu-nodejs送到sammy存储库,命令为:

docker push sammy/ubuntu-nodejs

该过程在上传镜像时可能需要一些时间才能完成,但完成后,输出将如下所示:

OutputThe push refers to a repository [docker.io/sammy/ubuntu-nodejs]e3fbbfb44187: Pushed5f70bf18a086: Pusheda3b5c80a4eba: Pushed7f18b442972b: Pushed3ce512daaf78: Pushed7aae4540b42d: Pushed...

将镜像推送到注册表后,它应该会列在你帐户的仪表板上,如下图所示。

Docker Hub 上列出了新的 Docker 镜像

如果未登录,则推送尝试导致此类错误:

OutputThe push refers to a repository [docker.io/sammy/ubuntu-nodejs]e3fbbfb44187: Preparing5f70bf18a086: Preparinga3b5c80a4eba: Preparing7f18b442972b: Preparing3ce512daaf78: Preparing7aae4540b42d: Waitingunauthorized: authentication required

登录docker login并重复推送尝试。然后验证它是否存在于你的 Docker Hub 存储库页面上。


点击全文阅读


本文链接:http://zhangshiyu.com/post/97121.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1