How to dockerize Go application

Introduction

When you develop an application then you need to dockerize your application.

Guide

Create an application, say Hello world under ./cmd/test/main.go.

1
go mod init test
1
2
3
4
5
6
7
package main

import "fmt"

func main() {
fmt.Println("Hello world")
}

Create Dockerfile to dockerize application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
FROM golang:alpine AS builder

WORKDIR /src

COPY go.mod go.sum ./
RUN go mod download

COPY ./cmd ./cmd

RUN go build -o app ./cmd/test

FROM alpine:3

WORKDIR /app

COPY --from=builder /src/app ./

ENTRYPOINT ./app

Build docker image following command.

1
docker build -t test:latest .

Run docker image following command.

1
docker run -it --rm test:latest

Then should print Hello world on terminal.

Conclusion

The multiple stage is important in Dockerfile. It can optimize size of docker image.