Skip to content

Commit ff57916

Browse files
authored
Merge pull request Tikam02#161 from s403o/master
Add multi-stage-builds to docker tutorial :)
2 parents a5adafe + 025a860 commit ff57916

44 files changed

Lines changed: 49 additions & 8 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Container-orchestration/Docker/readme.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
4. [Writing Dockerfile](#4-writing-dockerfile)
88
5. [Running Docker Image](#5-runnig-up-the-docker-image)
99
6. [Push to Docker-hub](#6-pushing-image-to-dockerhub)
10+
7. [Use multi-stage builds](#7-Use-multi-stage-builds)
1011

1112

1213
*****************
@@ -244,4 +245,44 @@ sudo apt-get install docker.io
244245
``` $ docker run --name nodejs-image-demo -p 80:8080 -d your_dockerhub_username/nodejs-image-demo ```
245246

246247

248+
## 7 Use multi-stage builds
249+
- With multi-stage builds, you use multiple ``` FROM ``` statements in your Dockerfile. Each ``` FROM ``` instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image, also you can name your stages, by adding an ```AS <NAME>``` to the ```FROM``` instruction To show how this works, let’s adapt the Dockerfile to use multi-stage builds.
247250

251+
252+
[Dockerfile](https://github.com/s403o/GoViolin/blob/master/Dockerfile):
253+
```
254+
### stage 1 (build) ###
255+
FROM golang:alpine3.15 as build
256+
257+
# set working directory
258+
RUN mkdir -p /app
259+
WORKDIR /app
260+
261+
# install app dependencies
262+
RUN go mod init github.com/Rosalita/GoViolin
263+
264+
# add app
265+
COPY . /app
266+
267+
# listener port at runtime
268+
EXPOSE 3000
269+
270+
# build
271+
RUN go build -o go
272+
273+
# test
274+
HEALTHCHECK --interval=1m --timeout=20s --start-period=30s --retries=3 \
275+
CMD go test || exit 1
276+
277+
### stage 2 (run) ###
278+
FROM alpine as production
279+
280+
WORKDIR /app
281+
COPY --from=build /app .
282+
283+
# run
284+
ENTRYPOINT [ "./go" ]
285+
```
286+
- The end result is the same tiny production image as before, with a significant reduction in complexity.
287+
How does it work? The second ```FROM``` instruction starts a new build stage with the ```alpine as production``` image as its base. The ```COPY --from=build /app .``` line copies just the built artifact from the previous stage into this new stage. The Go SDK and any intermediate artifacts are left behind, and not saved in the final image.
288+
- You can check the final image from this link [s403o/goapp](https://hub.docker.com/r/s403o/goapp/tags) the final size is 50MB! :)

img/1-physical-layer.svg

Lines changed: 1 addition & 1 deletion
Loading

0 commit comments

Comments
 (0)