Docker image creation and optimization Example 2

Create a working directory:

$ mkdir docker_bp2
$ cd docker_bp2
Create a hello.go Go file:
$ cat hello.go
package main
import "fmt"
func main() { fmt.Println("Hello world from Docker!") }
Create Dockerfile:
$ cat Dockerfile 
FROM golang:alpine
WORKDIR /app
ADD . /app
RUN cd /app && go build -o hello-go-docker
ENTRYPOINT ./hello-go-docker
Build image:
$ docker build -t docker-bp2 .
Check image size:
$ docker images | grep  docker-bp2
301MB

Optimize – try multistage build:
$ cat Dockerfile
# build stage
FROM golang:alpine AS build-image
ADD . /src
RUN cd /src && go build -o hello-go-docker
# final stage
FROM alpine
WORKDIR /app
COPY --from=build-image /src/hello-go-docker /app/
ENTRYPOINT ./hello-go-docker
Check image size:
$ docker images | grep  docker-bp2
7.61MB