如何在Ubuntu上安装使用Docker

介绍

Docker 最初是 dotCloud 公司创始人 Solomon Hykes 在法国期间发起的一个公司内部项目,它是基于 dotCloud 公司多年云服务技术的一次革新,并于 2013 年 3 月以 Apache 2.0 授权协议开源,主要项目代码在 GitHub 上进行维护。Docker 项目后来还加入了 Linux 基金会,并成立推动 开放容器联盟(OCI)。 容器允许您在资源隔离的进程中运行应用程序。它们与虚拟机类似,但容器更便携,更有利于资源,并且更依赖于主机操作系统。

在本教程中,您将安装Docker,并学会使用容器和镜像,将镜像推送到Docker存储库。

准备

要学习本教程,您需要具备以下条件:

一个按照Ubuntu初始服务器,我们建议您使用腾讯云免费开发者实验室进行试验,或点击这里购买服务器。

如果您希望创建自己的镜像并将其推送到Docker Hub,则需要创建Docker Hub上的帐户。

第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 bionic stable"

接下来,使用新添加的repo源中的Docker包更新包数据库:

sudo apt update

确保您要从Docker repo安装而不是默认的Ubuntu repo:

apt-cache policy docker-ce

虽然Docker的版本号可能不同,但您还是会看到这样的输出:

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

现在docker-ce还没有安装,用上面这个命令我们能看到安装源来自的Docker官方存储库。

最后,安装Docker:

sudo apt install docker-ce

现在应该安装好Docker了,检查它是否正在运行:

sudo systemctl status docker

输出应类似于以下内容,表明该服务处于工作状态:

● docker.service - Docker Application Container Engine
   Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2018-07-05 15:08:39 UTC; 2min 55s ago
     Docs: https://docs.docker.com
 Main PID: 10096 (dockerd)
    Tasks: 16
   CGroup: /system.slice/docker.service
           ├─10096 /usr/bin/dockerd -H fd://
           └─10113 docker-containerd --config /var/run/docker/containerd/containerd.toml

Docker不仅可以为您提供Docker服务,还可以为您提供docker命令行工具或Docker客户端。我们将在本教程后面探讨如何使用docker命令。

第2步 - 在不输入Sudo情况下执行Docker(可选)

默认情况下,该docker命令只能由root用户或docker组中的用户运行,该用户在Docker的安装过程中自动创建。如果您尝试运行该docker命令而不使用sudo或不在docker组中中用户运行,您将看到如下输出:

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

要想在在运行docker命令时不输入sudo,请将用户名添加到docker组中:

sudo usermod -aG docker ${USER}

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

su - ${USER}

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

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

id -nG
sammy sudo docker

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

sudo usermod -aG docker username

本文的其余部分假定您以docker组中的用户身份运行该docker命令。如果您不是这样做,请在前面添加sudo命令。

第3步 - 使用Docker命令

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

docker [option] [command] [arguments]

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

docker

可用子命令的完整列表包括:

  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管理的Docker镜像市场,这是Docker项目背后的公司。任何人都可以在Docker Hub上托管他们的Docker镜像,所以您只需要将您的应用程序和Linux放在那边托管即可。

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

docker run hello-world

输出下面的内容则Docker正常工作:

Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
9bb5a5d4561a: Pull complete
Digest: sha256:3e1764d0f546ceac4565547df2ac4907fe46f007ea229fd7ef2718514bcec35d
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.
...

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

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

docker search ubuntu

该脚本将对Docker Hub进行抓取,并返回名称与搜索字符串匹配的所有镜像的列表。输出将类似于:

