课程地址
容器技术概述
docker能做什么:将应用程序代码和依赖打包为一个镜像,作为交付介质,在各种环境中部署
相比于虚拟机,docker 只虚拟出一个隔离的程序运行环境,其需要则资源大大减少
容器内的程序就好像直接运行在宿主机上,能够最大限度地使用宿主机的资源,但是它们相互隔离
容器对比KVM虚拟机的好处:
- 容器能够提供宿主机的原生的性能,而 kvm 虚拟机是分配宿主机硬件资源,容器需要的资源更少
- 启动一个 KVM 虚拟机,得有一个完整的开机流程,花费时间较长,或许得20S,而启动一个容器只需要1S
- KVM 需要硬件 CPU 的虚拟化支持,而容器不需要
Docker的使用流程:
docker最核心的组件:
- image镜像,构建容器(我们讲应用程序运行所需的环境,打包为镜像文件)
- container,容器(你的应用程序,就跑在容器中)
- 镜像仓库(dockerhub):保存镜像文件,提供上传,下载镜像)作用好比 github
- Dockerfile,将你部署项目的操作,写成一个部署脚本,这就是 dockerfile,且该脚本还能够构建出镜像文件
容器是镜像的一个运行实例
安装 Docker
更新本地仓库:
$ wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/epel-7.repo
$ wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
$ yum clean all #清空本地缓存
$ yum makecache #新的缓存
$ iptables -F
关闭selinux
getenforce # 获取selinux状态
sestatus # 获取selinux状态
vim /etc/selinux/config # 修改selinux状态#output# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy. Only selected processes are protected.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
关闭并停止防火墙:
systemctl disable firewalld
systemctl stop firewalld
开启linux内核的流量转发:
cat <<EOF > /etc/sysctl.d/docker.conf
net.bridge.bridge-nf-call-ip6tables = 1
net.bridge.bridge-nf-call-iptables = 1
net.ipv4.conf.default.rp_filter = 0
net.ipv4.conf.all.rp_filter = 0
net.ipv4.ip_forward=1
EOF# 加载配置文件
modprobe br_netfilter
sysctl -p /etc/sysctl.d/docker.conf
通过yum安装docker
curl -o /etc/yum.repos.d/docker-ce.repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
yum clean all && yum makecache
yum install docker-ce-20.10.6 -y
遇到的问题:
--> Finished Dependency Resolution
Error: Package: containerd.io-1.6.15-3.1.el7.x86_64 (docker-ce-stable)Requires: container-selinux >= 2:2.74
Error: Package: docker-ce-rootless-extras-20.10.22-3.el7.x86_64 (docker-ce-stable)Requires: fuse-overlayfs >= 0.7
Error: Package: 3:docker-ce-20.10.6-3.el7.x86_64 (docker-ce-stable)Requires: container-selinux >= 2:2.74
Error: Package: docker-ce-rootless-extras-20.10.22-3.el7.x86_64 (docker-ce-stable)Requires: slirp4netns >= 0.4You could try using --skip-broken to work around the problemYou could try running: rpm -Va --nofiles --nodigest
解决方法
简单来说就是去这个地方寻找最新的依赖,比如slirp4netns-0.4.3-4.el7_8.x86_64.rpm
,然后通过
sudo yum install -y yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/slirp4netns-0.4.3-4.el7_8.x86_64.rpm
安装这个最新的依赖,最后重新执行docker的安装命令即可。其他的依赖也是同理
配置镜像加速:
$ vim /etc/docker/daemon.json
$ cat /etc/docker/daemon.json
{
"registry-mirrors" : ["https://8xpk5wnt.mirror.aliyuncs.com"]
}
启动docker:
systemctl daemon-reload
systemctl enable docker
systemctl restart docker
使用 Docker
Docker 启动与停止
# 安装nginx镜像
docker pull nginx
# 查看本地安装的镜像
docker images
# 删除镜像
docker rmi 605c77e624dd
# 启动镜像
# -p, --publish list: Publish a container's port(s) to the host, host_port: container_port
# -d, --detach
docker run -d -p 880:80 nginx # -d, --detach
# 查看正在运行的实例
docker ps
# 停止镜像
docker stop 1bf388d03f19
# 再次启动
docker start 1bf388d03f19
启动nginx后,就可以访问http://192.168.93.12:880
看到nginx服务了,注意这里的880是宿主机端口,经过映射才到了容器内的nginx的80端口
Docker 生命周期
切换不同的 Linux 发行版
内核都公用宿主机的内核,上层的发行版可由 docker 自由替换
确认当前宿主机发行版:
$ cat /etc/redhat-release
$ cat /etc/os-release
CentOS Linux release 7.9.2009 (Core)
下载 2 个新的发行版:
$ docker pull ubuntu
$ docker pull centos:7.8.2003$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
redis latest 7614ae9453d1 13 months ago 113MB
ubuntu latest ba6acccedd29 15 months ago 72.8MB
centos 7.8.2003 afb6fca791e0 2 years ago 203MB
开启一个新的终端:
$ docker run -it afb6fca791e0 bash # --interactive --tty
查看容器内的发行版本:
[root@132e45321e68 /]# cat /etc/redhat-release
CentOS Linux release 7.8.2003 (Core)
Docker 镜像管理
进入到正在运行的容器内exec
:
$ docker exec -it 1bf388d03f19 bashroot@1bf388d03f19:/# ls
bin boot dev docker-entrypoint.d docker-entrypoint.sh etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var
root@1bf388d03f19:/# cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 11 (bullseye)"
NAME="Debian GNU/Linux"
VERSION_ID="11"
VERSION="11 (bullseye)"
VERSION_CODENAME=bullseye
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"
分层镜像的好处:共享资源,例如有多个镜像都来自于同一个 base 镜像,那么在 docker host 只需要存储一份base镜像。内存里也只需要加载一份host,即可为多个容器服务
即使多个容器共享一个 base 镜像,某个容器修改了 base 镜像的内容,例如修改/etc/下配置文件,其他容器的/etc/下内容是不会被修改的,修改动作只限制在单个容器内,这就是容器的写入时复制特性 (Copy-on-write)
当容器启动后,一个新的可写层被加载到容器顶部,这一层通常被称为容器层,容器层之下都被称为镜像层
只有容器层是可写的,下面的镜像层都是只读的
获取镜像
docker images # 查看本地镜像
docker search image_name[:version]
docker pull image_name[:version]
获取docker信息:docker info
$ docker info | grep Root
Docker Root Dir: /var/lib/docker# 该目录下的每一个文件都是一个json文件,记录了镜像和容器的关系
$ pwd
/var/lib/docker/image/overlay2/imagedb/content/sha256#--rm: Automatically remove the container when it exits
$ docker run -it --rm 5d0da3dc9764 bash[root@f8c3d3b2783d /]# cat /etc/redhat-release
CentOS Linux release 8.4.2105
查看镜像
docker images
docker images centos
docker images centos:7.8.2003
docker images -q #只获取IDs:--quiet, Only show image IDs
格式化显示镜像:
$ docker images --format "{{.ID}}:{{.Repository}}"
605c77e624dd:nginx
7614ae9453d1:redis
ba6acccedd29:ubuntu
5d0da3dc9764:centos
afb6fca791e0:centos$ docker images --format "table {{.ID}}\t{{.Repository}}\t{{.Tag}}"
IMAGE ID REPOSITORY TAG
605c77e624dd nginx latest
7614ae9453d1 redis latest
ba6acccedd29 ubuntu latest
5d0da3dc9764 centos latest
afb6fca791e0 centos 7.8.2003
删除镜像
hello-world镜像:
docker pull hello-world
docker run hello-world
查看所有运行(过)的容器记录:
docker ps -a #--all, Show all containers (default shows just running)
先删除容器记录:
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4fca3667e308 hello-world "/hello" 3 minutes ago Exited (0) 3 minutes ago nifty_babbage
7e90b6e223d6 nginx "/docker-entrypoint.…" 3 hours ago Up 3 hours 0.0.0.0:80->80/tcp, :::80->80/tcp stoic_mccarthy
6bce09c83930 ba6acccedd29 "bash" 19 hours ago Exited (127) 18 hours ago infallible_gates
132e45321e68 afb6fca791e0 "bash" 19 hours ago Exited (0) 19 hours ago objective_mclaren
803ecacc6b7d afb6fca791e0 "absh" 19 hours ago Created epic_booth
7b05004a50eb afb6fca791e0 "/bin/bash" 19 hours ago Exited (0) 19 hours ago inspiring_borg
1bf388d03f19 nginx "/docker-entrypoint.…" 24 hours ago Exited (0) 12 hours ago awesome_mayer$ docker rm 4fca3667e308
4fca3667e308
再删除容器:
# 或者:docker rmi hello-world
$ docker rmi feb5d9fea6a5
Untagged: hello-world:latest
Untagged: hello-world@sha256:2498fce14358aa50ead0cc6c19990fc6ff866ce72aeb5546e1d59caac3d0d60f
Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412
Deleted: sha256:e07ee1baac5fae6a26f30cabfe54a36d3402f96afda318fe0a96cec4ca393359
批量删除:
# 批量删除所有镜像
docker rmi `docker images -aq` # -a: all, -q: quit
# 批量删除所有容器
docker rm `docker images -aq`
导出镜像
将修改过的镜像打包导出,比如安装了各种实用工具的os镜像
docker image save centos:7.8.2003 > ./centos7.8.2003.tgz
导入镜像
docker image load -i ./centos7.8.2003.tgz # 导入镜像
$ docker rm `docker ps -aq` # 删除镜像
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
redis latest 7614ae9453d1 13 months ago 113MB
ubuntu latest ba6acccedd29 15 months ago 72.8MB
centos latest 5d0da3dc9764 16 months ago 231MB
centos 7.8.2003 afb6fca791e0 2 years ago 203MB$ docker rmi afb6fca791e0
Untagged: centos:7.8.2003
Untagged: centos@sha256:8540a199ad51c6b7b51492fa9fee27549fd11b3bb913e888ab2ccf77cbb72cc1
Deleted: sha256:afb6fca791e071c66276202f8efca5ce3d3dc4fb218bcddff1bc565d981ddd1e
Deleted: sha256:fb82b029bea0a2a3b6a62a9c1e47e57fae2a82f629b2d1a346da4fc8fb53a0b6
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
redis latest 7614ae9453d1 13 months ago 113MB
ubuntu latest ba6acccedd29 15 months ago 72.8MB
centos latest 5d0da3dc9764 16 months ago 231MB$ docker image load -i ./centos7.8.2003.tgz # 导入镜像
fb82b029bea0: Loading layer [==================================================>] 211.1MB/211.1MB
Loaded image: centos:7.8.2003
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 605c77e624dd 12 months ago 141MB
redis latest 7614ae9453d1 13 months ago 113MB
ubuntu latest ba6acccedd29 15 months ago 72.8MB
centos latest 5d0da3dc9764 16 months ago 231MB
centos 7.8.2003 afb6fca791e0 2 years ago 203MB
查看镜像详细信息:
docker image inspect afb6fca791e0
Docker容器管理
docker run image_name
等于创建+启动,如果镜像不存在本地,则会在线下载该镜像
注意,容器内的进程必须处于前台运行状态,否则容器就会直接退出
如果我们运行centos基础镜像,没有运行任何程序,容器会直接挂掉:
$ docker run centos:7.8.2003
$ docker run centos:7.8.2003
$ docker ps # 运行失败
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
377a4ced80e0 centos:7.8.2003 "/bin/bash" 7 seconds ago Exited (0) 7 seconds ago kind_merkle
62c14dd9fa98 centos:7.8.2003 "/bin/bash" 11 seconds ago Exited (0) 10 seconds ago naughty_volhard# 运行bash,sh和ping
$ docker run -it centos:7.8.2003 bash
[root@520e67be661c /]# exit
exit
$ docker run -it centos:7.8.2003 sh
sh-4.2# exit
exit$ docker run -it centos:7.8.2003 ping baidu.com$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
bce9360b1728 centos:7.8.2003 "ping baidu.com" 2 minutes ago Exited (0) 2 minutes ago sweet_euclid
45a3d0c7fa81 centos:7.8.2003 "sh" 2 minutes ago Exited (0) 2 minutes ago kind_euclid
520e67be661c centos:7.8.2003 "bash" 2 minutes ago Exited (0) 2 minutes ago practical_pare
377a4ced80e0 centos:7.8.2003 "/bin/bash" 4 minutes ago Exited (0) 4 minutes ago kind_merkle
62c14dd9fa98 centos:7.8.2003 "/bin/bash" 4 minutes ago Exited (0) 4 minutes ago naughty_volhard# -d后台运行
$ docker run -d centos:7.8.2003 ping baidu.com
2abff83b33b8989e9d0dc23c1e63ff7752186f06875c5aa7cff6792182c0441e
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
2abff83b33b8 centos:7.8.2003 "ping baidu.com" 5 seconds ago Up 4 seconds laughing_panini
其他运行参数:
# rm:运行后自动删除;name:命名
$ docker run -d --rm --name ping_baidu centos:7.8.2003 ping baidu.com
029d84623de7238bf14416969fd1e85a11b101cf13753cae484f8b45056ed269
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
029d84623de7 centos:7.8.2003 "ping baidu.com" 11 seconds ago Up 10 seconds baidu
$ docker stop 029d84623de7
029d84623de7
查看日志:
docker logs 2abff83b33b8 | tail -5
进入到正在运行的容器内:
docker exec -it d502f362eac9 bash
查看容器的详细信息:
docker container inspect d502f362eac9
后台运行nginx:
docker run -d --name docker_demo -p 80:80 nginx
查看容器内的端口转发情况:
$ docker port 87460199b5c5
80/tcp -> 0.0.0.0:85
80/tcp -> :::85
随机端口映射:
docker run -d --name docker_demo_P -P nginx
容器的提交:
# 首先启动一个初始容器
$ docker run -it centos7.8.2003 bash
# 在容器内安装vim
$ yum install vim -y
# 提交
$ docker commit 49ab6f9cfa5b syc198/centos-vim-7.8.2003
# 再次加载带有vim的centos
$ docker run -it syc198/centos-vim-7.8.2003 bash
Dockerfile
镜像是多层存储,每一层在前一层的基础上进行修改
容器也是多层存储,以镜像为基础层,在其基础层上加一层作为容器运行时的存储层
创建镜像有 2 个方法:
- 手动修改容器内容,docker commit
- 使用 dockerfile 定制
dockerfile 用于自定义镜像,主要有三大组成部分:
- 基础镜像信息:
FROM centos:6.8
- 制作镜像操作指令:
RUN yum install openssh-server -y
- 容器启动时执行指令:
CMD ["/bin/bash"]
指令 | 含义 |
---|---|
FROM | 父镜像 |
MAINTAINER | 维护者 |
RUN | 运行shell命令 |
ADD | 添加宿主机的文件到容器内,会自动解压 |
COPY | 同ADD指令,不会自动解压 |
WORKDIR | 设置当前工作目录,作用同cd |
VOLUME | 设置挂载卷,将容器内的目录挂载到主机上 |
EXPOSE | 指定对外开放的端口 |
CMD | 指定启动容器后要干的事 |
RUN
需求:写一个 dockerfile 构建一个 nginx 镜像,可以运行 nginx 服务
编写 Dockerfile:
FROM nginx
RUN echo "<h1>hello, Dockerfile<h1>" > /usr/share/nginx/html/index.html
构建:
$ docker build .
$ docker tag c5a08f633c37 my_nginx # 为生成的镜像命名
运行:
$ docker run -d -p 80:80 my_nginx
COPY与CMD
# copy指令能够保留源文件的元数据,如权限,访问时间等
COPY chaoge.py /home/
COPY chaoge* /tmp/cc?.txt. /home/CMD ["/bin/bash"]
CMD ["cat", "/etc/os-release"] # docker run -it centos cat /etc/os-release
CMD ["nginx", "-g", "deamon off"] # docker中必须要在`前台`运行程序
ENTRYPOINT
ENTRYPOINT 和 CMD:
entrypoint 和 cmd 的作用一样,都是在指定容器启动程序以及参数。但是在指定 entrypoint 后,cmd 指令的语义就有了变化:cmd 中的内容被当作参数传递给 entrypoint 指令
编写Dockerfile:
FROM centos:7.8.2003
RUN rpm --rebuilddb && yum install epel-release -y
RUN rpm --rebuilddb && yum install curl -y
CMD ["curl", "-s", "http://ipinfo.io/ip"]
构建:
docker build .
docker tag e247b94ec812 centos_curl
运行镜像,生成容器:
$ docker run centos_curl
110.243.77.78 # CMD的执行结果
$ docker run centos_curl pwd
/
如果想对命令curl -s http://ipinfo.io/ip
增加-I
选项如何呢?
当然可以执行完整的curl命令:
$ docker run centos_curl curl -s http://ipinfo.io/ip -I
HTTP/1.1 200 OK
access-control-allow-origin: *
content-type: text/html; charset=utf-8
content-length: 13
date: Thu, 19 Jan 2023 13:14:25 GMT
x-envoy-upstream-service-time: 1
strict-transport-security: max-age=2592000; includeSubDomains
Via: 1.1 google
这很繁琐,下面修改Dockerfile:
FROM centos:7.8.2003
RUN rpm --rebuilddb && yum install epel-release -y
RUN rpm --rebuilddb && yum install curl -y
ENTRYPOINT ["curl", "-s", "http://ipinfo.io/ip"]
这时可以简单地增加-I
选项:
docker run centos_curl_new -I
# curl -s http://ipinfo.io/ip -I
ARG与ENV
都是给容器设置环境变量
区别在于 ENV 设置的环境变量,无论是在容器构建时还是在容器运行时,该变量都有效;而ARG设置的变量只存在于容器构建时
ENV NAME="daniel"
ENV AGE="18"
ENV MYSQL_VERSION=5.6RUN yum install mysql-$MYSQL_VERSION
VOLUME
容器运行时,应保证存储层不写入任何数据;运行在容器内产生的数据,推荐挂在到宿主机上,写入宿主机
VOLUME /data
,将容器内的/data文件夹在容器运行时,该目录自动挂载为匿名卷,任何向该目录中写入数据的操作,都不会被容器记录,保证的容器存储层无状态理念
FROM centos:7.8.2003
MAINTAINER syc198@qq.com
VOLUME ["/data1", "/data2"]
构建&运行:
docker build .
docker run 35a8a728f7a5
查看详细信息:
docker inspect CONTAINER_ID
得到的目录相关信息:
"Mounts": [{"Type": "volume","Name": "ff150caa553c68a29141986f2f0c3a90db0e8391ce849d38a7988d58be3afa94","Source": "/var/lib/docker/volumes/ff150caa553c68a29141986f2f0c3a90db0e8391ce849d38a7988d58be3afa94/_data","Destination": "/data1","Driver": "local","Mode": "","RW": true,"Propagation": ""},{"Type": "volume","Name": "fbb7728b3ddabe83e725310622bb12dc32846f043a53d6600e462566f6dd3b46","Source": "/var/lib/docker/volumes/fbb7728b3ddabe83e725310622bb12dc32846f043a53d6600e462566f6dd3b46/_data","Destination": "/data2","Driver": "local","Mode": "","RW": true,"Propagation": ""}],"Volumes": {"/data1": {},"/data2": {}},
EXPOSE
指定容器运行时对外提供的端口服务
跟端口相关的命令:
docker port 30220bb56389
docker run -p 80:80 # 宿主机端口:容器端口
docker run -P # 随机端口映射
WORKDIR
在dockerfile中切换工作目录
WORKDIR /opt
USER
在dockerfile中切换用户
USER daniel
USER root
使用Docker部署一个python后端
后端逻辑:
#coding:utf8
from flask import Flaskapp=Flask(__name__)
@app.route('/hello')
def hello():return "hello form docker, i am daniel"if __name__ == "__main__":app.run(host="0.0.0.0", port=8080)
Dockerfile:
FROM centos:7.8.2003
RUN curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo;
RUN curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo;
RUN yum makecache fast;
RUN yum install python3-devel python3-pip -y
RUN pip3 install -i https://pypi.douban.com/simple flask
COPY app.py /opt
WORKDIR /opt
EXPOSE 8080
CMD ["python3", "app.py"]
构建和运行:
$ docker build --no-cache -t "my_flask" .
$ docker run -d --name my_flask_1 -p 80:8080 my_flask
如何修改该网站的内容:进入容器,修改代码,重启容器
$ docker exec -it my_flask_1 bash
$ docker restart db09dc0a257d
回顾
docker 利用容器运行应用程序
容器是镜像的运行实例,可以被run、start、stop、rm
每个容器都是相互隔离,保证平台安全
容器可以看作是一个简易版Linux环境(有root权限,进程,用户空间,网络)
镜像是只读的,容器在启动的时候创建一层可写层
$ docker run --name my_nginx -d --restart=always ubuntu bash
$ docker run --name my_nginx -d -p 80:80 --rm nginx
$ docker run -P -rm nginx
$ docker logs -f
查看容器内进程信息:
$ docker top 458c807fc5aa
查看容器内的资源信息:
$ docker stats 458c807fc5aa
查看容器的详细信息:
$ docker inspect 458c807fc5aa
获取容器IP:
$ docker inspect --format "{{.NetworkSettings.IPAddress}}" 458c807fc5aa