The base image has Go, but nothing of the shop. COPY copies files from the shop's folder on your computer, where you run docker build, into the image: COPY source destination. A . as the destination is the image's current folder, /app thanks to WORKDIR; with two sources or more, the destination ends with /, like ./. RUN runs a command inside the image while it is being built, and keeps what the command changed. go mod download downloads the modules go.mod lists, and go build -o shop . compiles the code in the current folder into a program named shop.
Each line of a Dockerfile makes a layer, a saved change to the image, and Docker keeps the layers in a cache. On the next build it reuses a layer, CACHED, as long as the line and the files it copies have not changed. From the first line that changed, every line runs again. So the order matters: what changes rarely goes at the top, what changes often at the bottom.
Here is the same idea for a program built on Node.js: its package list, package.json, is copied and installed first, and the code last.
var dockerfile = `
FROM node:22-slim
WORKDIR /srv
COPY package.json ./
RUN npm install
COPY . .
`
The check builds your image, then changes main.go and builds again. When your lines are right, it prints:
$ docker build -t shop . [1/7] FROM golang:1.23 [2/7] WORKDIR /app [3/7] ENV CGO_ENABLED=0 [4/7] COPY go.mod go.sum ./: copies go.mod, go.sum into /app [5/7] RUN go mod download: downloads modernc.org/sqlite v1.34.5 and the modules it needs [6/7] COPY . .: copies main.go, go.mod, go.sum, Dockerfile into /app [7/7] RUN go build -o shop .: compiles the shop into /app/shop In the image: /app/go.mod, /app/go.sum, /app/main.go, /app/Dockerfile, /app/shop You change main.go and build again: [1/7] FROM golang:1.23: CACHED [2/7] WORKDIR /app: CACHED [3/7] ENV CGO_ENABLED=0: CACHED [4/7] COPY go.mod go.sum ./: CACHED [5/7] RUN go mod download: CACHED [6/7] COPY . .: runs again, main.go changed [7/7] RUN go build -o shop .: runs again, because a line above it ran again go mod download was CACHED: a change to the code does not download the modules again
Your task: after the three lines of the base, add four lines inside the backticks of dockerfile: copy go.mod and go.sum into the current folder, download the modules with go mod download, copy the whole shop folder into the current folder, then compile the shop with go build -o shop .. A change to main.go must leave the download CACHED.
Assignment
Follow the Coding Tutorial to add the COPY, RUN, COPY and RUN lines to the shop's Dockerfile, in that order.
Hint
In COPY source destination, a dot as the source means everything in the shop's folder, and a dot as the destination means /app. Go can only read go.mod once a line above it has copied the file in.
Free plan: 30 tutor messages. PRO is unlimited.
