Docker 实战—运用 Dockerfile 构建镜像
2019-11-18杂谈搜奇网33°c
A+ A-GitHub Page:http://blog.cloudli.top/posts/Docker实战-运用-Dockerfile-构建镜像/
Dockerfile 指令详解请接见:https://www.cnblogs.com/cloudfloating/p/11737447.html
运用 Alpine Linux 作为基础镜像
Alpine 是一个异常轻量的 Linux 镜像,他只要约莫 5MB 的大小,基于它构建镜像,能够大大削减镜像的体积。
Alpine 的 Docker Hub 页面:https://hub.docker.com/_/alpine
docker pull alpine
Alpine 运用 apk
敕令来装置软件包,支撑的软件包列表能够在官网检察:https://pkgs.alpinelinux.org/packages
这里以装置 Nginx 为例,进修镜像的构建。别的 Nginx 自身有官方镜像,pull 即可。
构建 Nginx 镜像
编写 Dockerfile
FROM alpine
RUN apk update \
# 装置 nginx
apk add --no-cache nginx \
mkdir /run/nginx && \
# 消灭缓存
rm -rf /tmp/* /var/cache/apk/*
# 增加容器启动敕令,启动 nginx,以前台体式格局运转
CMD [ "nginx", "-g", "daemon off;" ]
这里有一个坑点,必需建立 /run/nginx
目次,不然会报错。
构建镜像
运用 docker build
敕令构建:
docker build -t nginx-alpine .
在 Dockerfile 目次下实行以上敕令即可构建镜像。-t
参数指定了镜像称号为 nginx-alpine
,末了的 .
示意构建上下文(.
示意当前目次).
在运用 COPY
指令复制文件时,指令中的源途径是相对于构建上下文的(如果指定上下文为 /home
,那末相当于一切的源途径前面都加上了 /home/
)。
如果你的 Dockerfile 文件名不是 “Dockerfile”,能够运用 -f
参数指定。
万万不要将 Dockerfile 放在根目次下构建,如果你将 Dockerfile 放在一个寄存大批视频目次下,而且构建上下文为当前目次,那末镜像将会异常大(视频都被打包进去了)。最好做法是将 Dockerfile 和须要用到的文件放在一个零丁的目次下。
运转容器
运用构建的镜像运转容器:
docker run --name my-nginx -p 80:80 -d nginx-apline
--name
指定容器的称号,能够省略(后续只能经由过程容器 id 来操纵);-p
映照端口,宿主端口 -> 容器端口;-d
背景运转。
运转后接见 http://localhost/
,会涌现一个 nginx 的 404 页面,申明已运转胜利了,由于这里装置的 Nginx 并没有默许页面,/etc/nginx/conf.d/default.conf
中的内容:
# This is a default site configuration which will simply return 404, preventing
# chance access to any other virtualhost.
server {
listen 80 default_server;
listen [::]:80 default_server;
# Everything is a 404
location / {
return 404;
}
}
运用构建的 Nginx 镜像运转一个静态页面
在一个空目次下建立 Nginx 配置文件:
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www;
location / {
index index.html;
}
}
编写一个静态页面:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Hello, Docker!</h1>
</body>
</html>
运用之前构建的镜像构建一个新的镜像:
FROM nginx-alpine
# 拷贝配置文件,掩盖默许的
COPY default.conf /etc/nginx/conf.d/
# 拷贝静态页面
COPY index.html /var/www
构建镜像、运转容器:
docker build -t site .
docker run --name my-site -p 80:80 -d site
如今接见 http://localhost/
,就能够看到 Hello, Docker!