Building and deploying a Go service
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
The best part of Go
Deploying a Go program is pleasantly boring. The compiler produces one executable file with everything inside it. No interpreter, no virtual environment, no pile of dependencies on the server. You copy a file and run it. This lesson covers the practical steps.
Building
go build -o tasks-api .
./tasks-api
The result is a native executable for your own operating system. To build for another one, set two environment variables. This is called cross-compilation, and Go does it out of the box:
# build for a Linux server from Windows (PowerShell)
$env:GOOS = "linux"; $env:GOARCH = "amd64"; go build -o tasks-api .
# the same from macOS or Linux
GOOS=linux GOARCH=amd64 go build -o tasks-api .
Common combinations are linux/amd64, linux/arm64 (many cloud machines and Raspberry Pis), windows/amd64 and darwin/arm64. If you set the variables in PowerShell, remember to clear them afterwards, or all later builds will target Linux.
Smaller, reproducible binaries
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=1.0.0" -o tasks-api .
Each option has a purpose. CGO_ENABLED=0 turns off C bindings, producing a fully static binary that runs on any Linux, even in a container with nothing else in it. -trimpath removes your local folder paths from the binary. -ldflags="-s -w" strips debug tables and symbols, making the file about a quarter smaller. The -X main.version=1.0.0 part sets a string variable at build time, so that the program can report its version:
var version = "dev" // overwritten by -X at build time
// in main():
slog.Info("starting", "version", version)
Configuration from the environment
Do not hard-code ports, database addresses or secrets. Read them from environment variables, which every platform supports. We did this already with PORT. A small helper keeps it tidy:
func env(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
addr := ":" + env("PORT", "8080")
dsn := env("DATABASE_URL", "")
Never commit secrets to Git. On a server, put them in the service definition or a secrets manager, and fail at startup with a clear message if a required one is missing.
Docker: a small image
A multi-stage Dockerfile builds in a full Go image and copies only the binary into a tiny final image.
FROM golang:1.25 AS build
WORKDIR /src
COPY go.mod go.sum* ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/tasks-api .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/tasks-api /tasks-api
EXPOSE 8080
ENTRYPOINT ["/tasks-api"]
docker build -t tasks-api .
docker run --rm -p 8080:8080 -e PORT=8080 tasks-api
The first stage compiles. The second starts from a minimal base image that has no shell and no package manager, runs as a non-root user, and ends up around 10 to 15 MB in total. Copying go.mod and downloading dependencies before copying the rest of the source means Docker can cache the downloads, so rebuilds after a code change are fast.
Running on a plain Linux server
You do not need containers. Copy the binary to the server, for example to /opt/tasks-api/, and run it as a service with systemd. Create /etc/systemd/system/tasks-api.service:
[Unit]
Description=Tasks API
After=network.target
[Service]
ExecStart=/opt/tasks-api/tasks-api
Environment=PORT=8080
User=tasksapi
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now tasks-api
sudo systemctl status tasks-api
journalctl -u tasks-api -f
systemd starts the program at boot, restarts it if it crashes, and collects everything it writes to the standard output or error, which you read with journalctl. That is why our slog logger writes to the console, with no log files to rotate. When you deploy a new version, replace the binary and run sudo systemctl restart tasks-api. The graceful shutdown code from the previous lesson lets running requests finish.
Put a proxy in front
For public traffic, run a reverse proxy such as Caddy or nginx in front of your service. It handles HTTPS certificates, compression and slow clients, and forwards requests to localhost:8080. Go can serve HTTPS itself, but a proxy makes certificate renewal and multiple sites easier.
Production checklist
- Server timeouts are set, and shutdown is graceful.
- There is a
/healthzendpoint for load balancers and monitors. - Logs are structured and go to standard output.
- Configuration comes from the environment, and secrets are not in the repository.
- Tests,
go vetandgo test -racerun in CI before every deploy. - You can see memory and CPU use, and know what a normal day looks like. For deeper profiling,
net/http/pprofis built in. Keep it off the public port. - Data does not live only in memory. Our task API loses everything on restart, so a real service would use a database such as PostgreSQL through the
database/sqlpackage.
Common mistakes
- Building with CGO enabled and copying the binary into an image without the C libraries. It fails with a confusing "not found" error even though the file exists. Set
CGO_ENABLED=0. - Forgetting GOOS and GOARCH, and uploading a Windows executable to a Linux server.
- Binding to localhost in a container. A server listening on
127.0.0.1inside Docker is not reachable from outside. Listening on:8080works. - Running as root when you do not need to.
- No restart policy. A crash at night then means downtime until someone notices.
Try it yourself
Build the tasks API for Linux with the flags above, and compare its size with a plain go build. Write the Dockerfile, build the image and check that curl localhost:8080/healthz responds. Add a version variable set with -ldflags and return it from the health endpoint. Finally, stop the container with docker stop and look at the logs to check that your graceful shutdown message appears.
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=1.0.0" -o tasks-api .
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account