引言
Docker 是一个开源的应用容器引擎,它允许开发者打包他们的应用以及应用的依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化。本教程将带领新手从零开始,在 Linux 系统上安装与配置 Docker。
环境准备
在开始之前,请确保你的 Linux 系统满足以下要求:
- Linux 发行版:Ubuntu、CentOS、Debian 等
- 系统版本:至少是 Ubuntu 16.04、CentOS 7、Debian 9
- root 用户权限
安装 Docker
使用包管理器安装
以下以 Ubuntu 20.04 为例,使用 apt 包管理器安装 Docker:
sudo apt update
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
sudo apt update
sudo apt install -y docker-ce
使用 Docker 安装
你也可以直接使用 Docker 的官方安装脚本:
sudo curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
安装完成后,可以使用以下命令查看 Docker 版本:
docker --version
配置 Docker
设置 Docker 为非 root 用户
为了安全起见,建议为非 root 用户设置 Docker 权限:
sudo usermod -aG docker $USER
newgrp docker
设置 Docker 仓库镜像加速
由于 Docker 官方镜像仓库在国内访问速度较慢,你可以设置镜像加速器来提高下载速度。以下以 Daocloud 为例:
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": ["https://f1361db2.mirror.aliyuncs.com"]
}
EOF
sudo systemctl restart docker
使用 Docker
运行第一个容器
现在,你可以尝试运行一个简单的容器:
docker run hello-world
如果一切顺利,你将看到以下输出:
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 executed the 'docker run' command.
2. The Docker daemon received the command from the client, and sent out a container request.
3. The Docker daemon created a new container from an image that matches your request (Ubuntu:latest).
4. The Docker daemon ran the container in a way that the user receives output from the container’s CMD (which is the 'echo' command in this case).
To run a command in a new container, start with the 'docker run' command.
EOF
查看容器列表
你可以使用以下命令查看当前正在运行的容器:
docker ps
停止和删除容器
停止一个正在运行的容器:
docker stop 容器ID或名称
删除一个容器:
docker rm 容器ID或名称
总结
恭喜你,你已经完成了 Linux 系统上 Docker 的安装与配置!现在你可以开始使用 Docker 来构建、测试和部署你的应用程序了。希望这篇教程对你有所帮助!