如何自动从系统中删除中间阶段的Docker容器?

Kim*_*kka 3 docker dockerfile

我有Dockerfile,我已承诺使用git repo。我试图分阶段构建容器,并且仅在安装了static go二进制文件的情况下保存最后的容器阶段。

但是,“暂存”容器似乎也已保存到我的系统中。我试图使用--rm标志自动删除它,但没有成功。

这是我的Dockerfile

# Use golang alpine3.7 image for build
FROM golang:1.10.0-alpine3.7
# Maintainer information
LABEL Maintainer="Kimmo Hintikka"
# set working directory to local source
WORKDIR /go/src/github.com/HintikkaKimmo/kube-test-app
# Copy kube-test-app to currect working directory
COPY kube-test-app.go .
# build golang binary from the app source
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o kube-test-app .


# Use Alpine 3.7 as base to mach the build face
FROM alpine:3.7
# Maintainer information
LABEL Maintainer="Kimmo Hintikka"
# Install ca-certificates for HTTPS connections
RUN apk --no-cache add ca-certificates
# Set working directory
WORKDIR /root/
# Copy binary from previous stage. --from=0 means the index of the build action
COPY --from=0 /go/src/github.com/HintikkaKimmo/kube-test-app/kube-test-app .
# Run the binary
CMD [ "./kube-test-app" ]
Run Code Online (Sandbox Code Playgroud)

这是我用来构建它的命令。

docker build --rm github.com/hintikkakimmo/kube-test-app -t kube-test-app
Run Code Online (Sandbox Code Playgroud)

这样可以成功构建,但是还会创建一个附加的无标签TAG <none>容器,这是构建的第一阶段。

~/go/src/github.com/hintikkakimmo/kube-test-app(master*) » docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
kube-test-app       latest              f87087bf2549        8 minutes ago       11.3MB
<none>              <none>              1bb40fa05f27        8 minutes ago       397MB
golang              1.10.0-alpine3.7    85256d3905e2        7 days ago          376MB
alpine              3.7                 3fd9065eaf02        6 weeks ago         4.15MB
alpine              latest              3fd9065eaf02        6 weeks ago         4.15MB
Run Code Online (Sandbox Code Playgroud)

我的Docker版本是:

~ » docker --version               kimmo.hintikka@ie.ibm.com@Kimmos-MacBook-Pro
Docker version 17.12.0-ce, build c97c6d6
Run Code Online (Sandbox Code Playgroud)

tri*_*117 5

您应该这样构建它:

docker build --rm -t kube-test-app .
Run Code Online (Sandbox Code Playgroud)

如果dockerfile位于目录中,或指定dockerfile的路径

docker build --rm -t kube-test-app -f path/to/dockerfile .
Run Code Online (Sandbox Code Playgroud)

-t 是标签,是您构建的Docker映像的名称

要删除除图像和运行容器以外的所有内容,请使用 docker system prune

用于删除图像 docker rmi -f image_name


小智 5

我采取了不同的方法。我在中间容器上设置了标签:

FROM golang:1.14.2 AS builder
LABEL builder=true
Run Code Online (Sandbox Code Playgroud)

当我运行构建时,我只需附加一个命令来查找并销毁包含该标签的图像:

docker build . -t custom-api:0.0.1 && \
  docker rmi `docker images --filter label=builder=true -q`
Run Code Online (Sandbox Code Playgroud)