如何在 Ubuntu 上安装和使用 Docker

第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 -
Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)).
OK

将 Docker 存储库添加到 APT 源:

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

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

确保您即将从 Docker 仓库安装,而不是从默认的 Ubuntu 仓库安装:

apt-cache policy docker-ce

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

最后,安装 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 Wed 2025-07-30 21:39:27 CST; 18s ago
TriggeredBy:  docker.socket
       Docs: https://docs.docker.com
   Main PID: 1981534 (dockerd)
      Tasks: 10
     Memory: 22.2M
        CPU: 447ms
     CGroup: /system.slice/docker.service
             └─1981534 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock

Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306373044+08:00" level=warning msg="WARNING: No io.weight (per device) support"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306379103+08:00" level=warning msg="WARNING: No io.max (rbps) support"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306385273+08:00" level=warning msg="WARNING: No io.max (wbps) support"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306391064+08:00" level=warning msg="WARNING: No io.max (riops) support"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306396825+08:00" level=warning msg="WARNING: No io.max (wiops) support"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.306421105+08:00" level=info msg="Docker daemon" commit=bea959c containerd-snapshotter=false storage-driver=overlay2 version=28.3.3
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.308027446+08:00" level=info msg="Initializing buildkit"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.343898090+08:00" level=info msg="Completed buildkit initialization"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.348226593+08:00" level=info msg="Daemon has completed initialization"
Jul 30 21:39:27 lavm-od61ss3meu dockerd[1981534]: time="2025-07-30T21:39:27.348302779+08:00" level=info msg="API listen on /run/docker.sock"
root@lavm-od61ss3meu:~# 

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

默认情况下,该
docker命令只能由
root用户或
docker组中的用户运行
,该组在 Docker 安装过程中自动创建。如果你尝试
docker在不添加前缀
sudo或不属于
docker组的情况下运行该命令,则会得到如下输出:

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

输出

sammy sudo docker

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

sudo usermod -aG docker username

第3步 – 使用Docker命令

使用过程
docker包括传递一系列选项和命令,以及后面的参数。语法如下:

docker [option] [command] [arguments]

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

docker

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

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
  bake        Build from a file
  pull        Download an image from a registry
  push        Upload an image to a registry
  images      List images
  login       Authenticate 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
  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:
  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/
root@lavm-od61ss3meu:~# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
root@lavm-od61ss3meu:~# docker -v
Docker version 28.3.3, build 980b856
root@lavm-od61ss3meu:~# 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
  bake        Build from a file
  pull        Download an image from a registry
  push        Upload an image to a registry
  images      List images
  login       Authenticate 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
  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:
  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 命令参数--help

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

docker info

输出下面

docker info
Client: Docker Engine - Community
 Version:    28.3.3
 Context:    default
 Debug Mode: false
 Plugins:
  buildx: Docker Buildx (Docker Inc.)
    Version:  v0.26.1
    Path:     /usr/libexec/docker/cli-plugins/docker-buildx
  compose: Docker Compose (Docker Inc.)
    Version:  v2.39.1
    Path:     /usr/libexec/docker/cli-plugins/docker-compose

Server:
 Containers: 0
  Running: 0
  Paused: 0
  Stopped: 0
 Images: 3
 Server Version: 28.3.3
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 CDI spec directories:
  /etc/cdi
  /var/run/cdi
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 05044ec0a9a75232cad458027ca83437aae3f4da
 runc version: v1.2.5-0-g59923ef
 init version: de40ad0
 Security Options:
  apparmor
  seccomp
   Profile: builtin
  cgroupns
 Kernel Version: 5.15.0-60-generic
 Operating System: Ubuntu 22.04.3 LTS
 OSType: linux
 Architecture: x86_64
 CPUs: 4
 Total Memory: 7.763GiB
 Name: lavm-od61ss3meu
 ID: 344ed51d-62f7-4c82-a000-bf508368f60d
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Experimental: false
 Insecure Registries:
  ::1/128
  127.0.0.0/8
 Live Restore Enabled: false

WARNING: No cpu cfs quota support
WARNING: No cpu cfs period support
WARNING: No cpu shares support
WARNING: No cpuset support
WARNING: No io.weight support
WARNING: No io.weight (per device) support
WARNING: No io.max (rbps) support
WARNING: No io.max (wbps) support
WARNING: No io.max (riops) support
WARNING: No io.max (wiops) support

第4步 – 使用Docker镜像

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

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

发表评论