Implementing multi-stage docker to build smaller and faster Go docker image

Prabesh
Geek Culture
Published in
5 min readMar 4, 2023

--

docker+go

If you’re a developer who wants to kickstart the process of creating a Docker image for your go application, you’ve come to the right place! Docker provides developers with a powerful platform to build, ship, and run applications by utilizing software containers. This guide will help you to create a Docker image for a Go application.

We will be using multi-stage docker build to create an optimal docker image for our GO application.

So let us begin

Stage 1: Compiling and Building Go binary

we first define what image we want to be our base image. This image should be small hence i am using golang:1.19.3-alpine which is smaller in size than just golang:1.19.3

# Stage 1
FROM golang:1.19.3-alpine AS build_base

After that, we define some environment variables. While these env variables are inferred, it good to defined so that readers are aware what varibles are being used when building the base image.

ENV CGO_ENABLED=1
ENV GO111MODULE=on
ENV GOOS=linux
ENV GOARCH=amd64

Once that is done, we add following command to specify our current work directory inside the container. If that directory does not exists, docker creates…

--

--

Prabesh
Geek Culture

Senior Site Reliability Engineer & Backend Engineer | Docker Captain 🐳 | Auth0 Ambassador @Okta | https://www.linkedin.com/in/prabeshthapa