DEV Community

pop for Pronto Tools

Posted on

6 4

มา Optimize docker builds ด้วย multi-stage กันเถอะ

Multi-stage คือ

เทคนิคที่ช่วยให้เราสามารถ optimize ระยะเวลาในการ build image ซ้ำ แทนที่เราจะ มา build image ใหม่ทุกครั้ง ก็เปลี่ยนมาใช้การ copy image ที่เคย build ไปแล้วมาใช้กับ stage ใหม่แทน

Note: Multi-Stage สามารถใช้งานได้กับ Docker edge version เวอร์ชั่น v17.05.0ce ขึ้นไป

หากเปรียบเทียบกับความเป็นจริง Multi-Stage ก็คล้ายกับแก้วใบหนึ่งที่เป็นเหมือน blue print(พิมพ์เขียว) ให้เราสามารถนำมา Reuse ได้ แทนจะเราจะผลิตแก้วกระดาษที่ซ้ำทุกครั้ง

compare with the real world

ลองกันเลย 🚩

เริ่มต้นด้วยการสร้าง Dockerfile สำหรับ dev และDockerfile สำหรับ production
ฺBuild without multi-stage

หลังจากนั้นลองสั่ง build ทั้งสอง images โดยใช้คำสั่ง

docker build -t demo-dev -f Dockerfile-dev .
docker build -t demo-prod -f Dockerfile-production .
Enter fullscreen mode Exit fullscreen mode

โดยผลลัพธ์ที่ได้คือ

| Docker Tags     | Size   |
|-----------------|--------|
| demo-dev        | 994MB  |
| demo-prod       | 996MB  |
| Summary         | 1.99GB |

Enter fullscreen mode Exit fullscreen mode

หลังจากนั้นเราลองมาใช้ Multi-Stage กันบ้าง ✨
DockerfileMuti-stage

ลองสั่ง build images โดยใช้คำสั่ง

docker build -t demo-multi-stage -f Dockerfile-muti-stage .
Enter fullscreen mode Exit fullscreen mode

โดยผลลัพธ์ที่ได้คือ

| Docker Tags      | Size   |
|------------------|--------|
| demo-multi-stage | 1.01GB |

Enter fullscreen mode Exit fullscreen mode

จะเห็นได้ว่าขนาด image ที่ถูก build ลดลงไปถึง 0.98 GB 🎉

โดยวิธีการ เขียน docker multi-stage ง่ายมาก เพียงแค่ใช้คำสั่ง

copy --from=<index stage or stage name> <destination path> <original path>
Enter fullscreen mode Exit fullscreen mode

Syntax Multistage

Summary

Muti stage เป็นอีกหนึ่งวิธีที่จะช่วยเพิ่มทางเลือกให้กับคุณในการ ลดขนาดของ image ที่จะช่วยให้ image ของคุณ lean ขึ้นและยังช่วยลดระยะเวลาในการ build image ได้อีกด้วย

Ref:

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
heyfirst profile image
First Kanisorn Sutham

Coooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooool

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more