File tree Expand file tree Collapse file tree 2 files changed +26
-4
lines changed Expand file tree Collapse file tree 2 files changed +26
-4
lines changed Original file line number Diff line number Diff line change 1
- FROM golang:1.9-alpine
1
+ FROM golang:1.9-alpine as builder
2
2
3
3
RUN apk --no-cache add git
4
4
@@ -10,7 +10,7 @@ COPY app.go .
10
10
11
11
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
12
12
13
- FROM alpine:latest
13
+ FROM alpine:latest as prod
14
14
15
15
RUN apk --no-cache add ca-certificates
16
16
Original file line number Diff line number Diff line change @@ -134,7 +134,7 @@ go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
134
134
编写 ` Dockerfile ` 文件
135
135
136
136
``` docker
137
- FROM golang:1.9-alpine
137
+ FROM golang:1.9-alpine as builder
138
138
139
139
RUN apk --no-cache add git
140
140
@@ -146,7 +146,7 @@ COPY app.go .
146
146
147
147
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
148
148
149
- FROM alpine:latest
149
+ FROM alpine:latest as prod
150
150
151
151
RUN apk --no-cache add ca-certificates
152
152
@@ -175,3 +175,25 @@ go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
175
175
```
176
176
177
177
很明显使用多阶段构建的镜像体积小,同时也完美解决了上边提到的问题。
178
+
179
+ #### 只构建某一阶段的镜像
180
+
181
+ 我们可以使用 ` as ` 来为某一阶段命名,例如
182
+
183
+ ``` dockerfile
184
+ FROM golang:1.9-alpine as builder
185
+ ```
186
+
187
+ 例如当我们只想构建 ` builder ` 阶段的镜像时,我们可以在使用 ` docker build ` 命令时加上 ` --target ` 参数即可
188
+
189
+ ``` bash
190
+ $ docker build --target builder -t username/imagename:tag .
191
+ ```
192
+
193
+ #### 构建时从其他镜像复制文件
194
+
195
+ 上面例子中我们使用 ` COPY --from=0 /go/src/github.com/go/helloworld/app . ` 从上一阶段的镜像中复制文件,我们也可以复制任意镜像中的文件。
196
+
197
+ ``` dockerfile
198
+ $ COPY --from=nginx:latest /etc/nginx/nginx.conf /nginx.conf
199
+ ```
You can’t perform that action at this time.
0 commit comments