Start learning free

LESSON 150 OF 173 · BACKEND: SHIPPING IT

A Dockerfile: The Base Image in Go

Practice

To run the shop the same way on any server, you pack it into a Docker image: a snapshot of a small Linux system with Go, the modules and your code in it. A container is that image running. The recipe for an image is a file named Dockerfile, one instruction per line. Here you write its text as the Go string dockerfile, between backticks: in a raw string, each line you type is one line of the file, with no quotes and no \n.

A Dockerfile starts with FROM, the image you build on, written name:tag: the tag after the colon is the version. WORKDIR picks the folder where the next lines work and the app runs later; Docker creates it if it is missing. ENV sets an environment variable, the kind os.Getenv reads, written NAME=value. Here is the start of a Dockerfile for another program, built on Node.js:

var dockerfile = `
FROM node:22-slim
WORKDIR /srv
ENV TZ=UTC
`

One variable matters for Go. Some packages call code written in C through cgo, and a program built that way needs the C library of the image to run. The shop's SQLite driver, modernc.org/sqlite, is written in Go, so with CGO_ENABLED=0 go build makes a program that needs no C library.

The check reads your lines the way docker build would. When they are right, it prints:

$ docker build -t shop .
[1/3] FROM golang:1.23: starts from a Debian Linux with Go 1.23 installed: the tools that build the shop
[2/3] WORKDIR /app: makes the folder /app and works in it; the next lines and the app run there
[3/3] ENV CGO_ENABLED=0: sets CGO_ENABLED for every program in the image, so go build makes a program that needs no C library (modernc.org/sqlite is written in Go)
The base is ready: golang:1.23, working in /app. The files of the shop come next.

Your task: write three lines inside the backticks of dockerfile: start FROM the official Go image, golang, version 1.23; work in the folder /app; and set CGO_ENABLED to 0.


Assignment
Follow the Coding Tutorial to write the first three lines of the shop's Dockerfile: FROM, WORKDIR and ENV.


Hint
Inside the backticks you write the file's lines as they are: no quotes, no \n, one instruction per line. Write the folder as a full path that starts with /, and NAME=value with no spaces around =.


STEP 1 OF 3
    Ctrl + Enter to check

    Ship Dockerfile Base in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free