Dockerfile 基础

docker镜像构建需要至少一条FROM指令,表明从什么基础开始打架镜像,空镜像FROM scratch, scratch不是一个可拉取的镜像,相当于一个关键字。最小的linux运行系统可以FROM busybox开始搭建。

多阶段构建:一个Dockerfile可以多个From, 最后一个From生效,前面的可以AS别名,多用于构建最终运行的bin文件,COPY可以从前面的From阶段中拷贝文件。

官方示例:

# syntax=docker/dockerfile:1
FROM golang:1.16-alpine AS build

# Install tools required for project
# Run `docker build --no-cache .` to update dependencies
RUN apk add --no-cache git
RUN go get github.com/golang/dep/cmd/dep

# List project dependencies with Gopkg.toml and Gopkg.lock
# These layers are only re-built when Gopkg files are updated
COPY Gopkg.lock Gopkg.toml /go/src/project/
WORKDIR /go/src/project/
# Install library dependencies
RUN dep ensure -vendor-only

# Copy the entire project and build it
# This layer is rebuilt when a file changes in the project directory
COPY . /go/src/project/
RUN go build -o /bin/project

# This results in a single layer image
FROM scratch
COPY --from=build /bin/project /bin/project
ENTRYPOINT ["/bin/project"]
CMD ["--help"]

COPY --from=build 这里的from参数就指定从前面的构建阶段中拷贝数据,这样一个docker build命令可以完成构建测试和镜像生成, 并且这个构建环境是跨平台的。

scratch环境只能运行无任何依赖的二进制,go天生有这方面的优势,如果是标准C编译的二进制,是有动态库依赖的,不能直接运行, 需要FROM ubuntu才能运行。官方提供了C的依赖写法,参考:https://github.com/docker-library/hello-world

标签: docker

添加新评论