Dockerfile
- Go course
- Advanced
- Lesson 47/68
- 4 min
Learn to write a Dockerfile for a Go app.
Dockerfile
A Dockerfile is a text file describing step by step how to build an image. The simplest Go Dockerfile:
FROM golang:1.23
WORKDIR /app
COPY . .
RUN go build -o server .
CMD ["./server"]FROM sets the base image, WORKDIR the working folder, COPY the files, RUN the build command and CMD the command run when the container starts. docker build -t app . builds the image.
.dockerignore
COPY . . sends everything in the folder. A .dockerignore file leaves out unneeded or secret files, speeds up builds and protects the cache:
.git
*.env
bin/
node_modules/If you use ENTRYPOINT instead of CMD, arguments given to the container are appended to your program.
Practice Container-ready server
A server running in a container must listen on all interfaces. Write addr(port string) string returning ":" + port. Print addr("8080").
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func addr(port string) string {
return ":" + port
}
func main() {
fmt.Println(addr("8080"))
}Expected output
:8080
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the biggest problem of this single-stage image?
- Go can't compile
- It can't open a port
- The whole Go toolchain stays in the image, making it hundreds of MB Correct answer
- It doesn't run
Explanation: The golang base contains the compiler and libraries (~800 MB); running needs only the binary. Multi-stage builds solve this.
2 Base image
____ golang:1.23
WORKDIR /app
FROM golang:1.23
WORKDIR /app
Explanation: FROM is the first instruction of every Dockerfile and chooses the base image.
3 Instruction and role
| Term | Meaning |
|---|---|
FROM |
Base image |
COPY |
Copies files |
RUN |
Build-time command |
CMD |
Startup command |