NAME                                                      DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
ubuntu                                                    Ubuntu is a Debian-based Linux operating sys…   7917                [OK]
dorowu/ubuntu-desktop-lxde-vnc                            Ubuntu with openssh-server and NoVNC            193                                     [OK]
rastasheep/ubuntu-sshd                                    Dockerized SSH service, built on top of offi…   156                                     [OK]
ansible/ubuntu14.04-ansible                               Ubuntu 14.04 LTS with ansible                   93                                      [OK]
ubuntu-upstart                                            Upstart is an event-based replacement for th…   87                  [OK]
neurodebian                                               NeuroDebian provides neuroscience research s…   50                  [OK]
ubuntu-debootstrap                                        debootstrap --variant=minbase --components=m…   38                  [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mysql-5      ubuntu-16-nginx-php-phpmyadmin-mysql-5          36                                      [OK]
nuagebec/ubuntu                                           Simple always updated Ubuntu docker images w…   23                                      [OK]
tutum/ubuntu                                              Simple Ubuntu docker images with SSH access     18
i386/ubuntu                                               Ubuntu is a Debian-based Linux operating sys…   13
ppc64le/ubuntu                                            Ubuntu is a Debian-based Linux operating sys…   12
1and1internet/ubuntu-16-apache-php-7.0                    ubuntu-16-apache-php-7.0                        10                                      [OK]
1and1internet/ubuntu-16-nginx-php-phpmyadmin-mariadb-10   ubuntu-16-nginx-php-phpmyadmin-mariadb-10       6                                       [OK]
eclipse/ubuntu_jdk8                                       Ubuntu, JDK8, Maven 3, git, curl, nmap, mc, …   6                                       [OK]
codenvy/ubuntu_jdk8                                       Ubuntu, JDK8, Maven 3, git, curl, nmap, mc, …   4                                       [OK]
darksheer/ubuntu                                          Base Ubuntu Image -- Updated hourly             4                                       [OK]
1and1internet/ubuntu-16-apache                            ubuntu-16-apache                                3                                       [OK]
1and1internet/ubuntu-16-nginx-php-5.6-wordpress-4         ubuntu-16-nginx-php-5.6-wordpress-4             3                                       [OK]
1and1internet/ubuntu-16-sshd                              ubuntu-16-sshd                                  1                                       [OK]
pivotaldata/ubuntu                                        A quick freshening-up of the base Ubuntu doc…   1
1and1internet/ubuntu-16-healthcheck                       ubuntu-16-healthcheck                           0                                       [OK]
pivotaldata/ubuntu-gpdb-dev                               Ubuntu images for GPDB development              0
smartentry/ubuntu                                         ubuntu with smartentry                          0                                       [OK]
ossobv/ubuntu
...

OFFICIAL列中,带OK标记的表明这个镜像由公司构建和支持。其他镜像则由个人创建。确定要使用的映像后,可以使用命令pull将其下载到计算机。

执行以下ubuntu命令将官方映像下载到您的计算机:

docker pull ubuntu

您将看到以下输出:

Using default tag: latest
latest: Pulling from library/ubuntu
6b98dfc16071: Pull complete
4001a1209541: Pull complete
6319fc68c576: Pull complete
b24603670dc3: Pull complete
97f170c87c6f: Pull complete
Digest: sha256:5f4bdc3467537cbbe563e80db2c3ec95d548a9145d64453b06939c4592d67b6d
Status: Downloaded newer image for ubuntu:latest

下载映像后,可以使用子命令run运行容器。正如示例中那样,如果在使用子命令docker执行时未下载hello-world镜像,则Docker客户端将首先下载镜像,然后使用run运行容器。

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

docker images

输出应类似于以下内容:

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              113a43faa138        4 weeks ago         81.2MB
hello-world         latest              e38bc07ac18e        2 months ago        1.85kB

正如您将在本教程后面看到的那样,用于运行容器的镜像可以被修改并用于生成新镜像,然后可以将其上传到Docker Hub或其他Docker镜像托管网站。

我们来看看如何更详细地运行容器。

第5步 - 运行Docker容器

在您在上一步中hello-world容器是运行并发出一个测试消息之后退出容器。容器可以比这更有用,它们可以是交互式的。毕竟,它们类似于虚拟机,只是更加有利于资源。

举个例子,让我们使用Ubuntu的最新镜像运行一个容器。-i-t子命令的意思为您提供了对容器的交互式shell访问:

docker run -it ubuntu

现在,您应该已经进入docker内部,在这个环境下,您的shell展现如下:

root@d9b100f2f636:/#

请注意命令提示符中的容器ID。在例子中它是d9b100f2f636,稍后您需要该容器ID以在要删除容器时标识容器。现在您可以在容器内运行任何命令。例如,让我们更新容器内的包数据库。您不需要sudo命令添加前缀,因为您以root用户身份在容器内操作:

apt update

然后在其中安装任何应用程序。我们安装Node.js:

apt install nodejs

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

node -v

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

v8.10.0

您在容器内进行的任何更改仅适用于该容器。要退出容器,请输入exit退出。

让我们看看下一步管理我们系统上的容器。

第6步 - 管理Docker容器

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

docker ps

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

CONTAINER ID        IMAGE               COMMAND             CREATED             

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

要查看所有容器的运行状态,请使用docker ps命令加指令-a运行:

docker ps -a

您将看到类似于此的输出:

d9b100f2f636        ubuntu              "/bin/bash"         About an hour ago   Exited (0) 8 minutes ago                           sharp_volhard
01c950718166        hello-world         "/hello"            About an hour ago   Exited (0) About an hour ago                       festive_williams

要查看您创建的最新容器,请使用-l命令:

docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
d9b100f2f636        ubuntu              "/bin/bash"         About an hour ago   Exited (0) 10 minutes ago                       sharp_volhard

要启动已停止的容器,请使用docker start,后跟容器IDd9b100f2f636。让我们启动基于Ubuntu的容器,命令如下:

docker start d9b100f2f636

容器将启动,您可以使用docker ps来查看其状态:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
d9b100f2f636        ubuntu              "/bin/bash"         About an hour ago   Up 8 seconds                            sharp_volhard

要停止正在运行的容器,请使用docker stop,后跟容器ID或名称sharp_volhard。这次,我们将使用Docker分配容器的名称,即:

docker stop sharp_volhard

一旦您决定不再需要容器,请使用docker rm命令将其删除。使用该docker ps -a命令查找与映像hello-world关联的容器的容器,然后将其删除。

docker rm festive_williams

您可以使用开关启动一个新容器并为其命名--name。您还可以使用该开关创建一个在停止时自行删除的容器--rm。有关这些选项和其他选项的更多信息,请参阅docker run help命令。

容器可以转换为可用于构建新容器的映像。让我们来看看它是如何工作的。

步骤7 - 将容器中的更改提交到Docker镜像

当您启动Docker镜像时,您可以像使用虚拟机一样创建,修改和删除文件。您所做的更改仅适用于该容器。您可以启动和停止它,但是一旦使用docker rm命令销毁它,更改将永久丢失。本节介绍如何将容器的状态保存为新的Docker镜像。

在Ubuntu容器中安装Node.js后,您现在有一个运行镜像的容器,但容器与您用来创建它的镜像不同。但是您可能希望稍后重新使用此容器作为新映像。

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

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

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

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

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

当你提交镜像后,新的镜像在您的计算机上本地保存。在本教程的后面,您将学习如何将映像推送到Docker Hub之类的Docker镜像市场,以便其他人可以访问它。

再次列出Docker镜像将显示旧镜像以及从中衍生的新镜像:

docker images

你会看到这样的输出:

REPOSITORY               TAG                 IMAGE ID            CREATED             SIZE
sammy/ubuntu-nodejs   latest              7c1f35226ca6        7 seconds ago       179MB
ubuntu                   latest              113a43faa138        4 weeks ago         81.2MB
hello-world              latest              e38bc07ac18e        2 months ago        1.85kB

在此示例中,是新镜像ubuntu-nodejs,它是从Docker Hub的ubuntu现有镜像衍生的。镜像大小差异反映了所做的变化。因此,下次需要使用预先安装了NodeJS的Ubuntu运行容器时,您可以使用新映像ubuntu-nodejs

您还可以从Dockerfile构建映像,这样可以在新映像中自动安装软件。但是,这超出了本教程的范围。

现在让我们与他人分享新镜像,以便他们可以从中创建容器。

步骤8 - 将Docker镜像推送到Docker存储库

从现有映像创建新映像之后的下一个步骤是与您几个朋友分享,Docker Hub上的镜像全世界都可以访问,不过你先要安装注册Docker Hub地址才行。

本节介绍如何将Docker镜像推送到Docker Hub,要推送镜像,请先登录Docker Hub。

docker login -u docker-registry-username

系统将提示您使用Docker Hub密码进行身份验证。然后你可以使用以下方法推送自己的镜像

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

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

docker push sammy/ubuntu-nodejs

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

The push refers to a repository [docker.io/sammy/ubuntu-nodejs]
e3fbbfb44187: Pushed
5f70bf18a086: Pushed
a3b5c80a4eba: Pushed
7f18b442972b: Pushed
3ce512daaf78: Pushed
7aae4540b42d: Pushed

...

将镜像推送到注册表后,它应该列在您帐户的控制台上,如下图所示。

如果推送尝试导致此类错误,那么您可能没有登录:

The push refers to a repository [docker.io/sammy/ubuntu-nodejs]
e3fbbfb44187: Preparing
5f70bf18a086: Preparing
a3b5c80a4eba: Preparing
7f18b442972b: Preparing
3ce512daaf78: Preparing
7aae4540b42d: Waiting
unauthorized: authentication required

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

您现在可以使用docker pull sammy/ubuntu-node<^>将镜像拉取到新计算机并使用它来运行新容器。

结论

在本教程中,您学会了如何安装了Docker,如何使用镜像和容器,并将修改后的镜像推送到Docker Hub。腾讯云也提供了相关的容器服务,同时腾讯云容器服务基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务。腾讯云容器服务完全兼容原生 kubernetes API ,扩展了腾讯云的 CBS、CLB 等 kubernetes 插件,为容器化的应用提供高效部署、资源调度、服务发现和动态伸缩等一系列完整功能,解决用户开发、测试及运维过程的环境一致性问题,提高了大规模容器集群管理的便捷性,帮助用户降低成本,提高效率。容器服务提供免费使用,涉及的其他云产品另外单独计费。 欢迎登陆免费实验室进行试用。


参考文献:《How to Install and Use Docker on Ubuntu 18.04》

本站文章资源均来源自网络,除非特别声明,否则均不代表站方观点,并仅供查阅,不作为任何参考依据!
如有侵权请及时跟我们联系,本站将及时删除!
如遇版权问题,请查看 本站版权声明
THE END
分享
二维码
海报
如何在Ubuntu上安装使用Docker
在本教程中,您将安装Docker,并学会使用容器和镜像,将镜像推送到Docker存储库。
<<上一篇
下一篇>>