第一章 安装与基础使用 v1.0
第一部分 安装
一、Windows/Mac
Windows与Mac系统推荐安装Docker Desktop
访问 Docker 官网,下载对应系统版本的Docker Desktop安装包安装即可
二、Linux
安装Docker Engine
bash
# add repo
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
if [ $? -ne 0 ]; then
echo "add repo fail, exit..."
exit 1
fi
# install
yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
if [ $? -ne 0 ]; then
echo "install fail, exit..."
exit 1
fi
# start docker and set docker to start automatically on boot
systemctl start docker
systemctl enable docker
bash
# add repo
dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
if [ $? -ne 0 ]; then
echo "add repo fail, exit..."
exit 1
fi
# replace $releasever
sed -i 's/\$releasever/9/g' /etc/yum.repos.d/docker-ce.repo
# install
dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
if [ $? -ne 0 ]; then
echo "install fail, exit..."
exit 1
fi
# start docker and set docker to start automatically on boot
systemctl start docker
systemctl enable docker
第二部分 基础使用
Docker 的核心操作围绕:镜像(Image)和容器(Container)展开
两者关系belike:镜像是容器的模板,容器是基于镜像构建的运行实例
一、基本使用流程
- 拉取镜像:从Docker Hub(官方镜像仓库)或私有仓库下载镜像
- 创建容器:基于镜像创建可运行的容器实例
- 操作容器:启动、停止、进入容器,或在容器中执行命令
- 销毁资源:删除不再使用的容器或镜像,释放存储空间
二、基础使用
示例:Docker使用Python镜像运行容器并执行HelloWorld程序
1、拉取基础镜像
shell
docker pull <image-name>[:<tag>] # tag参数可选,默认为latest,即最新版
shell
docker images
shell
docker pull python:latest # 拉取最新版本的Python镜像
docker images # 可看到已拉取的python镜像信息
*镜像拉取缓慢解决方案
可配置国内镜像源,以Linux系统为例,编辑配置文件
json
{
"registry-mirrors": ["https://xxx.mirror.aliyuncs.com"]
}
编辑后重启Docker:systemctl daemon-reload && systemctl restart docker
快速配置镜像源操作示例
bash
# write images repo
# 当前各大国内镜像站点陆续关停Docker镜像源,以下镜像源为互联网搜集,不一定仍可用
sudo tee /etc/docker/daemon.json <<-'EOF'
{
"registry-mirrors": [
"https://docker.m.daocloud.io",
"https://docker.imgdb.de",
"https://docker-0.unsee.tech",
"https://docker.hlmirror.com",
"https://docker.1ms.run",
"https://func.ink",
"https://lispy.org",
"https://docker.xiaogenban1993.com"
]
}
EOF
# restart
systemctl daemon-reload && systemctl restart docker
2、基于镜像创建并运行容器
shell
docker run <image-name>[:<tag>] # tag参数可选,默认为latest,即最新版
shell
docker run -n python-container python:latest # -n <name>: 指定当前容器名称
3、执行命令
shell
docker exec <id/name> [command]
shell
docker exec -it <id/name> [bash]
shell
docker exec python-container python -c "print('hello world')"
三、清理容器与镜像
1、停止正在运行的容器
shell
docker stop <id/name>
shell
docker stop python-container
2、删除容器
shell
docker rm <id/name>
shell
docker rm python-container
3、删除镜像
shell
docker rmi <image-name>[:<tag>]
shell
docker rmi python:latest