Devops @ MindTickle
yashmehrotra.com
github.com/yashmehrotra
@yashm95
I like tinkering with systems
As per docker's official documentation:
As per docker's official documentation:
Multi-Staged Builds !
Multi-stage builds are a new feature introduced in Docker 17.05
They are useful to anyone who has struggled to optimize Dockerfiles while keeping them easy to read and maintain.
// main.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080
}
FROM golang:latest as base
COPY . /go/src/github.com/org/helloworld
WORKDIR /go/src/github.com/org/helloworld
RUN go get -u github.com/gin-gonic/gin
ENV CGO_ENABLED 0
RUN go build -o HelloWorld main.go
FROM scratch
COPY --from=base /go/src/github.com/org/helloworld/HelloWorld \
/usr/bin/HelloWorld
EXPOSE 8080
ENTRYPOINT ["HelloWorld"]
Lets build a hello world image for golang using both multi-staged and normal builds
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
# requirements.txt
Flask==1.0.2
gunicorn==19.9.0
FROM python:3.6-alpine as base
RUN apk update && apk add build-base
COPY . /code/
WORKDIR /code
RUN pip install -r requirements.txt
FROM python:3.6-alpine
COPY --from=base /code/ /code
COPY --from=base /usr/local/lib/python3.6 /usr/local/lib/python3.6
COPY --from=base /usr/local/bin/gunicorn /usr/local/bin/gunicorn
WORKDIR /code
ENTRYPOINT ["gunicorn", "-b 0.0.0.0:8000", "app:app"]
Name | Old Size | New Size |
---|---|---|
Jafa (Node) | 966 MB | 199 MB |
Bailey (Node) | 943 MB | 176 MB |
MT Login Provider (Golang) |
705 MB | 16 MB |
Use slim images from docker hub
If you can compromise on performance, alpine base images can also be used
Separate out compile-time and run-time dependencies
Add compile-time dependencies in builder image
If you have assets (images, binaries) in your code-base, you can remove them as well
Keep in mind is that using multi-stage will not impact the build time of the image
Multi-stage builds are useful where space is a constraint, and whilst it is always better to build small concise containers, it is easy to get carried away trying to shave off a few megabytes.
Even though they are great to use, they shouldn’t be abused, the effort should always spent be towards improving the workflow.
Golang: https://github.com/MindTickle/devops-grpc-go-boilerplate
Scala (with Play Framework): https://github.com/MindTickle/devops-scala-play-boilerplate
Python: https://github.com/MindTickle/devops-python-boilerplate
yashmehrotra.com
github.com/yashmehrotra
@yashm95