Tutorials / Go: From Basics to Production / Building and deploying a Go service

Building and deploying a Go service

14 min read go
Course contents (17 lessons)
  1. Getting started with Go
  2. Installing Go 1.25 and your first program
  3. Variables, types and constants
  4. Control flow: if, for and switch
  5. Functions, multiple returns and defer
  6. Slices and maps
  7. Arrays and slices
  8. Maps and working with strings
  9. Structs, methods and interfaces
  10. Structs, methods and pointers
  11. Interfaces
  12. Errors, packages and generics
  13. Error handling the Go way
  14. Packages and modules
  15. Generics
  16. Concurrency
  17. Goroutines and channels
  18. select, timeouts and context
  19. Mutexes, sync and the race detector
  20. Testing
  21. Testing and benchmarks
  22. Building and shipping a service
  23. Building an HTTP JSON API with net/http
  24. 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 /healthz endpoint 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 vet and go test -race run 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/pprof is 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/sql package.

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.1 inside Docker is not reachable from outside. Listening on :8080 works.
  • 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.

go
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