掌握构建镜像的两种方法
(1),使用docker commit 命令基于容器构建镜像
(2),使用docker build基于Dockerfile 构建镜像
(1),使用docker commit 命令基于容器构建镜像
以交互方式运行ubuntu镜像
docker run -it ubuntu /bin/bash
docker run -d 后台运行容器,并返回容器id
docker run -i 让容器的标准输入保持打开
docker run -t 为容器重新分配一个伪输入终端
docker run -p 设置端口 格式为"主机端口:容器端口"
--dns 指定容器使用的dns服务器
--name 为容器指定一个名称
--rm 容器退出时自动删除
在容器中安装nginx
root@a121e9acb7d6:/# apt update //更新软件包
root@a121e9acb7d6:/# apt install -y nginx
root@a121e9acb7d6:/# nginx -v //查看版本
基于该容器生成新的镜像
root@a121e9acb7d6:/# exit //先退出容器
[root@localhost ~]# docker commit a121e9acb7d6 ubuntu-with-nginx
//执行docker commit 将该容器提交并在本地生成新的镜像
基于新的镜像启动新容器
//以交互方式启动容器后,在容器中执行nginx命令启动Nginx服务。然后使用 ps -aux查询相关的进程
(2),使用docker build基于Dockerfile 构建镜像
//准备构建Dockerfile 构建上下文
[root@localhost ~]# mkdir ubuntu-nginx && cd ubuntu-nginx
//编写Dockerfile文件,使用nano 进行编辑。
[root@localhost ubuntu-nginx]# nano Dockerfile
FROM ubuntu:latest
RUN apt update && apt install -y nginx
RUN echo "Hello!This is nginx server" > /usr/share/nginx/html/index.html
EXPOSE 80
CMD ["nginx","-g","daemon off;"]
//构建镜像
[root@localhost ubuntu-nginx]# docker build -t ubuntu-with-nginx:1.0 .
//基于该镜像启动容器
[root@localhost ubuntu-nginx]# docker run --rm -d -p 8000:80 --name test-nginx ubuntu-with-nginx:1.0
//访问nginx网站进行测试
[root@localhost ubuntu-nginx]# curl 127.0.0.1:8000
(3),测试镜像构建的缓存
//修改Dockerfile文件
RUN echo "Hello!This is nginx server" > /usr/share/nginx/html/index.html && cp /usr/share/nginx/html/index.html /var/www/html
//构建新的镜像
docker build -t ubuntu-with-nginx:2.0 .
//启动新镜像进行测试
docker run --rm -d -p 8000:80 --name test-nginx ubuntu-with-nginx:2.0
[root@localhost ubuntu-nginx]# curl 127.0.0.1:8000
Hello!This is nginx server