Skip to content

Commit 0db00b9

Browse files
committed
Update Dockerfile multistage-builds yeasy#320
1 parent 3b59591 commit 0db00b9

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

image/demo/multistage-builds/Dockerfile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM golang:1.9-alpine
1+
FROM golang:1.9-alpine as builder
22

33
RUN apk --no-cache add git
44

@@ -10,7 +10,7 @@ COPY app.go .
1010

1111
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
1212

13-
FROM alpine:latest
13+
FROM alpine:latest as prod
1414

1515
RUN apk --no-cache add ca-certificates
1616

image/multistage-builds.md

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
134134
编写 `Dockerfile` 文件
135135

136136
```docker
137-
FROM golang:1.9-alpine
137+
FROM golang:1.9-alpine as builder
138138
139139
RUN apk --no-cache add git
140140
@@ -146,7 +146,7 @@ COPY app.go .
146146
147147
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .
148148
149-
FROM alpine:latest
149+
FROM alpine:latest as prod
150150
151151
RUN apk --no-cache add ca-certificates
152152
@@ -175,3 +175,25 @@ go/helloworld 1 f55d3e16affc 2 minutes ago 295MB
175175
```
176176

177177
很明显使用多阶段构建的镜像体积小,同时也完美解决了上边提到的问题。
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+
```

0 commit comments

Comments
 (0)