linux环境下(ubuntu和centos通用)安装和使用docker教程

234 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。    

1. 安装docker

在centos终端执行命令:

curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

该命令同样适用于ubantu系统。 过程如下:

warning: /var/cache/yum/x86_64/7/docker-ce-stable/packages/docker-ce-20.10.2-3.el7.x86_64.rpm: Header V4 RSA/SHA512 Signature, key ID 621e9f35: NOKEY
Public key for docker-ce-20.10.2-3.el7.x86_64.rpm is not installed
Importing GPG key 0x621E9F35:
 Userid     : "Docker Release (CE rpm) <docker@docker.com>"
 Fingerprint: 060a 61c5 1b55 8a7f 742b 77aa c52f eb6b 621e 9f35
 From       : https://download.docker.com/linux/centos/gpg
setsebool:  SELinux is disabled.
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker your-user

Remember that you will have to log out and back in for this to take effect!

WARNING: Adding a user to the "docker" group will grant the ability to run
         containers which can be used to obtain root privileges on the
         docker host.
         Refer to https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface
         for more information.

执行完成后,表示docker已经自动安装成功! 可以通过docker version查看docker的版本: 在这里插入图片描述

2. 配置docker镜像加速源

cd /etc/docker/daemon.json 添加如下内容,如果daemon.json文件不存在,那么使用vim命令创建该文件

{"registry-mirrors":["https://reg-mirror.qiniu.com/"]} 

也可使用以下命令配置daemon.json:

sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "registry-mirrors":["https://reg-mirror.qiniu.com/"],
  "live-restore": true,
  "log-driver":"json-file",
  "log-opts": {"max-size":"500m", "max-file":"3"},
  "storage-driver": "overlay2"
}
EOF

添加完成后使用命令:

sudo systemctl daemon-reload
sudo systemctl restart docker

如果没有报错,那么表示docker启动成功,镜像加速源也配好了! 另外附其他镜像加速源: 科大镜像:docker.mirrors.ustc.edu.cn/ 网易:hub-mirror.c.163.com/ 阿里云:https://<你的ID>.mirror.aliyuncs.com

3. 使用docker启动第一个容器

1) 运行第一个容器

docker run ubuntu:15.10 /bin/echo "hello word"

在这里插入图片描述

原理 docker 会先从本地寻找ubuntu镜像,如果存在那么就启动,如果不存在,那么docker就会从默认的镜像仓库中下载出ubuntu镜像。

2) 运行一个交互式的容器

在这里插入图片描述

参数解析:

  • -i : 该参数表示的是可以与容器进行对话。
  • -t: 该参数表示的是可以在容器里打开一个新的终端。

如图,可以发现进入到了ubuntu容器的终端里。

3) 常用命令

docker run 启动一个容器 -d: 表示以后台的形式启动,相当于一个进程。 在这里插入图片描述

docker ps 查看docker容器里有哪些镜像。 在这里插入图片描述

docker stop 7d1dfae34632 停止docker里CONTAINER ID 为 7d1dfae34632 的容器。 在这里插入图片描述

docker logs 7d1dfae34632 查看容器id 为7d1dfae34632 里的输出日志。 在这里插入图片描述 docker images 查看docker里的所有镜像 在这里插入图片描述

docker pull 镜像名称 从远程仓库Docker Hub中拉取指定镜像 在这里插入图片描述 docker rmi IMAGE ID 删除指定镜像 注: 如果镜像被容器在使用,那么会出现删除失败的问题: 在这里插入图片描述 已经没有在使用的镜像可以被删除: 在这里插入图片描述 systemctl status docker.service 查看docker运行状态 在这里插入图片描述 systemctl start docker.service 启动docker服务 systemctl stop docker.service 停止docker服务 docker login 登录到docker的Hub仓库

参考文章