Docker from Scratch?

Viewed 1148

How to build a docker from scratch image?

2 Answers

Docker "FROM scratch" is a concept where you build a docker image from scratch without using any base image. The scratch image is an empty image with no layers. This is useful when you want to build a minimal docker image. It's a good fit for go applications because go binaries can be statically linked without any dependencies. This means you can build a docker image with just the go binary and nothing else. The final image size will be very small.

Here's an example repository:

https://github.com/calmdev/go-docker-from-scratch

To try it – clone the repository and re-open in devcontainer.

This repository contains a simple go web server application with a single "Hello, World!" route. The Dockerfile in this repository builds a docker image from scratch and copies the go binary into the image. The final compressed image size is only 2.1MB. This is a very small image size compared to a typical image.

The Dockerfile is shown below:

# https://hub.docker.com/_/scratch
FROM scratch

# Copy the web binary to the container.
COPY bin/web /

# Run the web binary.
CMD ["/web"]

The Dockerfile is very simple. It uses the scratch image as the base image. The COPY command copies the go binary from the bin directory to the root directory of the container. The CMD command runs the go binary when the container starts.

To build the docker image, use the following command:

make build

To build and run the docker image, use the following command:

make run

The make run command will build the docker image and run the container. The container will start the go web server on the port defined within the .devcontainer/.env file which by default is 8090. You can access the web server by opening a browser and navigating to http://localhost:8090. You should see the "Hello, World!" message displayed on the page.

depending on your use case you may want to add root cert chain and timezone info:

ADD ca-certificates.crt /etc/ssl/certs/
COPY zoneinfo.zip /usr/local/go/lib/time/zoneinfo.zip

update the cert with:
wget -O ca-certificates.crt https://curl.se/ca/cacert.pem

zoneinfo is in $GOROOT/lib/time/zoneinfo.zip